Best Python code snippet using localstack_python
signals.py
Source:signals.py
1import logging2from django.contrib.contenttypes.models import ContentType3from django.db.models.signals import post_save, post_delete, pre_save4from usermodel.models import User5from myprofile.models import ProfileUnits6#from mysearches.models import SavedSearch7from solr.models import Update8logging.basicConfig()9logger = logging.getLogger(__name__)10def presave_solr(sender, instance, *args, **kwargs):11 """12 Flag an instance for being uploaded to solr in the post-save if anything13 we actually care about has been changed.14 """15 ignore_fields = ['last_modified', 'last_response', 'last_sent',16 'date_updated', 'last_login', 'date_joined']17 setattr(instance, 'solr_update', False)18 if instance.pk:19 # The instance might have a pk but still not actually20 # exist (eg: loading fixtures).21 try:22 obj = sender.objects.get(pk=instance.pk)23 except sender.DoesNotExist:24 setattr(instance, 'solr_update', True)25 return26 for field in obj._meta.fields:27 current_val = getattr(obj, field.attname)28 new_val = getattr(instance, field.attname)29 try:30 if field.attname not in ignore_fields and current_val != new_val:31 setattr(instance, 'solr_update', True)32 except TypeError, e:33 logger.error("%s for field %s" % (e, field.attname))34 setattr(instance, 'solr_update', True)35 else:36 setattr(instance, 'solr_update', True)37def prepare_add_to_solr(sender, instance, **kwargs):38 """39 Converts an object instance into a dictionary and adds it to solr.40 """41 if getattr(instance, 'solr_update', None):42 if sender in ProfileUnits.__subclasses__():43 content_type_id = ContentType.objects.get_for_model(ProfileUnits).pk44 object_id = instance.user_id45 else:46 content_type_id = ContentType.objects.get_for_model(sender).pk47 object_id = instance.pk48 uid = "%s##%s" % (content_type_id, object_id)49 obj, _ = Update.objects.get_or_create(uid=uid)50 obj.delete = False51 obj.save()52def prepare_delete_from_solr(sender, instance, **kwargs):53 """54 Removes and object instance from solr.55 """56 if sender in ProfileUnits.__subclasses__():57 content_type_id = ContentType.objects.get_for_model(ProfileUnits).pk58 object_id = instance.user_id59 # If there are existing ProfileUnits for a user, since all ProfileUnits60 # are in the same solr document, update the document rather than61 # removing it.62 if ProfileUnits.objects.filter(user_id=instance.user_id).exclude(63 pk=instance.pk):64 prepare_add_to_solr(sender, instance, **kwargs)65 return66 else:67 content_type_id = ContentType.objects.get_for_model(sender).pk68 object_id = instance.pk69 uid = "%s##%s" % (content_type_id, object_id)70 obj, _ = Update.objects.get_or_create(uid=uid)71 obj.delete = True72 obj.save()73def profileunits_to_dict(user_id):74 """75 Creates a dictionary of profile units for a user.76 inputs:77 :user_id: the id of the user the dictionary is being created for78 """79 content_type_id = ContentType.objects.get_for_model(ProfileUnits).pk80 solr_dict = {81 'uid': "%s##%s" % (content_type_id, user_id),82 'ProfileUnits_user_id': user_id,83 }84 models = {}85 units = ProfileUnits.objects.filter(user_id=user_id).select_related('basicinfo',86 'education',87 'experience',88 'skill',89 'social',90 'content_type')91 for unit in units:92 unit = getattr(unit, unit.get_model_name())93 models.setdefault(unit.__class__.__name__, []).append(unit)94 for model_name, objs in models.items():95 if not objs:96 continue97 # if model_name == 'Address':98 # solr_dict['Address_region'] = ["%s##%s" %99 # (getattr(obj, 'country_code'),100 # getattr(obj, 'country_sub_division_code'))101 # for obj in objs]102 # solr_dict['Address_full_location'] = ["%s##%s##%s" %103 # (getattr(obj, 'country_code'),104 # getattr(obj, 'country_sub_division_code'),105 # getattr(obj, 'city_name'))106 # for obj in objs]107 for field in objs[0]._meta.fields:108 obj_list = [getattr(obj, field.attname) for obj in objs]109 field_type = field.get_internal_type()110 if (field_type != 'OneToOneField' and111 not any(s in field.attname112 for s in ['password', 'timezone',113 'deactivate_type'])):114 field_name = "%s_%s" % (model_name, field.attname)115 solr_dict[field_name] = filter(None, list(obj_list))116 return solr_dict117def object_to_dict(model, obj):118 """119 Turns an object into a solr compatible dictionary.120 inputs:121 :model: the model for the object122 :object: object being converted into a solr dictionary123 """124 content_type_id = ContentType.objects.get_for_model(model).pk125 object_id = obj.pk126 solr_dict = {127 'uid': "%s##%s" % (content_type_id, object_id),128 }129 # if model == SavedSearch:130 # if obj.user:131 # solr_dict['SavedSearch_company_id'] = obj.get_company()132 # for field in User._meta.fields:133 # field_type = field.get_internal_type()134 # if (field_type != 'OneToOneField' and135 # not any(s in field.attname136 # for s in ['password', 'timezone',137 # 'deactivate_type'])):138 # field_name = "User_%s" % field.attname139 # solr_dict[field_name] = getattr(obj.user, field.attname)140 # else:141 # return None142 for field in model._meta.fields:143 field_type = field.get_internal_type()144 if (field_type != 'OneToOneField' and145 not any(s in field.attname146 for s in ['password', 'timezone',147 'deactivate_type', 'last_modified'])):148 field_name = "%s_%s" % (model.__name__, field.attname)149 solr_dict[field_name] = getattr(obj, field.attname)150 return solr_dict151post_save.connect(prepare_add_to_solr, sender=User,152 dispatch_uid="user")153post_delete.connect(prepare_delete_from_solr, sender=User,154 dispatch_uid='user')155pre_save.connect(presave_solr, sender=User)156# post_save.connect(prepare_add_to_solr, sender=SavedSearch,157# dispatch_uid='savedsearch')158# post_delete.connect(prepare_delete_from_solr, sender=SavedSearch,159# dispatch_uid='savedsearch')160# pre_save.connect(presave_solr, sender=SavedSearch)161for model_class in ProfileUnits.__subclasses__():162 pre_save.connect(presave_solr, sender=model_class)163 post_save.connect(prepare_add_to_solr,164 sender=model_class,165 dispatch_uid="att_post_save_"+model_class.__name__)166 post_delete.connect(prepare_delete_from_solr,167 sender=model_class,...
button.py
Source:button.py
1import pygame as pg2from source.load.comp import ImageAnimation, Surface3pg.init()4class Button(Surface):5 def __init__(self, pos: tuple[int, int], hitbox_size: tuple[int, int], deactivation_assets, on_hover_assets, activation_assets=None, speed: tuple[int, int, int] = (0.1, 0.1, 0.1)):6 x, y = pos7 hw, hh = hitbox_size8 super().__init__(x, y, hw, hh, None, True)9 deactivation_state = ImageAnimation(deactivation_assets, self.rect.centerx, self.rect.centery, speed[0])10 on_hover_state = ImageAnimation(on_hover_assets, self.rect.centerx, self.rect.centery, speed[1])11 activation_state = ImageAnimation(activation_assets, self.rect.centerx, self.rect.centery, speed[2]) if activation_assets is not None else None12 self.animation_list = [deactivation_state, on_hover_state, activation_state]13 self.activated_by_click = False14 self.activated_by_key = False15 self.is_on_hover = False16 def toggle_animation(self, animation_type: int):17 """18 animation_type:19 - 0: deactivation animation20 - 1: on hover animation21 - 2: activation animation22 """23 self.animation_list[animation_type].toggle_animation()24 def check_click(self, click_type: int):25 '''26 click_type:27 - 0: left click28 - 1: middle click29 - 2: right click30 '''31 self.check_hover()32 self.activated_by_click = self.is_on_hover and pg.mouse.get_pressed()[click_type]33 def check_key_activate(self, key):34 keys = pg.key.get_pressed()35 self.activated_by_key = keys[key]36 def check_hover(self):37 self.is_on_hover = self.rect.collidepoint(pg.mouse.get_pos())38 def deactivate_button(self, deactivate_type: int):39 """40 0: both activated_by_click and activated_by_key41 1: activated_by_click42 2: activated_by_key43 """44 match deactivate_type:45 case 0:46 self.activated_by_click = self.activated_by_key = False47 case 1:48 self.activated_by_click = False49 case 2:50 self.activated_by_key = False51 def is_activated(self, check_type: int):52 """53 0: both is_activated_by_click and activated_by_key54 1: activated_by_click or activated_by_key55 2: activated_by_click56 3: activated_by_key57 """58 match check_type:59 case 0:60 return self.activated_by_click and self.activated_by_key61 case 1:62 return self.activated_by_click or self.activated_by_key63 case 2:64 return self.activated_by_click65 case 3:...
PGraph.py
Source:PGraph.py
...26 key = get_key_with_file_in_path(filename, self.active_nodes)27 if key is not None:28 self.active_nodes[key] = self.all_nodes[key]29 self.mode = '?'30 def deactivate_type(self, type):31 self.active_nodes = {name:node for name,node in self.active_nodes.items() if not isinstance(node, type)}32 self.mode = '?'33 def activate_type(self, type):34 self.active_nodes |= {name:node for name,node in self.all_nodes.items() if isinstance(node, type)}35 self.mode = '?'36 def method_mode(self):37 pass38 def class_mode(self):39 pass40 def file_mode(self):41 self.deactivate_type(DirNode)42 self.activate_type(FileNode)43 self.mode = 'file'44 def dir_mode(self):45 self.deactivate_type(FileNode)46 self.activate_type(DirNode)47 self.mode = 'dir'48 def up(self):49 pass50 def down(self):...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!