ngram
listlengths 0
67.8k
|
|---|
[
"verb = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True,",
"the rest for field in ('verb', 'description', 'timestamp', 'extra'): data[field] = kwargs[field] return",
"@actor.setter def actor(self, actor): obj_ct, obj_id = _get_gfk(actor) self.actor_content_type = obj_ct self.actor_object_id =",
"*action_objects): return self._get_gfks('action_object', *action_objects) def model_actions(self, model): ct = ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct),",
"def model_actions(self, model): ct = ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), ) def",
"target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data, ) class EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING,",
"@action_object.setter def action_object(self, action_object): if action_object: obj_ct, obj_id = _get_gfk(action_object) self.action_object_content_type = obj_ct",
"= timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC', 'Z', 1) return timestamp def _format_description(kwargs, description_template): context",
"0 update.queryset_only = True # type: ignore def _get_gfks(self, field, *objects): ct =",
"def targets(self, *targets): return self._get_gfks('target', *targets) def action_objects(self, *action_objects): return self._get_gfks('action_object', *action_objects) def",
"short string, preferrably an infinitive. It should not duplicate information about the model",
"= ('-timestamp',) def __str__(self): return self.description def delete(self, **_): # Deletion not allowed",
"if obj_ct and obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id) return obj def _serialize_gfk(obj): if not",
"targets(self, *targets): return self._get_gfks('target', *targets) def action_objects(self, *action_objects): return self._get_gfks('action_object', *action_objects) def model_actions(self,",
"obj = delazify_object(obj) objstring = repr(obj).strip('<>') return objstring def _format_timestamp(timestamp): \"Print timestamp in",
"def action_object(self, action_object): if action_object: obj_ct, obj_id = _get_gfk(action_object) self.action_object_content_type = obj_ct self.action_object_object_id",
"verb, target=None, action_object=None, description_template='', timestamp=None, extra=None, using=None): \"\"\"Log event `actor`, `target` and `action_object`",
"models.TextField(blank=True, null=True, db_index=True) action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object', db_index=True) action_object_object_id =",
"('-timestamp',) def __str__(self): return self.description def delete(self, **_): # Deletion not allowed return",
"def _get_remote_obj(obj_ct, obj_id): if obj_ct and obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id) return obj def",
"= repr(obj).strip('<>') return objstring def _format_timestamp(timestamp): \"Print timestamp in JSON serializer compatible format\"",
"data['target'] = _serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object']) # copy the rest for field in",
"obj in objects: if not obj: continue obj_ct, obj_id = _get_gfk(obj) lookups =",
"'action_object': { 'ct': 'action_object_content_type', 'id': 'action_object_object_id' }, } Q = models.Q def _get_gfk(obj):",
"'id': 'target_object_id'}, 'action_object': { 'ct': 'action_object_content_type', 'id': 'action_object_object_id' }, } Q = models.Q",
"data['actor'] = _serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object']) # copy the rest",
"return self._get_gfks('actor', *actors) def targets(self, *targets): return self._get_gfks('target', *targets) def action_objects(self, *action_objects): return",
"self.filter(reduce(or_, q_objs)) def actors(self, *actors): return self._get_gfks('actor', *actors) def targets(self, *targets): return self._get_gfks('target',",
"actor_object_id = models.TextField(db_index=True) verb = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True, null=True) target_content_type =",
"self.target_object_id = obj_id @property def action_object(self): obj_ct = self.action_object_content_type obj_id = self.action_object_object_id return",
"= objstring return description_template.format(**context) def _serialize_event(kwargs): data = {} data['actor'] = _serialize_gfk(kwargs['actor']) data['target']",
"obj_id) @target.setter def target(self, target): if target: obj_ct, obj_id = _get_gfk(target) self.target_content_type =",
"django.contrib.contenttypes.models import ContentType from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.utils.timezone",
"obj._wrapped return obj def _format_obj(obj): try: objstring = obj.logprint() except AttributeError: obj =",
"objects: if not obj: continue obj_ct, obj_id = _get_gfk(obj) lookups = {ct: obj_ct,",
"return 0 update.queryset_only = True # type: ignore def _get_gfks(self, field, *objects): ct",
"self.actors(obj) | self.targets(obj) | self.action_objects(obj) return qs.distinct() class EventLogManager(models.Manager): def log_event(self, actor, verb,",
"True # type: ignore def _get_gfks(self, field, *objects): ct = GFK_MAPPER[field]['ct'] id =",
"obj = obj_ct.get_object_for_this_type(pk=obj_id) return obj def _serialize_gfk(obj): if not obj: return if isinstance(obj,",
"copy the rest for field in ('verb', 'description', 'timestamp', 'extra'): data[field] = kwargs[field]",
"_format_description(locals(), description_template) data = _serialize_event(locals()) return self.create( actor=actor, target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp,",
"return self.create( actor=actor, target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data, ) class EventLog(models.Model): actor_content_type",
"in ('actor', 'target', 'action_object'): obj = kwargs[field] if not obj: continue objstring =",
"= obj_ct self.target_object_id = obj_id @property def action_object(self): obj_ct = self.action_object_content_type obj_id =",
"will be added to the `data`-field, and may be looked up from the",
"the `description_template`. \"\"\" timestamp = timestamp if timestamp else tznow() description = _format_description(locals(),",
"obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs)) def actors(self, *actors): return self._get_gfks('actor', *actors) def targets(self,",
"def delete(self): return (0, {}) delete.queryset_only = True # type: ignore def update(self,",
"'actor': {'ct': 'actor_content_type', 'id': 'actor_object_id'}, 'target': {'ct': 'target_content_type', 'id': 'target_object_id'}, 'action_object': { 'ct':",
"rest for field in ('verb', 'description', 'timestamp', 'extra'): data[field] = kwargs[field] return data",
"_get_remote_obj(obj_ct, obj_id) @actor.setter def actor(self, actor): obj_ct, obj_id = _get_gfk(actor) self.actor_content_type = obj_ct",
"self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), ) def any(self, obj): ct = ContentType.objects.get_for_model(obj) qs =",
"not obj: continue obj_ct, obj_id = _get_gfk(obj) lookups = {ct: obj_ct, id: obj_id}",
"self.description def delete(self, **_): # Deletion not allowed return (0, {}) @property def",
"*action_objects) def model_actions(self, model): ct = ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), )",
"from the `description_template`. \"\"\" timestamp = timestamp if timestamp else tznow() description =",
"be looked up from the `description_template`. \"\"\" timestamp = timestamp if timestamp else",
"actor=actor, target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data, ) class EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType,",
"continue obj_ct, obj_id = _get_gfk(obj) lookups = {ct: obj_ct, id: obj_id} q_objs.append(Q(**lookups)) return",
"**_): # Deletion not allowed return (0, {}) @property def actor(self): obj_ct =",
"= deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp']) for field in ('actor', 'target', 'action_object'): obj =",
"obj['pk'] value = obj['value'] else: ct, pk = _get_gfk(obj) value = str(obj) return",
"data['action_object'] = _serialize_gfk(kwargs['action_object']) # copy the rest for field in ('verb', 'description', 'timestamp',",
"be added to the `data`-field, and may be looked up from the `description_template`.",
"related_name='actor', db_index=True) actor_object_id = models.TextField(db_index=True) verb = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True, null=True)",
"def action_objects(self, *action_objects): return self._get_gfks('action_object', *action_objects) def model_actions(self, model): ct = ContentType.objects.get_for_model(model) return",
"null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target', db_index=True) target_object_id = models.TextField(blank=True, null=True,",
"obj): ct = ContentType.objects.get_for_model(obj) qs = self.actors(obj) | self.targets(obj) | self.action_objects(obj) return qs.distinct()",
"models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target',",
"data = {} data['actor'] = _serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object']) #",
"tznow GFK_MAPPER = { 'actor': {'ct': 'actor_content_type', 'id': 'actor_object_id'}, 'target': {'ct': 'target_content_type', 'id':",
"for obj in objects: if not obj: continue obj_ct, obj_id = _get_gfk(obj) lookups",
"class EventLogManager(models.Manager): def log_event(self, actor, verb, target=None, action_object=None, description_template='', timestamp=None, extra=None, using=None): \"\"\"Log",
"= models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True,",
"('verb', 'description', 'timestamp', 'extra'): data[field] = kwargs[field] return data class EventLogQuerySet(models.QuerySet): def delete(self):",
"from functools import reduce from operator import or_ from copy import deepcopy from",
"str(obj) return { 'ct': {'pk': ct.pk, 'name': str(ct)}, 'pk': pk, 'value': str(obj) }",
"db_index=True) description = models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target', db_index=True)",
"(0, {}) @property def actor(self): obj_ct = self.actor_content_type obj_id = self.actor_object_id return _get_remote_obj(obj_ct,",
"= timestamp if timestamp else tznow() description = _format_description(locals(), description_template) data = _serialize_event(locals())",
"on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target', db_index=True) target_object_id = models.TextField(blank=True, null=True, db_index=True) action_object_content_type = models.ForeignKey(ContentType,",
"def target(self, target): if target: obj_ct, obj_id = _get_gfk(target) self.target_content_type = obj_ct self.target_object_id",
"@property def target(self): obj_ct = self.target_content_type obj_id = self.target_object_id return _get_remote_obj(obj_ct, obj_id) @target.setter",
"qs = self.actors(obj) | self.targets(obj) | self.action_objects(obj) return qs.distinct() class EventLogManager(models.Manager): def log_event(self,",
"model instances of `actor`, `target` or `action_object`. `description_template` is used to build a",
"# type: ignore def _get_gfks(self, field, *objects): ct = GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id']",
"db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering = ('-timestamp',) def __str__(self): return self.description",
"obj def _serialize_gfk(obj): if not obj: return if isinstance(obj, dict): ct = obj['ct']",
"db_index=True) actor_object_id = models.TextField(db_index=True) verb = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True, null=True) target_content_type",
"It should not duplicate information about the model instances of `actor`, `target` or",
"== object: obj._setup() obj = obj._wrapped return obj def _format_obj(obj): try: objstring =",
"ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), ) def any(self, obj): ct = ContentType.objects.get_for_model(obj)",
"description_template) data = _serialize_event(locals()) return self.create( actor=actor, target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data,",
"obj_id) @action_object.setter def action_object(self, action_object): if action_object: obj_ct, obj_id = _get_gfk(action_object) self.action_object_content_type =",
"_serialize_gfk(kwargs['action_object']) # copy the rest for field in ('verb', 'description', 'timestamp', 'extra'): data[field]",
"_serialize_gfk(obj): if not obj: return if isinstance(obj, dict): ct = obj['ct'] pk =",
"return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), ) def any(self, obj): ct = ContentType.objects.get_for_model(obj) qs",
"description_template.format(**context) def _serialize_event(kwargs): data = {} data['actor'] = _serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target']) data['action_object']",
"any(self, obj): ct = ContentType.objects.get_for_model(obj) qs = self.actors(obj) | self.targets(obj) | self.action_objects(obj) return",
"dict): ct = obj['ct'] pk = obj['pk'] value = obj['value'] else: ct, pk",
"be JSON serializable, preferrably a dict. The info will be added to the",
"action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object', db_index=True) action_object_object_id = models.TextField(blank=True, null=True, db_index=True)",
"_get_remote_obj(obj_ct, obj_id) @action_object.setter def action_object(self, action_object): if action_object: obj_ct, obj_id = _get_gfk(action_object) self.action_object_content_type",
"obj_id) def _get_remote_obj(obj_ct, obj_id): if obj_ct and obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id) return obj",
"obj_ct = self.actor_content_type obj_id = self.actor_object_id return _get_remote_obj(obj_ct, obj_id) @actor.setter def actor(self, actor):",
"in objects: if not obj: continue obj_ct, obj_id = _get_gfk(obj) lookups = {ct:",
"import now as tznow GFK_MAPPER = { 'actor': {'ct': 'actor_content_type', 'id': 'actor_object_id'}, 'target':",
"_serialize_event(kwargs): data = {} data['actor'] = _serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object'])",
"obj_ct, obj_id = _get_gfk(target) self.target_content_type = obj_ct self.target_object_id = obj_id @property def action_object(self):",
"str(obj) } def delazify_object(obj): if hasattr(obj, '_wrapped') and hasattr(obj, '_setup'): if obj._wrapped.__class__ ==",
"'target', 'action_object'): obj = kwargs[field] if not obj: continue objstring = _format_obj(obj) context[field]",
"= delazify_object(obj) objstring = repr(obj).strip('<>') return objstring def _format_timestamp(timestamp): \"Print timestamp in JSON",
"deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp']) for field in ('actor', 'target', 'action_object'): obj = kwargs[field]",
"action_object): if action_object: obj_ct, obj_id = _get_gfk(action_object) self.action_object_content_type = obj_ct self.action_object_object_id = obj_id",
"timestamp def _format_description(kwargs, description_template): context = deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp']) for field in",
"= obj_id @property def action_object(self): obj_ct = self.action_object_content_type obj_id = self.action_object_object_id return _get_remote_obj(obj_ct,",
"= obj_ct self.actor_object_id = obj_id @property def target(self): obj_ct = self.target_content_type obj_id =",
"models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target', db_index=True) target_object_id = models.TextField(blank=True, null=True, db_index=True) action_object_content_type =",
"not obj: continue objstring = _format_obj(obj) context[field] = objstring return description_template.format(**context) def _serialize_event(kwargs):",
"objstring = obj.logprint() except AttributeError: obj = delazify_object(obj) objstring = repr(obj).strip('<>') return objstring",
"obj.logprint() except AttributeError: obj = delazify_object(obj) objstring = repr(obj).strip('<>') return objstring def _format_timestamp(timestamp):",
"Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), ) def any(self, obj): ct = ContentType.objects.get_for_model(obj) qs = self.actors(obj)",
"= models.TextField(blank=True, null=True, db_index=True) action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object', db_index=True) action_object_object_id",
"'_setup'): if obj._wrapped.__class__ == object: obj._setup() obj = obj._wrapped return obj def _format_obj(obj):",
"= obj.pk return (obj_ct, obj_id) def _get_remote_obj(obj_ct, obj_id): if obj_ct and obj_id: obj",
"information about the model instances of `actor`, `target` or `action_object`. `description_template` is used",
"{ct: obj_ct, id: obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs)) def actors(self, *actors): return self._get_gfks('actor',",
"delete.queryset_only = True # type: ignore def update(self, **_): return 0 update.queryset_only =",
"_format_timestamp(timestamp): \"Print timestamp in JSON serializer compatible format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp =",
"ContentType from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.utils.timezone import now",
"action_object(self): obj_ct = self.action_object_content_type obj_id = self.action_object_object_id return _get_remote_obj(obj_ct, obj_id) @action_object.setter def action_object(self,",
"_serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object']) # copy the rest for field in ('verb', 'description',",
"`action_object` are model instances. `actor` is required. `verb` is a short string, preferrably",
"datetime with timezone `extra` must be JSON serializable, preferrably a dict. The info",
"'id': 'actor_object_id'}, 'target': {'ct': 'target_content_type', 'id': 'target_object_id'}, 'action_object': { 'ct': 'action_object_content_type', 'id': 'action_object_object_id'",
"= {ct: obj_ct, id: obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs)) def actors(self, *actors): return",
"info will be added to the `data`-field, and may be looked up from",
"related_name='target', db_index=True) target_object_id = models.TextField(blank=True, null=True, db_index=True) action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True,",
"'value': str(obj) } def delazify_object(obj): if hasattr(obj, '_wrapped') and hasattr(obj, '_setup'): if obj._wrapped.__class__",
"format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC', 'Z', 1) return timestamp def _format_description(kwargs,",
"arguments. `timestamp` must be a datetime with timezone `extra` must be JSON serializable,",
"def _get_gfks(self, field, *objects): ct = GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id'] q_objs = []",
"actors(self, *actors): return self._get_gfks('actor', *actors) def targets(self, *targets): return self._get_gfks('target', *targets) def action_objects(self,",
"Q(target_content_type=ct), Q(action_object_content_type=ct), ) def any(self, obj): ct = ContentType.objects.get_for_model(obj) qs = self.actors(obj) |",
"used to build a human-readble string from the other arguments. `timestamp` must be",
"'timestamp', 'extra'): data[field] = kwargs[field] return data class EventLogQuerySet(models.QuerySet): def delete(self): return (0,",
"'name': str(ct)}, 'pk': pk, 'value': str(obj) } def delazify_object(obj): if hasattr(obj, '_wrapped') and",
"delazify_object(obj): if hasattr(obj, '_wrapped') and hasattr(obj, '_setup'): if obj._wrapped.__class__ == object: obj._setup() obj",
"def _get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj) obj_id = obj.pk return (obj_ct, obj_id) def _get_remote_obj(obj_ct,",
"def _serialize_gfk(obj): if not obj: return if isinstance(obj, dict): ct = obj['ct'] pk",
"q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs)) def actors(self, *actors): return self._get_gfks('actor', *actors) def targets(self, *targets):",
"blank=True, null=True, related_name='action_object', db_index=True) action_object_object_id = models.TextField(blank=True, null=True, db_index=True) data = models.JSONField(default=dict, encoder=DjangoJSONEncoder)",
"from django.utils.timezone import now as tznow GFK_MAPPER = { 'actor': {'ct': 'actor_content_type', 'id':",
"\"Print timestamp in JSON serializer compatible format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC',",
"*targets): return self._get_gfks('target', *targets) def action_objects(self, *action_objects): return self._get_gfks('action_object', *action_objects) def model_actions(self, model):",
"= { 'actor': {'ct': 'actor_content_type', 'id': 'actor_object_id'}, 'target': {'ct': 'target_content_type', 'id': 'target_object_id'}, 'action_object':",
"{ 'ct': 'action_object_content_type', 'id': 'action_object_object_id' }, } Q = models.Q def _get_gfk(obj): obj_ct",
"= models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow, db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering",
"self.actor_object_id return _get_remote_obj(obj_ct, obj_id) @actor.setter def actor(self, actor): obj_ct, obj_id = _get_gfk(actor) self.actor_content_type",
"{ 'ct': {'pk': ct.pk, 'name': str(ct)}, 'pk': pk, 'value': str(obj) } def delazify_object(obj):",
"models.TextField(db_index=True) verb = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING,",
"timestamp=timestamp, data=data, ) class EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id =",
"on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object', db_index=True) action_object_object_id = models.TextField(blank=True, null=True, db_index=True) data = models.JSONField(default=dict,",
"to the `data`-field, and may be looked up from the `description_template`. \"\"\" timestamp",
"as tznow GFK_MAPPER = { 'actor': {'ct': 'actor_content_type', 'id': 'actor_object_id'}, 'target': {'ct': 'target_content_type',",
"except AttributeError: obj = delazify_object(obj) objstring = repr(obj).strip('<>') return objstring def _format_timestamp(timestamp): \"Print",
"models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow, db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering =",
"instances of `actor`, `target` or `action_object`. `description_template` is used to build a human-readble",
"models.Q def _get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj) obj_id = obj.pk return (obj_ct, obj_id) def",
"str(ct)}, 'pk': pk, 'value': str(obj) } def delazify_object(obj): if hasattr(obj, '_wrapped') and hasattr(obj,",
"'ct': {'pk': ct.pk, 'name': str(ct)}, 'pk': pk, 'value': str(obj) } def delazify_object(obj): if",
"if hasattr(obj, '_wrapped') and hasattr(obj, '_setup'): if obj._wrapped.__class__ == object: obj._setup() obj =",
"required. `verb` is a short string, preferrably an infinitive. It should not duplicate",
"timestamp = timestamp if timestamp else tznow() description = _format_description(locals(), description_template) data =",
"# Deletion not allowed return (0, {}) @property def actor(self): obj_ct = self.actor_content_type",
"obj: continue obj_ct, obj_id = _get_gfk(obj) lookups = {ct: obj_ct, id: obj_id} q_objs.append(Q(**lookups))",
"{}) @property def actor(self): obj_ct = self.actor_content_type obj_id = self.actor_object_id return _get_remote_obj(obj_ct, obj_id)",
"if not obj: return if isinstance(obj, dict): ct = obj['ct'] pk = obj['pk']",
"ct = obj['ct'] pk = obj['pk'] value = obj['value'] else: ct, pk =",
"1) return timestamp def _format_description(kwargs, description_template): context = deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp']) for",
"return description_template.format(**context) def _serialize_event(kwargs): data = {} data['actor'] = _serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target'])",
"preferrably an infinitive. It should not duplicate information about the model instances of",
"self.targets(obj) | self.action_objects(obj) return qs.distinct() class EventLogManager(models.Manager): def log_event(self, actor, verb, target=None, action_object=None,",
"looked up from the `description_template`. \"\"\" timestamp = timestamp if timestamp else tznow()",
"{'ct': 'actor_content_type', 'id': 'actor_object_id'}, 'target': {'ct': 'target_content_type', 'id': 'target_object_id'}, 'action_object': { 'ct': 'action_object_content_type',",
"from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.utils.timezone import now as",
"import models from django.utils.timezone import now as tznow GFK_MAPPER = { 'actor': {'ct':",
"actor(self): obj_ct = self.actor_content_type obj_id = self.actor_object_id return _get_remote_obj(obj_ct, obj_id) @actor.setter def actor(self,",
"return (0, {}) @property def actor(self): obj_ct = self.actor_content_type obj_id = self.actor_object_id return",
"timestamp.replace('UTC', 'Z', 1) return timestamp def _format_description(kwargs, description_template): context = deepcopy(kwargs) context['timestamp'] =",
"django.utils.timezone import now as tznow GFK_MAPPER = { 'actor': {'ct': 'actor_content_type', 'id': 'actor_object_id'},",
"now as tznow GFK_MAPPER = { 'actor': {'ct': 'actor_content_type', 'id': 'actor_object_id'}, 'target': {'ct':",
"(obj_ct, obj_id) def _get_remote_obj(obj_ct, obj_id): if obj_ct and obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id) return",
"tznow() description = _format_description(locals(), description_template) data = _serialize_event(locals()) return self.create( actor=actor, target=target, action_object=action_object,",
"a datetime with timezone `extra` must be JSON serializable, preferrably a dict. The",
"action_object(self, action_object): if action_object: obj_ct, obj_id = _get_gfk(action_object) self.action_object_content_type = obj_ct self.action_object_object_id =",
"import reduce from operator import or_ from copy import deepcopy from django.contrib.contenttypes.models import",
"= obj['value'] else: ct, pk = _get_gfk(obj) value = str(obj) return { 'ct':",
"target=None, action_object=None, description_template='', timestamp=None, extra=None, using=None): \"\"\"Log event `actor`, `target` and `action_object` are",
"_get_remote_obj(obj_ct, obj_id) @target.setter def target(self, target): if target: obj_ct, obj_id = _get_gfk(target) self.target_content_type",
"compatible format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC', 'Z', 1) return timestamp def",
"serializable, preferrably a dict. The info will be added to the `data`-field, and",
"obj_ct, obj_id = _get_gfk(actor) self.actor_content_type = obj_ct self.actor_object_id = obj_id @property def target(self):",
"JSON serializer compatible format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC', 'Z', 1) return",
"target(self, target): if target: obj_ct, obj_id = _get_gfk(target) self.target_content_type = obj_ct self.target_object_id =",
"kwargs[field] if not obj: continue objstring = _format_obj(obj) context[field] = objstring return description_template.format(**context)",
"{'pk': ct.pk, 'name': str(ct)}, 'pk': pk, 'value': str(obj) } def delazify_object(obj): if hasattr(obj,",
"isinstance(obj, dict): ct = obj['ct'] pk = obj['pk'] value = obj['value'] else: ct,",
"obj_id = self.actor_object_id return _get_remote_obj(obj_ct, obj_id) @actor.setter def actor(self, actor): obj_ct, obj_id =",
"hasattr(obj, '_wrapped') and hasattr(obj, '_setup'): if obj._wrapped.__class__ == object: obj._setup() obj = obj._wrapped",
"Deletion not allowed return (0, {}) @property def actor(self): obj_ct = self.actor_content_type obj_id",
"_format_description(kwargs, description_template): context = deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp']) for field in ('actor', 'target',",
"= models.DateTimeField(default=tznow, db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering = ('-timestamp',) def __str__(self):",
"Q = models.Q def _get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj) obj_id = obj.pk return (obj_ct,",
"context['timestamp'] = _format_timestamp(context['timestamp']) for field in ('actor', 'target', 'action_object'): obj = kwargs[field] if",
"db_index=True) action_object_object_id = models.TextField(blank=True, null=True, db_index=True) data = models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow,",
"'action_object_object_id' }, } Q = models.Q def _get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj) obj_id =",
"delazify_object(obj) objstring = repr(obj).strip('<>') return objstring def _format_timestamp(timestamp): \"Print timestamp in JSON serializer",
"a dict. The info will be added to the `data`-field, and may be",
"EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id = models.TextField(db_index=True) verb = models.CharField(max_length=255,",
"action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data, ) class EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor',",
"**_): return 0 update.queryset_only = True # type: ignore def _get_gfks(self, field, *objects):",
"type: ignore def _get_gfks(self, field, *objects): ct = GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id'] q_objs",
"else tznow() description = _format_description(locals(), description_template) data = _serialize_event(locals()) return self.create( actor=actor, target=target,",
"timestamp else tznow() description = _format_description(locals(), description_template) data = _serialize_event(locals()) return self.create( actor=actor,",
"other arguments. `timestamp` must be a datetime with timezone `extra` must be JSON",
"target): if target: obj_ct, obj_id = _get_gfk(target) self.target_content_type = obj_ct self.target_object_id = obj_id",
"using=None): \"\"\"Log event `actor`, `target` and `action_object` are model instances. `actor` is required.",
"obj_id) @actor.setter def actor(self, actor): obj_ct, obj_id = _get_gfk(actor) self.actor_content_type = obj_ct self.actor_object_id",
"obj: continue objstring = _format_obj(obj) context[field] = objstring return description_template.format(**context) def _serialize_event(kwargs): data",
"objstring return description_template.format(**context) def _serialize_event(kwargs): data = {} data['actor'] = _serialize_gfk(kwargs['actor']) data['target'] =",
"ct = GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id'] q_objs = [] for obj in objects:",
"context = deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp']) for field in ('actor', 'target', 'action_object'): obj",
"= models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id = models.TextField(db_index=True) verb = models.CharField(max_length=255, db_index=True) description",
"timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC', 'Z', 1) return timestamp def _format_description(kwargs, description_template):",
"'action_object_content_type', 'id': 'action_object_object_id' }, } Q = models.Q def _get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj)",
"\"\"\"Log event `actor`, `target` and `action_object` are model instances. `actor` is required. `verb`",
"self.target_object_id return _get_remote_obj(obj_ct, obj_id) @target.setter def target(self, target): if target: obj_ct, obj_id =",
"event `actor`, `target` and `action_object` are model instances. `actor` is required. `verb` is",
"= kwargs[field] return data class EventLogQuerySet(models.QuerySet): def delete(self): return (0, {}) delete.queryset_only =",
"self.target_content_type obj_id = self.target_object_id return _get_remote_obj(obj_ct, obj_id) @target.setter def target(self, target): if target:",
"ct = ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), ) def any(self, obj): ct",
"model instances. `actor` is required. `verb` is a short string, preferrably an infinitive.",
"= models.TextField(db_index=True) verb = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType,",
"= obj.logprint() except AttributeError: obj = delazify_object(obj) objstring = repr(obj).strip('<>') return objstring def",
"= True # type: ignore def _get_gfks(self, field, *objects): ct = GFK_MAPPER[field]['ct'] id",
"_format_timestamp(context['timestamp']) for field in ('actor', 'target', 'action_object'): obj = kwargs[field] if not obj:",
"return obj def _serialize_gfk(obj): if not obj: return if isinstance(obj, dict): ct =",
"human-readble string from the other arguments. `timestamp` must be a datetime with timezone",
"`description_template`. \"\"\" timestamp = timestamp if timestamp else tznow() description = _format_description(locals(), description_template)",
"actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id = models.TextField(db_index=True) verb = models.CharField(max_length=255, db_index=True)",
"model_actions(self, model): ct = ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), ) def any(self,",
"= _format_obj(obj) context[field] = objstring return description_template.format(**context) def _serialize_event(kwargs): data = {} data['actor']",
"obj_ct self.actor_object_id = obj_id @property def target(self): obj_ct = self.target_content_type obj_id = self.target_object_id",
"obj['value'] else: ct, pk = _get_gfk(obj) value = str(obj) return { 'ct': {'pk':",
"if timestamp else tznow() description = _format_description(locals(), description_template) data = _serialize_event(locals()) return self.create(",
"kwargs[field] return data class EventLogQuerySet(models.QuerySet): def delete(self): return (0, {}) delete.queryset_only = True",
"EventLogQuerySet(models.QuerySet): def delete(self): return (0, {}) delete.queryset_only = True # type: ignore def",
"= models.Q def _get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj) obj_id = obj.pk return (obj_ct, obj_id)",
"obj: return if isinstance(obj, dict): ct = obj['ct'] pk = obj['pk'] value =",
"and obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id) return obj def _serialize_gfk(obj): if not obj: return",
"from copy import deepcopy from django.contrib.contenttypes.models import ContentType from django.core.serializers.json import DjangoJSONEncoder from",
"'action_object'): obj = kwargs[field] if not obj: continue objstring = _format_obj(obj) context[field] =",
"ct, pk = _get_gfk(obj) value = str(obj) return { 'ct': {'pk': ct.pk, 'name':",
"def actor(self, actor): obj_ct, obj_id = _get_gfk(actor) self.actor_content_type = obj_ct self.actor_object_id = obj_id",
"'target_content_type', 'id': 'target_object_id'}, 'action_object': { 'ct': 'action_object_content_type', 'id': 'action_object_object_id' }, } Q =",
"self._get_gfks('actor', *actors) def targets(self, *targets): return self._get_gfks('target', *targets) def action_objects(self, *action_objects): return self._get_gfks('action_object',",
"if target: obj_ct, obj_id = _get_gfk(target) self.target_content_type = obj_ct self.target_object_id = obj_id @property",
"delete(self): return (0, {}) delete.queryset_only = True # type: ignore def update(self, **_):",
"}, } Q = models.Q def _get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj) obj_id = obj.pk",
"'pk': pk, 'value': str(obj) } def delazify_object(obj): if hasattr(obj, '_wrapped') and hasattr(obj, '_setup'):",
"obj def _format_obj(obj): try: objstring = obj.logprint() except AttributeError: obj = delazify_object(obj) objstring",
"= _get_gfk(target) self.target_content_type = obj_ct self.target_object_id = obj_id @property def action_object(self): obj_ct =",
"obj_id = _get_gfk(target) self.target_content_type = obj_ct self.target_object_id = obj_id @property def action_object(self): obj_ct",
"django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.utils.timezone import now as tznow",
"verb=verb, description=description, timestamp=timestamp, data=data, ) class EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True)",
"'description', 'timestamp', 'extra'): data[field] = kwargs[field] return data class EventLogQuerySet(models.QuerySet): def delete(self): return",
"null=True, db_index=True) data = models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow, db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)()",
"timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC', 'Z', 1) return timestamp def _format_description(kwargs, description_template): context =",
"blank=True, null=True, related_name='target', db_index=True) target_object_id = models.TextField(blank=True, null=True, db_index=True) action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING,",
"in ('verb', 'description', 'timestamp', 'extra'): data[field] = kwargs[field] return data class EventLogQuerySet(models.QuerySet): def",
"django.db import models from django.utils.timezone import now as tznow GFK_MAPPER = { 'actor':",
"GFK_MAPPER[field]['id'] q_objs = [] for obj in objects: if not obj: continue obj_ct,",
"return if isinstance(obj, dict): ct = obj['ct'] pk = obj['pk'] value = obj['value']",
"'extra'): data[field] = kwargs[field] return data class EventLogQuerySet(models.QuerySet): def delete(self): return (0, {})",
"models.TextField(blank=True, null=True, db_index=True) data = models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow, db_index=True) objects =",
"= self.target_object_id return _get_remote_obj(obj_ct, obj_id) @target.setter def target(self, target): if target: obj_ct, obj_id",
"return self._get_gfks('action_object', *action_objects) def model_actions(self, model): ct = ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct),",
"*targets) def action_objects(self, *action_objects): return self._get_gfks('action_object', *action_objects) def model_actions(self, model): ct = ContentType.objects.get_for_model(model)",
"update(self, **_): return 0 update.queryset_only = True # type: ignore def _get_gfks(self, field,",
"= _get_gfk(obj) value = str(obj) return { 'ct': {'pk': ct.pk, 'name': str(ct)}, 'pk':",
"deepcopy from django.contrib.contenttypes.models import ContentType from django.core.serializers.json import DjangoJSONEncoder from django.db import models",
"\"\"\" timestamp = timestamp if timestamp else tznow() description = _format_description(locals(), description_template) data",
"not duplicate information about the model instances of `actor`, `target` or `action_object`. `description_template`",
"`description_template` is used to build a human-readble string from the other arguments. `timestamp`",
"return { 'ct': {'pk': ct.pk, 'name': str(ct)}, 'pk': pk, 'value': str(obj) } def",
"not obj: return if isinstance(obj, dict): ct = obj['ct'] pk = obj['pk'] value",
"EventLogManager(models.Manager): def log_event(self, actor, verb, target=None, action_object=None, description_template='', timestamp=None, extra=None, using=None): \"\"\"Log event",
"'target': {'ct': 'target_content_type', 'id': 'target_object_id'}, 'action_object': { 'ct': 'action_object_content_type', 'id': 'action_object_object_id' }, }",
"or_ from copy import deepcopy from django.contrib.contenttypes.models import ContentType from django.core.serializers.json import DjangoJSONEncoder",
"DjangoJSONEncoder from django.db import models from django.utils.timezone import now as tznow GFK_MAPPER =",
"for field in ('verb', 'description', 'timestamp', 'extra'): data[field] = kwargs[field] return data class",
"hasattr(obj, '_setup'): if obj._wrapped.__class__ == object: obj._setup() obj = obj._wrapped return obj def",
"an infinitive. It should not duplicate information about the model instances of `actor`,",
"a short string, preferrably an infinitive. It should not duplicate information about the",
"*objects): ct = GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id'] q_objs = [] for obj in",
"data = _serialize_event(locals()) return self.create( actor=actor, target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data, )",
"from operator import or_ from copy import deepcopy from django.contrib.contenttypes.models import ContentType from",
"} def delazify_object(obj): if hasattr(obj, '_wrapped') and hasattr(obj, '_setup'): if obj._wrapped.__class__ == object:",
"= _serialize_event(locals()) return self.create( actor=actor, target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data, ) class",
"actor): obj_ct, obj_id = _get_gfk(actor) self.actor_content_type = obj_ct self.actor_object_id = obj_id @property def",
"obj_ct = ContentType.objects.get_for_model(obj) obj_id = obj.pk return (obj_ct, obj_id) def _get_remote_obj(obj_ct, obj_id): if",
"target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target', db_index=True) target_object_id = models.TextField(blank=True, null=True, db_index=True)",
"= ContentType.objects.get_for_model(obj) obj_id = obj.pk return (obj_ct, obj_id) def _get_remote_obj(obj_ct, obj_id): if obj_ct",
"self._get_gfks('target', *targets) def action_objects(self, *action_objects): return self._get_gfks('action_object', *action_objects) def model_actions(self, model): ct =",
"return _get_remote_obj(obj_ct, obj_id) @target.setter def target(self, target): if target: obj_ct, obj_id = _get_gfk(target)",
"The info will be added to the `data`-field, and may be looked up",
"= self.action_object_object_id return _get_remote_obj(obj_ct, obj_id) @action_object.setter def action_object(self, action_object): if action_object: obj_ct, obj_id",
"GFK_MAPPER = { 'actor': {'ct': 'actor_content_type', 'id': 'actor_object_id'}, 'target': {'ct': 'target_content_type', 'id': 'target_object_id'},",
"(0, {}) delete.queryset_only = True # type: ignore def update(self, **_): return 0",
"ct = ContentType.objects.get_for_model(obj) qs = self.actors(obj) | self.targets(obj) | self.action_objects(obj) return qs.distinct() class",
"_get_gfk(target) self.target_content_type = obj_ct self.target_object_id = obj_id @property def action_object(self): obj_ct = self.action_object_content_type",
"q_objs)) def actors(self, *actors): return self._get_gfks('actor', *actors) def targets(self, *targets): return self._get_gfks('target', *targets)",
"_get_remote_obj(obj_ct, obj_id): if obj_ct and obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id) return obj def _serialize_gfk(obj):",
"to build a human-readble string from the other arguments. `timestamp` must be a",
"def any(self, obj): ct = ContentType.objects.get_for_model(obj) qs = self.actors(obj) | self.targets(obj) | self.action_objects(obj)",
"obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id) return obj def _serialize_gfk(obj): if not obj: return if",
"obj_id = _get_gfk(actor) self.actor_content_type = obj_ct self.actor_object_id = obj_id @property def target(self): obj_ct",
"'_wrapped') and hasattr(obj, '_setup'): if obj._wrapped.__class__ == object: obj._setup() obj = obj._wrapped return",
"_get_gfk(obj) value = str(obj) return { 'ct': {'pk': ct.pk, 'name': str(ct)}, 'pk': pk,",
"data = models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow, db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)() class Meta:",
"actor(self, actor): obj_ct, obj_id = _get_gfk(actor) self.actor_content_type = obj_ct self.actor_object_id = obj_id @property",
"for field in ('actor', 'target', 'action_object'): obj = kwargs[field] if not obj: continue",
"# type: ignore def update(self, **_): return 0 update.queryset_only = True # type:",
"action_object=None, description_template='', timestamp=None, extra=None, using=None): \"\"\"Log event `actor`, `target` and `action_object` are model",
"obj._setup() obj = obj._wrapped return obj def _format_obj(obj): try: objstring = obj.logprint() except",
"if not obj: continue obj_ct, obj_id = _get_gfk(obj) lookups = {ct: obj_ct, id:",
"return timestamp def _format_description(kwargs, description_template): context = deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp']) for field",
"self.actor_content_type obj_id = self.actor_object_id return _get_remote_obj(obj_ct, obj_id) @actor.setter def actor(self, actor): obj_ct, obj_id",
"ContentType.objects.get_for_model(obj) qs = self.actors(obj) | self.targets(obj) | self.action_objects(obj) return qs.distinct() class EventLogManager(models.Manager): def",
"def update(self, **_): return 0 update.queryset_only = True # type: ignore def _get_gfks(self,",
"models from django.utils.timezone import now as tznow GFK_MAPPER = { 'actor': {'ct': 'actor_content_type',",
"= EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering = ('-timestamp',) def __str__(self): return self.description def delete(self,",
"the other arguments. `timestamp` must be a datetime with timezone `extra` must be",
"= [] for obj in objects: if not obj: continue obj_ct, obj_id =",
"`actor`, `target` or `action_object`. `description_template` is used to build a human-readble string from",
"ContentType.objects.get_for_model(obj) obj_id = obj.pk return (obj_ct, obj_id) def _get_remote_obj(obj_ct, obj_id): if obj_ct and",
"`actor`, `target` and `action_object` are model instances. `actor` is required. `verb` is a",
"obj_ct, id: obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs)) def actors(self, *actors): return self._get_gfks('actor', *actors)",
"in JSON serializer compatible format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC', 'Z', 1)",
"`verb` is a short string, preferrably an infinitive. It should not duplicate information",
"EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering = ('-timestamp',) def __str__(self): return self.description def delete(self, **_):",
"_get_gfks(self, field, *objects): ct = GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id'] q_objs = [] for",
"_get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj) obj_id = obj.pk return (obj_ct, obj_id) def _get_remote_obj(obj_ct, obj_id):",
"return data class EventLogQuerySet(models.QuerySet): def delete(self): return (0, {}) delete.queryset_only = True #",
"encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow, db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering = ('-timestamp',)",
"ordering = ('-timestamp',) def __str__(self): return self.description def delete(self, **_): # Deletion not",
"'Z', 1) return timestamp def _format_description(kwargs, description_template): context = deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp'])",
"obj_id): if obj_ct and obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id) return obj def _serialize_gfk(obj): if",
"pk = _get_gfk(obj) value = str(obj) return { 'ct': {'pk': ct.pk, 'name': str(ct)},",
"build a human-readble string from the other arguments. `timestamp` must be a datetime",
"@property def action_object(self): obj_ct = self.action_object_content_type obj_id = self.action_object_object_id return _get_remote_obj(obj_ct, obj_id) @action_object.setter",
"self.create( actor=actor, target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data, ) class EventLog(models.Model): actor_content_type =",
"action_object_object_id = models.TextField(blank=True, null=True, db_index=True) data = models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow, db_index=True)",
"= GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id'] q_objs = [] for obj in objects: if",
"@target.setter def target(self, target): if target: obj_ct, obj_id = _get_gfk(target) self.target_content_type = obj_ct",
"= ContentType.objects.get_for_model(obj) qs = self.actors(obj) | self.targets(obj) | self.action_objects(obj) return qs.distinct() class EventLogManager(models.Manager):",
"= str(obj) return { 'ct': {'pk': ct.pk, 'name': str(ct)}, 'pk': pk, 'value': str(obj)",
"= _get_gfk(actor) self.actor_content_type = obj_ct self.actor_object_id = obj_id @property def target(self): obj_ct =",
"the `data`-field, and may be looked up from the `description_template`. \"\"\" timestamp =",
"obj_ct self.target_object_id = obj_id @property def action_object(self): obj_ct = self.action_object_content_type obj_id = self.action_object_object_id",
"object: obj._setup() obj = obj._wrapped return obj def _format_obj(obj): try: objstring = obj.logprint()",
") def any(self, obj): ct = ContentType.objects.get_for_model(obj) qs = self.actors(obj) | self.targets(obj) |",
"of `actor`, `target` or `action_object`. `description_template` is used to build a human-readble string",
"= _format_timestamp(context['timestamp']) for field in ('actor', 'target', 'action_object'): obj = kwargs[field] if not",
"return _get_remote_obj(obj_ct, obj_id) @action_object.setter def action_object(self, action_object): if action_object: obj_ct, obj_id = _get_gfk(action_object)",
"ignore def update(self, **_): return 0 update.queryset_only = True # type: ignore def",
"`extra` must be JSON serializable, preferrably a dict. The info will be added",
"obj_ct = self.target_content_type obj_id = self.target_object_id return _get_remote_obj(obj_ct, obj_id) @target.setter def target(self, target):",
"extra=None, using=None): \"\"\"Log event `actor`, `target` and `action_object` are model instances. `actor` is",
"return (obj_ct, obj_id) def _get_remote_obj(obj_ct, obj_id): if obj_ct and obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id)",
"def _format_description(kwargs, description_template): context = deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp']) for field in ('actor',",
"pk, 'value': str(obj) } def delazify_object(obj): if hasattr(obj, '_wrapped') and hasattr(obj, '_setup'): if",
"def delete(self, **_): # Deletion not allowed return (0, {}) @property def actor(self):",
"= self.target_content_type obj_id = self.target_object_id return _get_remote_obj(obj_ct, obj_id) @target.setter def target(self, target): if",
"def action_object(self): obj_ct = self.action_object_content_type obj_id = self.action_object_object_id return _get_remote_obj(obj_ct, obj_id) @action_object.setter def",
"{'ct': 'target_content_type', 'id': 'target_object_id'}, 'action_object': { 'ct': 'action_object_content_type', 'id': 'action_object_object_id' }, } Q",
"value = str(obj) return { 'ct': {'pk': ct.pk, 'name': str(ct)}, 'pk': pk, 'value':",
"_format_obj(obj) context[field] = objstring return description_template.format(**context) def _serialize_event(kwargs): data = {} data['actor'] =",
"is used to build a human-readble string from the other arguments. `timestamp` must",
"data=data, ) class EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id = models.TextField(db_index=True)",
"'actor_object_id'}, 'target': {'ct': 'target_content_type', 'id': 'target_object_id'}, 'action_object': { 'ct': 'action_object_content_type', 'id': 'action_object_object_id' },",
"} Q = models.Q def _get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj) obj_id = obj.pk return",
"with timezone `extra` must be JSON serializable, preferrably a dict. The info will",
"obj_id = obj.pk return (obj_ct, obj_id) def _get_remote_obj(obj_ct, obj_id): if obj_ct and obj_id:",
"`data`-field, and may be looked up from the `description_template`. \"\"\" timestamp = timestamp",
"timestamp if timestamp else tznow() description = _format_description(locals(), description_template) data = _serialize_event(locals()) return",
"= _get_gfk(obj) lookups = {ct: obj_ct, id: obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs)) def",
"infinitive. It should not duplicate information about the model instances of `actor`, `target`",
"models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target', db_index=True) target_object_id = models.TextField(blank=True,",
"try: objstring = obj.logprint() except AttributeError: obj = delazify_object(obj) objstring = repr(obj).strip('<>') return",
"return obj def _format_obj(obj): try: objstring = obj.logprint() except AttributeError: obj = delazify_object(obj)",
"may be looked up from the `description_template`. \"\"\" timestamp = timestamp if timestamp",
"timestamp=None, extra=None, using=None): \"\"\"Log event `actor`, `target` and `action_object` are model instances. `actor`",
"db_index=True) target_object_id = models.TextField(blank=True, null=True, db_index=True) action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object',",
"added to the `data`-field, and may be looked up from the `description_template`. \"\"\"",
"must be a datetime with timezone `extra` must be JSON serializable, preferrably a",
"def target(self): obj_ct = self.target_content_type obj_id = self.target_object_id return _get_remote_obj(obj_ct, obj_id) @target.setter def",
"objstring = _format_obj(obj) context[field] = objstring return description_template.format(**context) def _serialize_event(kwargs): data = {}",
"[] for obj in objects: if not obj: continue obj_ct, obj_id = _get_gfk(obj)",
"= models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target', db_index=True) target_object_id = models.TextField(blank=True, null=True, db_index=True) action_object_content_type",
"should not duplicate information about the model instances of `actor`, `target` or `action_object`.",
"null=True, related_name='target', db_index=True) target_object_id = models.TextField(blank=True, null=True, db_index=True) action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True,",
"from django.db import models from django.utils.timezone import now as tznow GFK_MAPPER = {",
"must be JSON serializable, preferrably a dict. The info will be added to",
"db_index=True) action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object', db_index=True) action_object_object_id = models.TextField(blank=True, null=True,",
"delete(self, **_): # Deletion not allowed return (0, {}) @property def actor(self): obj_ct",
"def _format_obj(obj): try: objstring = obj.logprint() except AttributeError: obj = delazify_object(obj) objstring =",
"<gh_stars>1-10 from functools import reduce from operator import or_ from copy import deepcopy",
"_format_obj(obj): try: objstring = obj.logprint() except AttributeError: obj = delazify_object(obj) objstring = repr(obj).strip('<>')",
"return objstring def _format_timestamp(timestamp): \"Print timestamp in JSON serializer compatible format\" timestamp =",
"ct.pk, 'name': str(ct)}, 'pk': pk, 'value': str(obj) } def delazify_object(obj): if hasattr(obj, '_wrapped')",
"update.queryset_only = True # type: ignore def _get_gfks(self, field, *objects): ct = GFK_MAPPER[field]['ct']",
"a human-readble string from the other arguments. `timestamp` must be a datetime with",
"obj_id @property def target(self): obj_ct = self.target_content_type obj_id = self.target_object_id return _get_remote_obj(obj_ct, obj_id)",
"| self.targets(obj) | self.action_objects(obj) return qs.distinct() class EventLogManager(models.Manager): def log_event(self, actor, verb, target=None,",
"description=description, timestamp=timestamp, data=data, ) class EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id",
"continue objstring = _format_obj(obj) context[field] = objstring return description_template.format(**context) def _serialize_event(kwargs): data =",
"value = obj['value'] else: ct, pk = _get_gfk(obj) value = str(obj) return {",
"obj_ct, obj_id = _get_gfk(obj) lookups = {ct: obj_ct, id: obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_,",
"id = GFK_MAPPER[field]['id'] q_objs = [] for obj in objects: if not obj:",
"`action_object`. `description_template` is used to build a human-readble string from the other arguments.",
") class EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id = models.TextField(db_index=True) verb",
"repr(obj).strip('<>') return objstring def _format_timestamp(timestamp): \"Print timestamp in JSON serializer compatible format\" timestamp",
"description_template='', timestamp=None, extra=None, using=None): \"\"\"Log event `actor`, `target` and `action_object` are model instances.",
"_get_gfk(actor) self.actor_content_type = obj_ct self.actor_object_id = obj_id @property def target(self): obj_ct = self.target_content_type",
"Q(action_object_content_type=ct), ) def any(self, obj): ct = ContentType.objects.get_for_model(obj) qs = self.actors(obj) | self.targets(obj)",
"'id': 'action_object_object_id' }, } Q = models.Q def _get_gfk(obj): obj_ct = ContentType.objects.get_for_model(obj) obj_id",
"lookups = {ct: obj_ct, id: obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs)) def actors(self, *actors):",
"= _format_description(locals(), description_template) data = _serialize_event(locals()) return self.create( actor=actor, target=target, action_object=action_object, verb=verb, description=description,",
"*actors): return self._get_gfks('actor', *actors) def targets(self, *targets): return self._get_gfks('target', *targets) def action_objects(self, *action_objects):",
"self.target_content_type = obj_ct self.target_object_id = obj_id @property def action_object(self): obj_ct = self.action_object_content_type obj_id",
"return (0, {}) delete.queryset_only = True # type: ignore def update(self, **_): return",
"obj_id @property def action_object(self): obj_ct = self.action_object_content_type obj_id = self.action_object_object_id return _get_remote_obj(obj_ct, obj_id)",
"target: obj_ct, obj_id = _get_gfk(target) self.target_content_type = obj_ct self.target_object_id = obj_id @property def",
"{ 'actor': {'ct': 'actor_content_type', 'id': 'actor_object_id'}, 'target': {'ct': 'target_content_type', 'id': 'target_object_id'}, 'action_object': {",
"data[field] = kwargs[field] return data class EventLogQuerySet(models.QuerySet): def delete(self): return (0, {}) delete.queryset_only",
"self.action_object_content_type obj_id = self.action_object_object_id return _get_remote_obj(obj_ct, obj_id) @action_object.setter def action_object(self, action_object): if action_object:",
"`actor` is required. `verb` is a short string, preferrably an infinitive. It should",
"= {} data['actor'] = _serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object']) # copy",
"self.action_object_object_id return _get_remote_obj(obj_ct, obj_id) @action_object.setter def action_object(self, action_object): if action_object: obj_ct, obj_id =",
"_serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object']) # copy the rest for field",
"null=True, related_name='action_object', db_index=True) action_object_object_id = models.TextField(blank=True, null=True, db_index=True) data = models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp",
"return qs.distinct() class EventLogManager(models.Manager): def log_event(self, actor, verb, target=None, action_object=None, description_template='', timestamp=None, extra=None,",
"functools import reduce from operator import or_ from copy import deepcopy from django.contrib.contenttypes.models",
"import DjangoJSONEncoder from django.db import models from django.utils.timezone import now as tznow GFK_MAPPER",
"import ContentType from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.utils.timezone import",
"not allowed return (0, {}) @property def actor(self): obj_ct = self.actor_content_type obj_id =",
"= models.TextField(blank=True, null=True, db_index=True) data = models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow, db_index=True) objects",
"= self.actor_object_id return _get_remote_obj(obj_ct, obj_id) @actor.setter def actor(self, actor): obj_ct, obj_id = _get_gfk(actor)",
"copy import deepcopy from django.contrib.contenttypes.models import ContentType from django.core.serializers.json import DjangoJSONEncoder from django.db",
"AttributeError: obj = delazify_object(obj) objstring = repr(obj).strip('<>') return objstring def _format_timestamp(timestamp): \"Print timestamp",
"q_objs = [] for obj in objects: if not obj: continue obj_ct, obj_id",
"= GFK_MAPPER[field]['id'] q_objs = [] for obj in objects: if not obj: continue",
"description = _format_description(locals(), description_template) data = _serialize_event(locals()) return self.create( actor=actor, target=target, action_object=action_object, verb=verb,",
"= _serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object']) # copy the rest for",
"| self.action_objects(obj) return qs.distinct() class EventLogManager(models.Manager): def log_event(self, actor, verb, target=None, action_object=None, description_template='',",
"`timestamp` must be a datetime with timezone `extra` must be JSON serializable, preferrably",
"serializer compatible format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC', 'Z', 1) return timestamp",
"JSON serializable, preferrably a dict. The info will be added to the `data`-field,",
"qs.distinct() class EventLogManager(models.Manager): def log_event(self, actor, verb, target=None, action_object=None, description_template='', timestamp=None, extra=None, using=None):",
"field in ('actor', 'target', 'action_object'): obj = kwargs[field] if not obj: continue objstring",
"from the other arguments. `timestamp` must be a datetime with timezone `extra` must",
"if isinstance(obj, dict): ct = obj['ct'] pk = obj['pk'] value = obj['value'] else:",
"allowed return (0, {}) @property def actor(self): obj_ct = self.actor_content_type obj_id = self.actor_object_id",
"class Meta: ordering = ('-timestamp',) def __str__(self): return self.description def delete(self, **_): #",
"are model instances. `actor` is required. `verb` is a short string, preferrably an",
"objstring def _format_timestamp(timestamp): \"Print timestamp in JSON serializer compatible format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z')",
"class EventLogQuerySet(models.QuerySet): def delete(self): return (0, {}) delete.queryset_only = True # type: ignore",
"obj_id = self.target_object_id return _get_remote_obj(obj_ct, obj_id) @target.setter def target(self, target): if target: obj_ct,",
"be a datetime with timezone `extra` must be JSON serializable, preferrably a dict.",
"action_objects(self, *action_objects): return self._get_gfks('action_object', *action_objects) def model_actions(self, model): ct = ContentType.objects.get_for_model(model) return self.filter(",
"operator import or_ from copy import deepcopy from django.contrib.contenttypes.models import ContentType from django.core.serializers.json",
"null=True, db_index=True) action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object', db_index=True) action_object_object_id = models.TextField(blank=True,",
"preferrably a dict. The info will be added to the `data`-field, and may",
"= models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object', db_index=True) action_object_object_id = models.TextField(blank=True, null=True, db_index=True) data",
"GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id'] q_objs = [] for obj in objects: if not",
"def actor(self): obj_ct = self.actor_content_type obj_id = self.actor_object_id return _get_remote_obj(obj_ct, obj_id) @actor.setter def",
"= self.action_object_content_type obj_id = self.action_object_object_id return _get_remote_obj(obj_ct, obj_id) @action_object.setter def action_object(self, action_object): if",
"up from the `description_template`. \"\"\" timestamp = timestamp if timestamp else tznow() description",
"the model instances of `actor`, `target` or `action_object`. `description_template` is used to build",
"string from the other arguments. `timestamp` must be a datetime with timezone `extra`",
"reduce from operator import or_ from copy import deepcopy from django.contrib.contenttypes.models import ContentType",
"db_index=True) data = models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp = models.DateTimeField(default=tznow, db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)() class",
"= obj['ct'] pk = obj['pk'] value = obj['value'] else: ct, pk = _get_gfk(obj)",
"return self.filter(reduce(or_, q_objs)) def actors(self, *actors): return self._get_gfks('actor', *actors) def targets(self, *targets): return",
"timestamp = timestamp.replace('UTC', 'Z', 1) return timestamp def _format_description(kwargs, description_template): context = deepcopy(kwargs)",
"self.action_objects(obj) return qs.distinct() class EventLogManager(models.Manager): def log_event(self, actor, verb, target=None, action_object=None, description_template='', timestamp=None,",
"import or_ from copy import deepcopy from django.contrib.contenttypes.models import ContentType from django.core.serializers.json import",
"= self.actors(obj) | self.targets(obj) | self.action_objects(obj) return qs.distinct() class EventLogManager(models.Manager): def log_event(self, actor,",
"obj_ct.get_object_for_this_type(pk=obj_id) return obj def _serialize_gfk(obj): if not obj: return if isinstance(obj, dict): ct",
"and hasattr(obj, '_setup'): if obj._wrapped.__class__ == object: obj._setup() obj = obj._wrapped return obj",
"= obj_id @property def target(self): obj_ct = self.target_content_type obj_id = self.target_object_id return _get_remote_obj(obj_ct,",
"objstring = repr(obj).strip('<>') return objstring def _format_timestamp(timestamp): \"Print timestamp in JSON serializer compatible",
"'target_object_id'}, 'action_object': { 'ct': 'action_object_content_type', 'id': 'action_object_object_id' }, } Q = models.Q def",
"= kwargs[field] if not obj: continue objstring = _format_obj(obj) context[field] = objstring return",
"`target` and `action_object` are model instances. `actor` is required. `verb` is a short",
"'ct': 'action_object_content_type', 'id': 'action_object_object_id' }, } Q = models.Q def _get_gfk(obj): obj_ct =",
"# copy the rest for field in ('verb', 'description', 'timestamp', 'extra'): data[field] =",
"model): ct = ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), ) def any(self, obj):",
"objects = EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering = ('-timestamp',) def __str__(self): return self.description def",
"{} data['actor'] = _serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object']) # copy the",
"instances. `actor` is required. `verb` is a short string, preferrably an infinitive. It",
"obj = obj._wrapped return obj def _format_obj(obj): try: objstring = obj.logprint() except AttributeError:",
"else: ct, pk = _get_gfk(obj) value = str(obj) return { 'ct': {'pk': ct.pk,",
"and `action_object` are model instances. `actor` is required. `verb` is a short string,",
"field, *objects): ct = GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id'] q_objs = [] for obj",
"self._get_gfks('action_object', *action_objects) def model_actions(self, model): ct = ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct),",
"timezone `extra` must be JSON serializable, preferrably a dict. The info will be",
"log_event(self, actor, verb, target=None, action_object=None, description_template='', timestamp=None, extra=None, using=None): \"\"\"Log event `actor`, `target`",
"obj_id = self.action_object_object_id return _get_remote_obj(obj_ct, obj_id) @action_object.setter def action_object(self, action_object): if action_object: obj_ct,",
"from django.contrib.contenttypes.models import ContentType from django.core.serializers.json import DjangoJSONEncoder from django.db import models from",
"def _serialize_event(kwargs): data = {} data['actor'] = _serialize_gfk(kwargs['actor']) data['target'] = _serialize_gfk(kwargs['target']) data['action_object'] =",
"('actor', 'target', 'action_object'): obj = kwargs[field] if not obj: continue objstring = _format_obj(obj)",
"import deepcopy from django.contrib.contenttypes.models import ContentType from django.core.serializers.json import DjangoJSONEncoder from django.db import",
"self.actor_content_type = obj_ct self.actor_object_id = obj_id @property def target(self): obj_ct = self.target_content_type obj_id",
"return self.description def delete(self, **_): # Deletion not allowed return (0, {}) @property",
"target(self): obj_ct = self.target_content_type obj_id = self.target_object_id return _get_remote_obj(obj_ct, obj_id) @target.setter def target(self,",
"if not obj: continue objstring = _format_obj(obj) context[field] = objstring return description_template.format(**context) def",
"Meta: ordering = ('-timestamp',) def __str__(self): return self.description def delete(self, **_): # Deletion",
"= True # type: ignore def update(self, **_): return 0 update.queryset_only = True",
"about the model instances of `actor`, `target` or `action_object`. `description_template` is used to",
"= obj._wrapped return obj def _format_obj(obj): try: objstring = obj.logprint() except AttributeError: obj",
"'actor_content_type', 'id': 'actor_object_id'}, 'target': {'ct': 'target_content_type', 'id': 'target_object_id'}, 'action_object': { 'ct': 'action_object_content_type', 'id':",
"if obj._wrapped.__class__ == object: obj._setup() obj = obj._wrapped return obj def _format_obj(obj): try:",
"__str__(self): return self.description def delete(self, **_): # Deletion not allowed return (0, {})",
"obj._wrapped.__class__ == object: obj._setup() obj = obj._wrapped return obj def _format_obj(obj): try: objstring",
"`target` or `action_object`. `description_template` is used to build a human-readble string from the",
"self.actor_object_id = obj_id @property def target(self): obj_ct = self.target_content_type obj_id = self.target_object_id return",
"type: ignore def update(self, **_): return 0 update.queryset_only = True # type: ignore",
"def actors(self, *actors): return self._get_gfks('actor', *actors) def targets(self, *targets): return self._get_gfks('target', *targets) def",
"target_object_id = models.TextField(blank=True, null=True, db_index=True) action_object_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object', db_index=True)",
"description_template): context = deepcopy(kwargs) context['timestamp'] = _format_timestamp(context['timestamp']) for field in ('actor', 'target', 'action_object'):",
"def _format_timestamp(timestamp): \"Print timestamp in JSON serializer compatible format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp",
"duplicate information about the model instances of `actor`, `target` or `action_object`. `description_template` is",
"return _get_remote_obj(obj_ct, obj_id) @actor.setter def actor(self, actor): obj_ct, obj_id = _get_gfk(actor) self.actor_content_type =",
"= ContentType.objects.get_for_model(model) return self.filter( Q(actor_content_type=ct), Q(target_content_type=ct), Q(action_object_content_type=ct), ) def any(self, obj): ct =",
"id: obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs)) def actors(self, *actors): return self._get_gfks('actor', *actors) def",
"actor, verb, target=None, action_object=None, description_template='', timestamp=None, extra=None, using=None): \"\"\"Log event `actor`, `target` and",
"= obj['pk'] value = obj['value'] else: ct, pk = _get_gfk(obj) value = str(obj)",
"dict. The info will be added to the `data`-field, and may be looked",
"_serialize_event(locals()) return self.create( actor=actor, target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data, ) class EventLog(models.Model):",
"and may be looked up from the `description_template`. \"\"\" timestamp = timestamp if",
"pk = obj['pk'] value = obj['value'] else: ct, pk = _get_gfk(obj) value =",
"obj_id = _get_gfk(obj) lookups = {ct: obj_ct, id: obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs))",
"*actors) def targets(self, *targets): return self._get_gfks('target', *targets) def action_objects(self, *action_objects): return self._get_gfks('action_object', *action_objects)",
"on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id = models.TextField(db_index=True) verb = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True,",
"True # type: ignore def update(self, **_): return 0 update.queryset_only = True #",
"= self.actor_content_type obj_id = self.actor_object_id return _get_remote_obj(obj_ct, obj_id) @actor.setter def actor(self, actor): obj_ct,",
"is a short string, preferrably an infinitive. It should not duplicate information about",
"= _serialize_gfk(kwargs['target']) data['action_object'] = _serialize_gfk(kwargs['action_object']) # copy the rest for field in ('verb',",
"= _serialize_gfk(kwargs['action_object']) # copy the rest for field in ('verb', 'description', 'timestamp', 'extra'):",
"obj_ct and obj_id: obj = obj_ct.get_object_for_this_type(pk=obj_id) return obj def _serialize_gfk(obj): if not obj:",
"data class EventLogQuerySet(models.QuerySet): def delete(self): return (0, {}) delete.queryset_only = True # type:",
"description = models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target', db_index=True) target_object_id",
"= obj_ct.get_object_for_this_type(pk=obj_id) return obj def _serialize_gfk(obj): if not obj: return if isinstance(obj, dict):",
"obj.pk return (obj_ct, obj_id) def _get_remote_obj(obj_ct, obj_id): if obj_ct and obj_id: obj =",
"timestamp = models.DateTimeField(default=tznow, db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering = ('-timestamp',) def",
"obj['ct'] pk = obj['pk'] value = obj['value'] else: ct, pk = _get_gfk(obj) value",
"class EventLog(models.Model): actor_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id = models.TextField(db_index=True) verb =",
"string, preferrably an infinitive. It should not duplicate information about the model instances",
"{}) delete.queryset_only = True # type: ignore def update(self, **_): return 0 update.queryset_only",
"def delazify_object(obj): if hasattr(obj, '_wrapped') and hasattr(obj, '_setup'): if obj._wrapped.__class__ == object: obj._setup()",
"= timestamp.replace('UTC', 'Z', 1) return timestamp def _format_description(kwargs, description_template): context = deepcopy(kwargs) context['timestamp']",
"models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='action_object', db_index=True) action_object_object_id = models.TextField(blank=True, null=True, db_index=True) data =",
"def log_event(self, actor, verb, target=None, action_object=None, description_template='', timestamp=None, extra=None, using=None): \"\"\"Log event `actor`,",
"def __str__(self): return self.description def delete(self, **_): # Deletion not allowed return (0,",
"obj_ct = self.action_object_content_type obj_id = self.action_object_object_id return _get_remote_obj(obj_ct, obj_id) @action_object.setter def action_object(self, action_object):",
"_get_gfk(obj) lookups = {ct: obj_ct, id: obj_id} q_objs.append(Q(**lookups)) return self.filter(reduce(or_, q_objs)) def actors(self,",
"models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='actor', db_index=True) actor_object_id = models.TextField(db_index=True) verb = models.CharField(max_length=255, db_index=True) description =",
"ignore def _get_gfks(self, field, *objects): ct = GFK_MAPPER[field]['ct'] id = GFK_MAPPER[field]['id'] q_objs =",
"= models.TextField(blank=True, null=True) target_content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='target', db_index=True) target_object_id =",
"timestamp in JSON serializer compatible format\" timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f%Z') timestamp = timestamp.replace('UTC', 'Z',",
"@property def actor(self): obj_ct = self.actor_content_type obj_id = self.actor_object_id return _get_remote_obj(obj_ct, obj_id) @actor.setter",
"context[field] = objstring return description_template.format(**context) def _serialize_event(kwargs): data = {} data['actor'] = _serialize_gfk(kwargs['actor'])",
"related_name='action_object', db_index=True) action_object_object_id = models.TextField(blank=True, null=True, db_index=True) data = models.JSONField(default=dict, encoder=DjangoJSONEncoder) timestamp =",
"is required. `verb` is a short string, preferrably an infinitive. It should not",
"return self._get_gfks('target', *targets) def action_objects(self, *action_objects): return self._get_gfks('action_object', *action_objects) def model_actions(self, model): ct",
"or `action_object`. `description_template` is used to build a human-readble string from the other",
"obj = kwargs[field] if not obj: continue objstring = _format_obj(obj) context[field] = objstring",
"models.DateTimeField(default=tznow, db_index=True) objects = EventLogManager.from_queryset(EventLogQuerySet)() class Meta: ordering = ('-timestamp',) def __str__(self): return",
"field in ('verb', 'description', 'timestamp', 'extra'): data[field] = kwargs[field] return data class EventLogQuerySet(models.QuerySet):"
] |
[
"# python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a = {'a': 1, 'b':",
"<filename>trypython/basic/dict_/dict02.py<gh_stars>1-10 \"\"\" ディクショナリについてのサンプルです。 dict の マージ について (Python 3.5 以降で有効) \"\"\" from trypython.common.commoncls",
"# ------------------------------------------------------------ # ディクショナリのマージ # # python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------",
"{'a': 10, 'd': 40} pr('merge3', {**merged, **dict_d}) def go(): obj = Sample() obj.exec()",
"**dict_b} pr('merged', merged) dict_c = {'f': 5, 'g': 6} pr('merged2', {**merged, **dict_c}) #",
"3.5 以降で有効) \"\"\" from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr class Sample(SampleBase):",
"python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a = {'a': 1, 'b': 2}",
"(Python 3.5 以降で有効) \"\"\" from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr class",
"5, 'g': 6} pr('merged2', {**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d = {'a': 10, 'd':",
"# 同じ要素がある場合、後の要素で上書きされる dict_d = {'a': 10, 'd': 40} pr('merge3', {**merged, **dict_d}) def go():",
"import pr class Sample(SampleBase): def exec(self): # ------------------------------------------------------------ # ディクショナリのマージ # # python",
"{'c': 3, 'd': 4} merged = {**dict_a, **dict_b} pr('merged', merged) dict_c = {'f':",
"= {'a': 10, 'd': 40} pr('merge3', {**merged, **dict_d}) def go(): obj = Sample()",
"SampleBase from trypython.common.commonfunc import pr class Sample(SampleBase): def exec(self): # ------------------------------------------------------------ # ディクショナリのマージ",
"'b': 2} dict_b = {'c': 3, 'd': 4} merged = {**dict_a, **dict_b} pr('merged',",
"pr('merged', merged) dict_c = {'f': 5, 'g': 6} pr('merged2', {**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる",
"{**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d = {'a': 10, 'd': 40} pr('merge3', {**merged, **dict_d})",
"\"\"\" from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr class Sample(SampleBase): def exec(self):",
"ディクショナリのマージ # # python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a = {'a':",
"# ------------------------------------------------------------ dict_a = {'a': 1, 'b': 2} dict_b = {'c': 3, 'd':",
"dict_c = {'f': 5, 'g': 6} pr('merged2', {**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d =",
"def exec(self): # ------------------------------------------------------------ # ディクショナリのマージ # # python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能)",
"{**dict_a, **dict_b} pr('merged', merged) dict_c = {'f': 5, 'g': 6} pr('merged2', {**merged, **dict_c})",
"trypython.common.commonfunc import pr class Sample(SampleBase): def exec(self): # ------------------------------------------------------------ # ディクショナリのマージ # #",
"# 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a = {'a': 1, 'b': 2} dict_b = {'c':",
"------------------------------------------------------------ dict_a = {'a': 1, 'b': 2} dict_b = {'c': 3, 'd': 4}",
"{'f': 5, 'g': 6} pr('merged2', {**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d = {'a': 10,",
"pr class Sample(SampleBase): def exec(self): # ------------------------------------------------------------ # ディクショナリのマージ # # python 3.5",
"2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a = {'a': 1, 'b': 2} dict_b = {'c': 3,",
"# ディクショナリのマージ # # python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a =",
"= {'a': 1, 'b': 2} dict_b = {'c': 3, 'd': 4} merged =",
"dict_b = {'c': 3, 'd': 4} merged = {**dict_a, **dict_b} pr('merged', merged) dict_c",
"6} pr('merged2', {**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d = {'a': 10, 'd': 40} pr('merge3',",
"exec(self): # ------------------------------------------------------------ # ディクショナリのマージ # # python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) #",
"について (Python 3.5 以降で有効) \"\"\" from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr",
"# # python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a = {'a': 1,",
"= {'f': 5, 'g': 6} pr('merged2', {**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d = {'a':",
"dict の マージ について (Python 3.5 以降で有効) \"\"\" from trypython.common.commoncls import SampleBase from",
"**dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d = {'a': 10, 'd': 40} pr('merge3', {**merged, **dict_d}) def",
"import SampleBase from trypython.common.commonfunc import pr class Sample(SampleBase): def exec(self): # ------------------------------------------------------------ #",
"2} dict_b = {'c': 3, 'd': 4} merged = {**dict_a, **dict_b} pr('merged', merged)",
"3, 'd': 4} merged = {**dict_a, **dict_b} pr('merged', merged) dict_c = {'f': 5,",
"dict_d = {'a': 10, 'd': 40} pr('merge3', {**merged, **dict_d}) def go(): obj =",
"の マージ について (Python 3.5 以降で有効) \"\"\" from trypython.common.commoncls import SampleBase from trypython.common.commonfunc",
"'d': 4} merged = {**dict_a, **dict_b} pr('merged', merged) dict_c = {'f': 5, 'g':",
"1, 'b': 2} dict_b = {'c': 3, 'd': 4} merged = {**dict_a, **dict_b}",
"ディクショナリについてのサンプルです。 dict の マージ について (Python 3.5 以降で有効) \"\"\" from trypython.common.commoncls import SampleBase",
"dict_a = {'a': 1, 'b': 2} dict_b = {'c': 3, 'd': 4} merged",
"from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr class Sample(SampleBase): def exec(self): #",
"3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a = {'a': 1, 'b': 2} dict_b",
"= {'c': 3, 'd': 4} merged = {**dict_a, **dict_b} pr('merged', merged) dict_c =",
"以降で有効) \"\"\" from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr class Sample(SampleBase): def",
"------------------------------------------------------------ # ディクショナリのマージ # # python 3.5 以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a",
"merged = {**dict_a, **dict_b} pr('merged', merged) dict_c = {'f': 5, 'g': 6} pr('merged2',",
"from trypython.common.commonfunc import pr class Sample(SampleBase): def exec(self): # ------------------------------------------------------------ # ディクショナリのマージ #",
"'g': 6} pr('merged2', {**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d = {'a': 10, 'd': 40}",
"同じ要素がある場合、後の要素で上書きされる dict_d = {'a': 10, 'd': 40} pr('merge3', {**merged, **dict_d}) def go(): obj",
"\"\"\" ディクショナリについてのサンプルです。 dict の マージ について (Python 3.5 以降で有効) \"\"\" from trypython.common.commoncls import",
"マージ について (Python 3.5 以降で有効) \"\"\" from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import",
"trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr class Sample(SampleBase): def exec(self): # ------------------------------------------------------------",
"{'a': 1, 'b': 2} dict_b = {'c': 3, 'd': 4} merged = {**dict_a,",
"4} merged = {**dict_a, **dict_b} pr('merged', merged) dict_c = {'f': 5, 'g': 6}",
"pr('merged2', {**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d = {'a': 10, 'd': 40} pr('merge3', {**merged,",
"Sample(SampleBase): def exec(self): # ------------------------------------------------------------ # ディクショナリのマージ # # python 3.5 以降であれば以下のようにして #",
"= {**dict_a, **dict_b} pr('merged', merged) dict_c = {'f': 5, 'g': 6} pr('merged2', {**merged,",
"merged) dict_c = {'f': 5, 'g': 6} pr('merged2', {**merged, **dict_c}) # 同じ要素がある場合、後の要素で上書きされる dict_d",
"class Sample(SampleBase): def exec(self): # ------------------------------------------------------------ # ディクショナリのマージ # # python 3.5 以降であれば以下のようにして",
"以降であれば以下のようにして # 2つのディクショナリをマージできる。(いくつでも可能) # ------------------------------------------------------------ dict_a = {'a': 1, 'b': 2} dict_b ="
] |
[
"save_json(file_path, self) @classmethod def load(cls, file_path: Path): data = parse_json(file_path) return cls(data) @classmethod",
"@classmethod def load(cls, file_path: Path): data = parse_json(file_path) return cls(data) @classmethod def fromcounter(cls,",
"import Counter, OrderedDict from pathlib import Path from text_utils.utils import parse_json, save_json class",
"Path from text_utils.utils import parse_json, save_json class SymbolsDict(OrderedDict): # Tuple[str, int] def save(self,",
"def load(cls, file_path: Path): data = parse_json(file_path) return cls(data) @classmethod def fromcounter(cls, counter:",
"file_path: Path): data = parse_json(file_path) return cls(data) @classmethod def fromcounter(cls, counter: Counter): return",
"load(cls, file_path: Path): data = parse_json(file_path) return cls(data) @classmethod def fromcounter(cls, counter: Counter):",
"collections import Counter, OrderedDict from pathlib import Path from text_utils.utils import parse_json, save_json",
"# Tuple[str, int] def save(self, file_path: Path): save_json(file_path, self) @classmethod def load(cls, file_path:",
"import Path from text_utils.utils import parse_json, save_json class SymbolsDict(OrderedDict): # Tuple[str, int] def",
"SymbolsDict(OrderedDict): # Tuple[str, int] def save(self, file_path: Path): save_json(file_path, self) @classmethod def load(cls,",
"parse_json, save_json class SymbolsDict(OrderedDict): # Tuple[str, int] def save(self, file_path: Path): save_json(file_path, self)",
"file_path: Path): save_json(file_path, self) @classmethod def load(cls, file_path: Path): data = parse_json(file_path) return",
"self) @classmethod def load(cls, file_path: Path): data = parse_json(file_path) return cls(data) @classmethod def",
"Tuple[str, int] def save(self, file_path: Path): save_json(file_path, self) @classmethod def load(cls, file_path: Path):",
"int] def save(self, file_path: Path): save_json(file_path, self) @classmethod def load(cls, file_path: Path): data",
"OrderedDict from pathlib import Path from text_utils.utils import parse_json, save_json class SymbolsDict(OrderedDict): #",
"save(self, file_path: Path): save_json(file_path, self) @classmethod def load(cls, file_path: Path): data = parse_json(file_path)",
"text_utils.utils import parse_json, save_json class SymbolsDict(OrderedDict): # Tuple[str, int] def save(self, file_path: Path):",
"from collections import Counter, OrderedDict from pathlib import Path from text_utils.utils import parse_json,",
"def save(self, file_path: Path): save_json(file_path, self) @classmethod def load(cls, file_path: Path): data =",
"<filename>src/text_utils/symbols_dict.py<gh_stars>0 from collections import Counter, OrderedDict from pathlib import Path from text_utils.utils import",
"Path): data = parse_json(file_path) return cls(data) @classmethod def fromcounter(cls, counter: Counter): return cls(counter.most_common())",
"save_json class SymbolsDict(OrderedDict): # Tuple[str, int] def save(self, file_path: Path): save_json(file_path, self) @classmethod",
"import parse_json, save_json class SymbolsDict(OrderedDict): # Tuple[str, int] def save(self, file_path: Path): save_json(file_path,",
"from pathlib import Path from text_utils.utils import parse_json, save_json class SymbolsDict(OrderedDict): # Tuple[str,",
"Path): save_json(file_path, self) @classmethod def load(cls, file_path: Path): data = parse_json(file_path) return cls(data)",
"pathlib import Path from text_utils.utils import parse_json, save_json class SymbolsDict(OrderedDict): # Tuple[str, int]",
"Counter, OrderedDict from pathlib import Path from text_utils.utils import parse_json, save_json class SymbolsDict(OrderedDict):",
"from text_utils.utils import parse_json, save_json class SymbolsDict(OrderedDict): # Tuple[str, int] def save(self, file_path:",
"class SymbolsDict(OrderedDict): # Tuple[str, int] def save(self, file_path: Path): save_json(file_path, self) @classmethod def"
] |
[
"# Copyright 2016 NXP # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause #",
"# All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # # Generated by erpcgen",
"23 13:00:45 2019. # # AUTOGENERATED - DO NOT EDIT # import erpc",
"Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESSED_ID = 1 #Return which button was pressed def",
"Freescale Semiconductor, Inc. # Copyright 2016 NXP # All rights reserved. # #",
"# import erpc # Abstract base class for remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID =",
"2 BUTTON_PRESSED_ID = 1 #Return which button was pressed def button_pressed(self, which): raise",
"NOT EDIT # import erpc # Abstract base class for remote_control_app_1 class Iremote_control_app_1(object):",
"2019. # # AUTOGENERATED - DO NOT EDIT # import erpc # Abstract",
"BSD-3-Clause # # Generated by erpcgen 1.7.3 on Mon Sep 23 13:00:45 2019.",
"remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESSED_ID = 1 #Return which button was",
"class Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESSED_ID = 1 #Return which button was pressed",
"rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # # Generated by erpcgen 1.7.3 on",
"DO NOT EDIT # import erpc # Abstract base class for remote_control_app_1 class",
"Mon Sep 23 13:00:45 2019. # # AUTOGENERATED - DO NOT EDIT #",
"erpc # Abstract base class for remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESSED_ID",
"Sep 23 13:00:45 2019. # # AUTOGENERATED - DO NOT EDIT # import",
"13:00:45 2019. # # AUTOGENERATED - DO NOT EDIT # import erpc #",
"BUTTON_PRESSED_ID = 1 #Return which button was pressed def button_pressed(self, which): raise NotImplementedError()",
"Inc. # Copyright 2016 NXP # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause",
"2016 NXP # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # # Generated",
"SPDX-License-Identifier: BSD-3-Clause # # Generated by erpcgen 1.7.3 on Mon Sep 23 13:00:45",
"Semiconductor, Inc. # Copyright 2016 NXP # All rights reserved. # # SPDX-License-Identifier:",
"# AUTOGENERATED - DO NOT EDIT # import erpc # Abstract base class",
"# SPDX-License-Identifier: BSD-3-Clause # # Generated by erpcgen 1.7.3 on Mon Sep 23",
"# Abstract base class for remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESSED_ID =",
"All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # # Generated by erpcgen 1.7.3",
"# Generated by erpcgen 1.7.3 on Mon Sep 23 13:00:45 2019. # #",
"import erpc # Abstract base class for remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID = 2",
"Copyright (c) 2014-2016, Freescale Semiconductor, Inc. # Copyright 2016 NXP # All rights",
"- DO NOT EDIT # import erpc # Abstract base class for remote_control_app_1",
"EDIT # import erpc # Abstract base class for remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID",
"SERVICE_ID = 2 BUTTON_PRESSED_ID = 1 #Return which button was pressed def button_pressed(self,",
"= 2 BUTTON_PRESSED_ID = 1 #Return which button was pressed def button_pressed(self, which):",
"reserved. # # SPDX-License-Identifier: BSD-3-Clause # # Generated by erpcgen 1.7.3 on Mon",
"# Copyright (c) 2014-2016, Freescale Semiconductor, Inc. # Copyright 2016 NXP # All",
"on Mon Sep 23 13:00:45 2019. # # AUTOGENERATED - DO NOT EDIT",
"# # SPDX-License-Identifier: BSD-3-Clause # # Generated by erpcgen 1.7.3 on Mon Sep",
"# # AUTOGENERATED - DO NOT EDIT # import erpc # Abstract base",
"Copyright 2016 NXP # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # #",
"AUTOGENERATED - DO NOT EDIT # import erpc # Abstract base class for",
"for remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESSED_ID = 1 #Return which button",
"2014-2016, Freescale Semiconductor, Inc. # Copyright 2016 NXP # All rights reserved. #",
"by erpcgen 1.7.3 on Mon Sep 23 13:00:45 2019. # # AUTOGENERATED -",
"class for remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESSED_ID = 1 #Return which",
"# # Generated by erpcgen 1.7.3 on Mon Sep 23 13:00:45 2019. #",
"base class for remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESSED_ID = 1 #Return",
"erpcgen 1.7.3 on Mon Sep 23 13:00:45 2019. # # AUTOGENERATED - DO",
"1.7.3 on Mon Sep 23 13:00:45 2019. # # AUTOGENERATED - DO NOT",
"Generated by erpcgen 1.7.3 on Mon Sep 23 13:00:45 2019. # # AUTOGENERATED",
"NXP # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # # Generated by",
"Abstract base class for remote_control_app_1 class Iremote_control_app_1(object): SERVICE_ID = 2 BUTTON_PRESSED_ID = 1",
"(c) 2014-2016, Freescale Semiconductor, Inc. # Copyright 2016 NXP # All rights reserved."
] |
[
"self.df.at[i, 'Class'] if self.nmax is not None and self.counts[label] >= self.nmax: continue else:",
"+ '.wav' print('\\n', file) try: sr, wav_data = wavfile.read(os.path.join(self.root, 'Train', file)) except Exception",
"file) continue print(type(wav_data), 'original sample rate: ', sr) print(np.min(wav_data), np.max(wav_data)) wav_data = wav_data.astype(np.int16)",
"set into the required format to run the train.py script on it. Download",
"== '__main__': print(os.listdir('data/')) root = 'data/urbansounds_download' save_to = 'data/urbansounds' nmax = 100 proc",
"is not None and self.counts[label] >= self.nmax: continue else: file = str(self.df.at[i, 'ID'])",
"e: print(e) print('not using file ', file) continue print(type(wav_data), 'original sample rate: ',",
"self.labels = self.df.Class.unique() self.counts = {i:0 for i in self.labels} self.delete_download = False",
"plt import pandas as pd import os import shutil from scipy.io import wavfile",
"are different bit depths in the dataset and 24bit leads to issues now",
"run this script TODO: apparently there are different bit depths in the dataset",
"pandas as pd import os import shutil from scipy.io import wavfile class UrbanSoundsProcessor:",
"wavfile class UrbanSoundsProcessor: def __init__(self, root, nmax, save_to): self.root = root self.nmax =",
"self.df = pd.read_csv(os.path.join(root, 'train.csv')) self.labels = self.df.Class.unique() self.counts = {i:0 for i in",
"instances per class (nmax) and run this script TODO: apparently there are different",
"are simply ignored... ''' import numpy as np import matplotlib.pyplot as plt import",
"it. Download the the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip into root specified",
">= self.nmax: continue else: file = str(self.df.at[i, 'ID']) + '.wav' print('\\n', file) try:",
"Exception as e: print(e) print('not using file ', file) continue print(type(wav_data), 'original sample",
"and self.counts[label] >= self.nmax: continue else: file = str(self.df.at[i, 'ID']) + '.wav' print('\\n',",
"required format to run the train.py script on it. Download the the dataset",
"wavfile.write(os.path.join(self.save_to, label, file), rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train', file), # os.path.join(self.save_to, label, file))",
"os import shutil from scipy.io import wavfile class UrbanSoundsProcessor: def __init__(self, root, nmax,",
"= self.df.Class.unique() self.counts = {i:0 for i in self.labels} self.delete_download = False def",
"= str(self.df.at[i, 'ID']) + '.wav' print('\\n', file) try: sr, wav_data = wavfile.read(os.path.join(self.root, 'Train',",
"sounds data set into the required format to run the train.py script on",
"'Train', file), # os.path.join(self.save_to, label, file)) self.counts[label] += 1 total += 1 if",
"self.setup() total = 0 for i in self.df.index: if total >= self.nmax *",
"issues now these files are simply ignored... ''' import numpy as np import",
"for i in self.labels} self.delete_download = False def setup(self): for label in self.labels:",
"total >= self.nmax * len(self.labels): print('done loading {} instances each'.format(self.nmax)) break label =",
"run(self): self.setup() total = 0 for i in self.df.index: if total >= self.nmax",
"if total >= self.nmax * len(self.labels): print('done loading {} instances each'.format(self.nmax)) break label",
"total += 1 if self.delete_download: shutil.rmtree(self.root) if __name__ == '__main__': print(os.listdir('data/')) root =",
"using file ', file) continue print(type(wav_data), 'original sample rate: ', sr) print(np.min(wav_data), np.max(wav_data))",
"os.path.join(self.save_to, label, file)) self.counts[label] += 1 total += 1 if self.delete_download: shutil.rmtree(self.root) if",
"'Class'] if self.nmax is not None and self.counts[label] >= self.nmax: continue else: file",
"'data/urbansounds_download' save_to = 'data/urbansounds' nmax = 100 proc = UrbanSoundsProcessor(root, nmax, save_to) proc.run()",
"as pd import os import shutil from scipy.io import wavfile class UrbanSoundsProcessor: def",
"nmax self.save_to = save_to self.df = pd.read_csv(os.path.join(root, 'train.csv')) self.labels = self.df.Class.unique() self.counts =",
"{} instances each'.format(self.nmax)) break label = self.df.at[i, 'Class'] if self.nmax is not None",
"print(type(wav_data), 'original sample rate: ', sr) print(np.min(wav_data), np.max(wav_data)) wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label,",
"dataset and 24bit leads to issues now these files are simply ignored... '''",
"# shutil.copyfile(os.path.join(self.root, 'Train', file), # os.path.join(self.save_to, label, file)) self.counts[label] += 1 total +=",
"rate: ', sr) print(np.min(wav_data), np.max(wav_data)) wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file), rate=22050, data=wav_data)",
"root specified below, define where the restructured data is saved to (save_to) and",
"to restructure the urban sounds data set into the required format to run",
"class (nmax) and run this script TODO: apparently there are different bit depths",
"and run this script TODO: apparently there are different bit depths in the",
"= pd.read_csv(os.path.join(root, 'train.csv')) self.labels = self.df.Class.unique() self.counts = {i:0 for i in self.labels}",
"0 for i in self.df.index: if total >= self.nmax * len(self.labels): print('done loading",
"def run(self): self.setup() total = 0 for i in self.df.index: if total >=",
"'Train', file)) except Exception as e: print(e) print('not using file ', file) continue",
"to run the train.py script on it. Download the the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification",
"Download the the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip into root specified below,",
"dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip into root specified below, define where the",
"wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file), rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train', file), # os.path.join(self.save_to, label,",
"'train.csv')) self.labels = self.df.Class.unique() self.counts = {i:0 for i in self.labels} self.delete_download =",
">= self.nmax * len(self.labels): print('done loading {} instances each'.format(self.nmax)) break label = self.df.at[i,",
"restructured data is saved to (save_to) and the maxium instances per class (nmax)",
"self.df.index: if total >= self.nmax * len(self.labels): print('done loading {} instances each'.format(self.nmax)) break",
"restructure the urban sounds data set into the required format to run the",
"define where the restructured data is saved to (save_to) and the maxium instances",
"import os import shutil from scipy.io import wavfile class UrbanSoundsProcessor: def __init__(self, root,",
"import matplotlib.pyplot as plt import pandas as pd import os import shutil from",
"setup(self): for label in self.labels: os.makedirs(os.path.join(self.save_to, label)) def run(self): self.setup() total = 0",
"1 if self.delete_download: shutil.rmtree(self.root) if __name__ == '__main__': print(os.listdir('data/')) root = 'data/urbansounds_download' save_to",
"simply ignored... ''' import numpy as np import matplotlib.pyplot as plt import pandas",
"shutil.rmtree(self.root) if __name__ == '__main__': print(os.listdir('data/')) root = 'data/urbansounds_download' save_to = 'data/urbansounds' nmax",
"saved to (save_to) and the maxium instances per class (nmax) and run this",
"self.counts[label] >= self.nmax: continue else: file = str(self.df.at[i, 'ID']) + '.wav' print('\\n', file)",
"label = self.df.at[i, 'Class'] if self.nmax is not None and self.counts[label] >= self.nmax:",
"= self.df.at[i, 'Class'] if self.nmax is not None and self.counts[label] >= self.nmax: continue",
"def setup(self): for label in self.labels: os.makedirs(os.path.join(self.save_to, label)) def run(self): self.setup() total =",
"wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file), rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train', file), #",
"self.delete_download = False def setup(self): for label in self.labels: os.makedirs(os.path.join(self.save_to, label)) def run(self):",
"sample rate: ', sr) print(np.min(wav_data), np.max(wav_data)) wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file), rate=22050,",
"if self.nmax is not None and self.counts[label] >= self.nmax: continue else: file =",
"per class (nmax) and run this script TODO: apparently there are different bit",
"into root specified below, define where the restructured data is saved to (save_to)",
"import wavfile class UrbanSoundsProcessor: def __init__(self, root, nmax, save_to): self.root = root self.nmax",
"nmax, save_to): self.root = root self.nmax = nmax self.save_to = save_to self.df =",
"self.labels} self.delete_download = False def setup(self): for label in self.labels: os.makedirs(os.path.join(self.save_to, label)) def",
"import shutil from scipy.io import wavfile class UrbanSoundsProcessor: def __init__(self, root, nmax, save_to):",
"into the required format to run the train.py script on it. Download the",
"__name__ == '__main__': print(os.listdir('data/')) root = 'data/urbansounds_download' save_to = 'data/urbansounds' nmax = 100",
"the urban sounds data set into the required format to run the train.py",
"depths in the dataset and 24bit leads to issues now these files are",
"files are simply ignored... ''' import numpy as np import matplotlib.pyplot as plt",
"where the restructured data is saved to (save_to) and the maxium instances per",
"None and self.counts[label] >= self.nmax: continue else: file = str(self.df.at[i, 'ID']) + '.wav'",
"sr, wav_data = wavfile.read(os.path.join(self.root, 'Train', file)) except Exception as e: print(e) print('not using",
"self.df.Class.unique() self.counts = {i:0 for i in self.labels} self.delete_download = False def setup(self):",
"there are different bit depths in the dataset and 24bit leads to issues",
"scipy.io import wavfile class UrbanSoundsProcessor: def __init__(self, root, nmax, save_to): self.root = root",
"{i:0 for i in self.labels} self.delete_download = False def setup(self): for label in",
"script on it. Download the the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip into",
"maxium instances per class (nmax) and run this script TODO: apparently there are",
"in self.df.index: if total >= self.nmax * len(self.labels): print('done loading {} instances each'.format(self.nmax))",
"'.wav' print('\\n', file) try: sr, wav_data = wavfile.read(os.path.join(self.root, 'Train', file)) except Exception as",
"try: sr, wav_data = wavfile.read(os.path.join(self.root, 'Train', file)) except Exception as e: print(e) print('not",
"file)) self.counts[label] += 1 total += 1 if self.delete_download: shutil.rmtree(self.root) if __name__ ==",
"self.nmax is not None and self.counts[label] >= self.nmax: continue else: file = str(self.df.at[i,",
"train.zip into root specified below, define where the restructured data is saved to",
"rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train', file), # os.path.join(self.save_to, label, file)) self.counts[label] += 1",
"self.counts[label] += 1 total += 1 if self.delete_download: shutil.rmtree(self.root) if __name__ == '__main__':",
"str(self.df.at[i, 'ID']) + '.wav' print('\\n', file) try: sr, wav_data = wavfile.read(os.path.join(self.root, 'Train', file))",
"self.labels: os.makedirs(os.path.join(self.save_to, label)) def run(self): self.setup() total = 0 for i in self.df.index:",
"= save_to self.df = pd.read_csv(os.path.join(root, 'train.csv')) self.labels = self.df.Class.unique() self.counts = {i:0 for",
"wav_data = wavfile.read(os.path.join(self.root, 'Train', file)) except Exception as e: print(e) print('not using file",
"and 24bit leads to issues now these files are simply ignored... ''' import",
"Then unpack train.zip into root specified below, define where the restructured data is",
"ignored... ''' import numpy as np import matplotlib.pyplot as plt import pandas as",
"pd.read_csv(os.path.join(root, 'train.csv')) self.labels = self.df.Class.unique() self.counts = {i:0 for i in self.labels} self.delete_download",
"except Exception as e: print(e) print('not using file ', file) continue print(type(wav_data), 'original",
"''' script to restructure the urban sounds data set into the required format",
"(save_to) and the maxium instances per class (nmax) and run this script TODO:",
"in self.labels: os.makedirs(os.path.join(self.save_to, label)) def run(self): self.setup() total = 0 for i in",
"+= 1 if self.delete_download: shutil.rmtree(self.root) if __name__ == '__main__': print(os.listdir('data/')) root = 'data/urbansounds_download'",
"1 total += 1 if self.delete_download: shutil.rmtree(self.root) if __name__ == '__main__': print(os.listdir('data/')) root",
"is saved to (save_to) and the maxium instances per class (nmax) and run",
"* len(self.labels): print('done loading {} instances each'.format(self.nmax)) break label = self.df.at[i, 'Class'] if",
"continue else: file = str(self.df.at[i, 'ID']) + '.wav' print('\\n', file) try: sr, wav_data",
"loading {} instances each'.format(self.nmax)) break label = self.df.at[i, 'Class'] if self.nmax is not",
"the dataset and 24bit leads to issues now these files are simply ignored...",
"as plt import pandas as pd import os import shutil from scipy.io import",
"import pandas as pd import os import shutil from scipy.io import wavfile class",
"shutil from scipy.io import wavfile class UrbanSoundsProcessor: def __init__(self, root, nmax, save_to): self.root",
"break label = self.df.at[i, 'Class'] if self.nmax is not None and self.counts[label] >=",
"as e: print(e) print('not using file ', file) continue print(type(wav_data), 'original sample rate:",
"label, file), rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train', file), # os.path.join(self.save_to, label, file)) self.counts[label]",
"print('not using file ', file) continue print(type(wav_data), 'original sample rate: ', sr) print(np.min(wav_data),",
"import numpy as np import matplotlib.pyplot as plt import pandas as pd import",
"in self.labels} self.delete_download = False def setup(self): for label in self.labels: os.makedirs(os.path.join(self.save_to, label))",
"np import matplotlib.pyplot as plt import pandas as pd import os import shutil",
"''' import numpy as np import matplotlib.pyplot as plt import pandas as pd",
"label)) def run(self): self.setup() total = 0 for i in self.df.index: if total",
"the restructured data is saved to (save_to) and the maxium instances per class",
"below, define where the restructured data is saved to (save_to) and the maxium",
"= root self.nmax = nmax self.save_to = save_to self.df = pd.read_csv(os.path.join(root, 'train.csv')) self.labels",
"data set into the required format to run the train.py script on it.",
"file = str(self.df.at[i, 'ID']) + '.wav' print('\\n', file) try: sr, wav_data = wavfile.read(os.path.join(self.root,",
"matplotlib.pyplot as plt import pandas as pd import os import shutil from scipy.io",
"print(np.min(wav_data), np.max(wav_data)) wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file), rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train',",
"class UrbanSoundsProcessor: def __init__(self, root, nmax, save_to): self.root = root self.nmax = nmax",
"self.counts = {i:0 for i in self.labels} self.delete_download = False def setup(self): for",
"not None and self.counts[label] >= self.nmax: continue else: file = str(self.df.at[i, 'ID']) +",
"bit depths in the dataset and 24bit leads to issues now these files",
"False def setup(self): for label in self.labels: os.makedirs(os.path.join(self.save_to, label)) def run(self): self.setup() total",
"in the dataset and 24bit leads to issues now these files are simply",
"'ID']) + '.wav' print('\\n', file) try: sr, wav_data = wavfile.read(os.path.join(self.root, 'Train', file)) except",
"these files are simply ignored... ''' import numpy as np import matplotlib.pyplot as",
"file), # os.path.join(self.save_to, label, file)) self.counts[label] += 1 total += 1 if self.delete_download:",
"'__main__': print(os.listdir('data/')) root = 'data/urbansounds_download' save_to = 'data/urbansounds' nmax = 100 proc =",
"data is saved to (save_to) and the maxium instances per class (nmax) and",
"script TODO: apparently there are different bit depths in the dataset and 24bit",
"sr) print(np.min(wav_data), np.max(wav_data)) wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file), rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root,",
"save_to self.df = pd.read_csv(os.path.join(root, 'train.csv')) self.labels = self.df.Class.unique() self.counts = {i:0 for i",
"+= 1 total += 1 if self.delete_download: shutil.rmtree(self.root) if __name__ == '__main__': print(os.listdir('data/'))",
"if self.delete_download: shutil.rmtree(self.root) if __name__ == '__main__': print(os.listdir('data/')) root = 'data/urbansounds_download' save_to =",
"<reponame>birds-on-mars/birdsonearth<filename>utils/urbansounds.py ''' script to restructure the urban sounds data set into the required",
"24bit leads to issues now these files are simply ignored... ''' import numpy",
"from scipy.io import wavfile class UrbanSoundsProcessor: def __init__(self, root, nmax, save_to): self.root =",
"specified below, define where the restructured data is saved to (save_to) and the",
"root self.nmax = nmax self.save_to = save_to self.df = pd.read_csv(os.path.join(root, 'train.csv')) self.labels =",
"leads to issues now these files are simply ignored... ''' import numpy as",
"= nmax self.save_to = save_to self.df = pd.read_csv(os.path.join(root, 'train.csv')) self.labels = self.df.Class.unique() self.counts",
"different bit depths in the dataset and 24bit leads to issues now these",
"file) try: sr, wav_data = wavfile.read(os.path.join(self.root, 'Train', file)) except Exception as e: print(e)",
"', file) continue print(type(wav_data), 'original sample rate: ', sr) print(np.min(wav_data), np.max(wav_data)) wav_data =",
"to (save_to) and the maxium instances per class (nmax) and run this script",
"wavfile.read(os.path.join(self.root, 'Train', file)) except Exception as e: print(e) print('not using file ', file)",
"https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip into root specified below, define where the restructured data",
"continue print(type(wav_data), 'original sample rate: ', sr) print(np.min(wav_data), np.max(wav_data)) wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to,",
"len(self.labels): print('done loading {} instances each'.format(self.nmax)) break label = self.df.at[i, 'Class'] if self.nmax",
"the required format to run the train.py script on it. Download the the",
"instances each'.format(self.nmax)) break label = self.df.at[i, 'Class'] if self.nmax is not None and",
"root, nmax, save_to): self.root = root self.nmax = nmax self.save_to = save_to self.df",
"format to run the train.py script on it. Download the the dataset from:",
"the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip into root specified below, define where",
"root = 'data/urbansounds_download' save_to = 'data/urbansounds' nmax = 100 proc = UrbanSoundsProcessor(root, nmax,",
"now these files are simply ignored... ''' import numpy as np import matplotlib.pyplot",
"script to restructure the urban sounds data set into the required format to",
"print('done loading {} instances each'.format(self.nmax)) break label = self.df.at[i, 'Class'] if self.nmax is",
"self.nmax * len(self.labels): print('done loading {} instances each'.format(self.nmax)) break label = self.df.at[i, 'Class']",
"= wavfile.read(os.path.join(self.root, 'Train', file)) except Exception as e: print(e) print('not using file ',",
"each'.format(self.nmax)) break label = self.df.at[i, 'Class'] if self.nmax is not None and self.counts[label]",
"print(os.listdir('data/')) root = 'data/urbansounds_download' save_to = 'data/urbansounds' nmax = 100 proc = UrbanSoundsProcessor(root,",
"the maxium instances per class (nmax) and run this script TODO: apparently there",
"', sr) print(np.min(wav_data), np.max(wav_data)) wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file), rate=22050, data=wav_data) #",
"os.makedirs(os.path.join(self.save_to, label)) def run(self): self.setup() total = 0 for i in self.df.index: if",
"np.max(wav_data)) wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file), rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train', file),",
"for label in self.labels: os.makedirs(os.path.join(self.save_to, label)) def run(self): self.setup() total = 0 for",
"UrbanSoundsProcessor: def __init__(self, root, nmax, save_to): self.root = root self.nmax = nmax self.save_to",
"file)) except Exception as e: print(e) print('not using file ', file) continue print(type(wav_data),",
"this script TODO: apparently there are different bit depths in the dataset and",
"self.save_to = save_to self.df = pd.read_csv(os.path.join(root, 'train.csv')) self.labels = self.df.Class.unique() self.counts = {i:0",
"train.py script on it. Download the the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip",
"urban sounds data set into the required format to run the train.py script",
"on it. Download the the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip into root",
"unpack train.zip into root specified below, define where the restructured data is saved",
"self.root = root self.nmax = nmax self.save_to = save_to self.df = pd.read_csv(os.path.join(root, 'train.csv'))",
"label in self.labels: os.makedirs(os.path.join(self.save_to, label)) def run(self): self.setup() total = 0 for i",
"the the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip into root specified below, define",
"= {i:0 for i in self.labels} self.delete_download = False def setup(self): for label",
"data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train', file), # os.path.join(self.save_to, label, file)) self.counts[label] += 1 total",
"else: file = str(self.df.at[i, 'ID']) + '.wav' print('\\n', file) try: sr, wav_data =",
"shutil.copyfile(os.path.join(self.root, 'Train', file), # os.path.join(self.save_to, label, file)) self.counts[label] += 1 total += 1",
"to issues now these files are simply ignored... ''' import numpy as np",
"self.nmax = nmax self.save_to = save_to self.df = pd.read_csv(os.path.join(root, 'train.csv')) self.labels = self.df.Class.unique()",
"run the train.py script on it. Download the the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then",
"i in self.labels} self.delete_download = False def setup(self): for label in self.labels: os.makedirs(os.path.join(self.save_to,",
"numpy as np import matplotlib.pyplot as plt import pandas as pd import os",
"self.nmax: continue else: file = str(self.df.at[i, 'ID']) + '.wav' print('\\n', file) try: sr,",
"# os.path.join(self.save_to, label, file)) self.counts[label] += 1 total += 1 if self.delete_download: shutil.rmtree(self.root)",
"and the maxium instances per class (nmax) and run this script TODO: apparently",
"(nmax) and run this script TODO: apparently there are different bit depths in",
"file ', file) continue print(type(wav_data), 'original sample rate: ', sr) print(np.min(wav_data), np.max(wav_data)) wav_data",
"def __init__(self, root, nmax, save_to): self.root = root self.nmax = nmax self.save_to =",
"TODO: apparently there are different bit depths in the dataset and 24bit leads",
"from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack train.zip into root specified below, define where the restructured",
"= wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file), rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train', file), # os.path.join(self.save_to,",
"as np import matplotlib.pyplot as plt import pandas as pd import os import",
"__init__(self, root, nmax, save_to): self.root = root self.nmax = nmax self.save_to = save_to",
"for i in self.df.index: if total >= self.nmax * len(self.labels): print('done loading {}",
"print('\\n', file) try: sr, wav_data = wavfile.read(os.path.join(self.root, 'Train', file)) except Exception as e:",
"the train.py script on it. Download the the dataset from: https://www.kaggle.com/pavansanagapati/urban-sound-classification Then unpack",
"apparently there are different bit depths in the dataset and 24bit leads to",
"= 0 for i in self.df.index: if total >= self.nmax * len(self.labels): print('done",
"save_to): self.root = root self.nmax = nmax self.save_to = save_to self.df = pd.read_csv(os.path.join(root,",
"print(e) print('not using file ', file) continue print(type(wav_data), 'original sample rate: ', sr)",
"pd import os import shutil from scipy.io import wavfile class UrbanSoundsProcessor: def __init__(self,",
"total = 0 for i in self.df.index: if total >= self.nmax * len(self.labels):",
"'original sample rate: ', sr) print(np.min(wav_data), np.max(wav_data)) wav_data = wav_data.astype(np.int16) wavfile.write(os.path.join(self.save_to, label, file),",
"i in self.df.index: if total >= self.nmax * len(self.labels): print('done loading {} instances",
"= 'data/urbansounds_download' save_to = 'data/urbansounds' nmax = 100 proc = UrbanSoundsProcessor(root, nmax, save_to)",
"self.delete_download: shutil.rmtree(self.root) if __name__ == '__main__': print(os.listdir('data/')) root = 'data/urbansounds_download' save_to = 'data/urbansounds'",
"file), rate=22050, data=wav_data) # shutil.copyfile(os.path.join(self.root, 'Train', file), # os.path.join(self.save_to, label, file)) self.counts[label] +=",
"if __name__ == '__main__': print(os.listdir('data/')) root = 'data/urbansounds_download' save_to = 'data/urbansounds' nmax =",
"label, file)) self.counts[label] += 1 total += 1 if self.delete_download: shutil.rmtree(self.root) if __name__",
"= False def setup(self): for label in self.labels: os.makedirs(os.path.join(self.save_to, label)) def run(self): self.setup()"
] |
[
"return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids = []",
"NotImplementedError def get_exposed_ports(self): raise NotImplementedError def get_docker_version(self): raise NotImplementedError def get_volumes(self): raise NotImplementedError",
"set(layer_ids) def get_volumes(self): return self.__get_first_value('config', 'Volumes') def makeManifest(content): if content['schemaVersion'] == 1: return",
"def __get_first_value(self, *keys): for entry in self.__get_sorted_history(): try: return functools.reduce(operator.getitem, keys, entry) except",
"[] for layer in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids) def get_volumes(self): return self.__get_first_value('config', 'Volumes')",
"get_entrypoint(self): raise NotImplementedError def get_exposed_ports(self): raise NotImplementedError def get_docker_version(self): raise NotImplementedError def get_volumes(self):",
"self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids) def get_volumes(self): return self.__get_first_value('config', 'Volumes') def makeManifest(content): if content['schemaVersion']",
"get_volumes(self): return self.__get_first_value('config', 'Volumes') def makeManifest(content): if content['schemaVersion'] == 1: return DockerRegistrySchema1Manifest(content) else:",
"def __init__(self, content): self._content = content def get_created_date(self): raise NotImplementedError def get_entrypoint(self): raise",
"history = [] for entry in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'], reverse=True) return",
"return self.__get_first_value('config', 'Volumes') def makeManifest(content): if content['schemaVersion'] == 1: return DockerRegistrySchema1Manifest(content) else: raise",
"def get_entrypoint(self): raise NotImplementedError def get_exposed_ports(self): raise NotImplementedError def get_docker_version(self): raise NotImplementedError def",
"for layer in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids) def get_volumes(self): return self.__get_first_value('config', 'Volumes') def",
"self.__get_first_value('config', 'Volumes') def makeManifest(content): if content['schemaVersion'] == 1: return DockerRegistrySchema1Manifest(content) else: raise ValueError",
"*keys): for entry in self.__get_sorted_history(): try: return functools.reduce(operator.getitem, keys, entry) except KeyError: pass",
"x: x['created'], reverse=True) return history def __get_first_value(self, *keys): for entry in self.__get_sorted_history(): try:",
"'ExposedPorts') def get_layer_ids(self): layer_ids = [] for layer in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids)",
"get_created_date(self): raise NotImplementedError def get_entrypoint(self): raise NotImplementedError def get_exposed_ports(self): raise NotImplementedError def get_docker_version(self):",
"import functools import json import operator class DockerRegistryManifest(abc.ABC): def __init__(self, content): self._content =",
"self.__get_first_value('created') def get_docker_version(self): return self.__get_first_value('docker_version') def get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return",
"NotImplementedError def get_volumes(self): raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history = [] for",
"keys, entry) except KeyError: pass return None def get_created_date(self): return self.__get_first_value('created') def get_docker_version(self):",
"'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids = [] for layer",
"abc import functools import json import operator class DockerRegistryManifest(abc.ABC): def __init__(self, content): self._content",
"DockerRegistryManifest(abc.ABC): def __init__(self, content): self._content = content def get_created_date(self): raise NotImplementedError def get_entrypoint(self):",
"functools import json import operator class DockerRegistryManifest(abc.ABC): def __init__(self, content): self._content = content",
"class DockerRegistryManifest(abc.ABC): def __init__(self, content): self._content = content def get_created_date(self): raise NotImplementedError def",
"def get_created_date(self): raise NotImplementedError def get_entrypoint(self): raise NotImplementedError def get_exposed_ports(self): raise NotImplementedError def",
"json import operator class DockerRegistryManifest(abc.ABC): def __init__(self, content): self._content = content def get_created_date(self):",
"get_docker_version(self): raise NotImplementedError def get_volumes(self): raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history =",
"return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids = [] for layer in self._content['fsLayers']: layer_ids.append(layer['blobSum'])",
"= [] for entry in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'], reverse=True) return history",
"get_layer_ids(self): layer_ids = [] for layer in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids) def get_volumes(self):",
"layer_ids.append(layer['blobSum']) return set(layer_ids) def get_volumes(self): return self.__get_first_value('config', 'Volumes') def makeManifest(content): if content['schemaVersion'] ==",
"= [] for layer in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids) def get_volumes(self): return self.__get_first_value('config',",
"NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history = [] for entry in self._content['history']: history.append(json.loads(entry['v1Compatibility']))",
"import abc import functools import json import operator class DockerRegistryManifest(abc.ABC): def __init__(self, content):",
"def get_created_date(self): return self.__get_first_value('created') def get_docker_version(self): return self.__get_first_value('docker_version') def get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint')",
"get_created_date(self): return self.__get_first_value('created') def get_docker_version(self): return self.__get_first_value('docker_version') def get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint') def",
"raise NotImplementedError def get_volumes(self): raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history = []",
"reverse=True) return history def __get_first_value(self, *keys): for entry in self.__get_sorted_history(): try: return functools.reduce(operator.getitem,",
"def get_volumes(self): raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history = [] for entry",
"layer_ids = [] for layer in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids) def get_volumes(self): return",
"None def get_created_date(self): return self.__get_first_value('created') def get_docker_version(self): return self.__get_first_value('docker_version') def get_entrypoint(self): return self.__get_first_value('config',",
"get_docker_version(self): return self.__get_first_value('docker_version') def get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts')",
"history.sort(key=lambda x: x['created'], reverse=True) return history def __get_first_value(self, *keys): for entry in self.__get_sorted_history():",
"NotImplementedError def get_entrypoint(self): raise NotImplementedError def get_exposed_ports(self): raise NotImplementedError def get_docker_version(self): raise NotImplementedError",
"__init__(self, content): self._content = content def get_created_date(self): raise NotImplementedError def get_entrypoint(self): raise NotImplementedError",
"return functools.reduce(operator.getitem, keys, entry) except KeyError: pass return None def get_created_date(self): return self.__get_first_value('created')",
"KeyError: pass return None def get_created_date(self): return self.__get_first_value('created') def get_docker_version(self): return self.__get_first_value('docker_version') def",
"layer in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids) def get_volumes(self): return self.__get_first_value('config', 'Volumes') def makeManifest(content):",
"in self.__get_sorted_history(): try: return functools.reduce(operator.getitem, keys, entry) except KeyError: pass return None def",
"self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids = [] for",
"DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history = [] for entry in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x:",
"try: return functools.reduce(operator.getitem, keys, entry) except KeyError: pass return None def get_created_date(self): return",
"in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids) def get_volumes(self): return self.__get_first_value('config', 'Volumes') def makeManifest(content): if",
"operator class DockerRegistryManifest(abc.ABC): def __init__(self, content): self._content = content def get_created_date(self): raise NotImplementedError",
"raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history = [] for entry in self._content['history']:",
"def get_exposed_ports(self): raise NotImplementedError def get_docker_version(self): raise NotImplementedError def get_volumes(self): raise NotImplementedError class",
"raise NotImplementedError def get_exposed_ports(self): raise NotImplementedError def get_docker_version(self): raise NotImplementedError def get_volumes(self): raise",
"pass return None def get_created_date(self): return self.__get_first_value('created') def get_docker_version(self): return self.__get_first_value('docker_version') def get_entrypoint(self):",
"return history def __get_first_value(self, *keys): for entry in self.__get_sorted_history(): try: return functools.reduce(operator.getitem, keys,",
"history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'], reverse=True) return history def __get_first_value(self, *keys): for entry in",
"for entry in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'], reverse=True) return history def __get_first_value(self,",
"def get_docker_version(self): return self.__get_first_value('docker_version') def get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config',",
"def __get_sorted_history(self): history = [] for entry in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'],",
"get_exposed_ports(self): raise NotImplementedError def get_docker_version(self): raise NotImplementedError def get_volumes(self): raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest):",
"self.__get_sorted_history(): try: return functools.reduce(operator.getitem, keys, entry) except KeyError: pass return None def get_created_date(self):",
"def get_docker_version(self): raise NotImplementedError def get_volumes(self): raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history",
"import json import operator class DockerRegistryManifest(abc.ABC): def __init__(self, content): self._content = content def",
"<filename>docker_registry_frontend/manifest.py import abc import functools import json import operator class DockerRegistryManifest(abc.ABC): def __init__(self,",
"content def get_created_date(self): raise NotImplementedError def get_entrypoint(self): raise NotImplementedError def get_exposed_ports(self): raise NotImplementedError",
"__get_first_value(self, *keys): for entry in self.__get_sorted_history(): try: return functools.reduce(operator.getitem, keys, entry) except KeyError:",
"except KeyError: pass return None def get_created_date(self): return self.__get_first_value('created') def get_docker_version(self): return self.__get_first_value('docker_version')",
"self._content = content def get_created_date(self): raise NotImplementedError def get_entrypoint(self): raise NotImplementedError def get_exposed_ports(self):",
"def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids = [] for layer in",
"class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history = [] for entry in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda",
"def get_layer_ids(self): layer_ids = [] for layer in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return set(layer_ids) def",
"raise NotImplementedError def get_entrypoint(self): raise NotImplementedError def get_exposed_ports(self): raise NotImplementedError def get_docker_version(self): raise",
"= content def get_created_date(self): raise NotImplementedError def get_entrypoint(self): raise NotImplementedError def get_exposed_ports(self): raise",
"get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids =",
"content): self._content = content def get_created_date(self): raise NotImplementedError def get_entrypoint(self): raise NotImplementedError def",
"return None def get_created_date(self): return self.__get_first_value('created') def get_docker_version(self): return self.__get_first_value('docker_version') def get_entrypoint(self): return",
"history def __get_first_value(self, *keys): for entry in self.__get_sorted_history(): try: return functools.reduce(operator.getitem, keys, entry)",
"self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids = [] for layer in self._content['fsLayers']: layer_ids.append(layer['blobSum']) return",
"[] for entry in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'], reverse=True) return history def",
"return self.__get_first_value('docker_version') def get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def",
"def get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids",
"in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'], reverse=True) return history def __get_first_value(self, *keys): for",
"entry) except KeyError: pass return None def get_created_date(self): return self.__get_first_value('created') def get_docker_version(self): return",
"functools.reduce(operator.getitem, keys, entry) except KeyError: pass return None def get_created_date(self): return self.__get_first_value('created') def",
"get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self): layer_ids = [] for layer in self._content['fsLayers']:",
"__get_sorted_history(self): history = [] for entry in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'], reverse=True)",
"NotImplementedError def get_docker_version(self): raise NotImplementedError def get_volumes(self): raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self):",
"x['created'], reverse=True) return history def __get_first_value(self, *keys): for entry in self.__get_sorted_history(): try: return",
"import operator class DockerRegistryManifest(abc.ABC): def __init__(self, content): self._content = content def get_created_date(self): raise",
"return set(layer_ids) def get_volumes(self): return self.__get_first_value('config', 'Volumes') def makeManifest(content): if content['schemaVersion'] == 1:",
"self.__get_first_value('docker_version') def get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self): return self.__get_first_value('config', 'ExposedPorts') def get_layer_ids(self):",
"raise NotImplementedError def get_docker_version(self): raise NotImplementedError def get_volumes(self): raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def",
"entry in self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'], reverse=True) return history def __get_first_value(self, *keys):",
"return self.__get_first_value('created') def get_docker_version(self): return self.__get_first_value('docker_version') def get_entrypoint(self): return self.__get_first_value('config', 'Entrypoint') def get_exposed_ports(self):",
"def get_volumes(self): return self.__get_first_value('config', 'Volumes') def makeManifest(content): if content['schemaVersion'] == 1: return DockerRegistrySchema1Manifest(content)",
"entry in self.__get_sorted_history(): try: return functools.reduce(operator.getitem, keys, entry) except KeyError: pass return None",
"get_volumes(self): raise NotImplementedError class DockerRegistrySchema1Manifest(DockerRegistryManifest): def __get_sorted_history(self): history = [] for entry in",
"self._content['history']: history.append(json.loads(entry['v1Compatibility'])) history.sort(key=lambda x: x['created'], reverse=True) return history def __get_first_value(self, *keys): for entry",
"for entry in self.__get_sorted_history(): try: return functools.reduce(operator.getitem, keys, entry) except KeyError: pass return"
] |
[
"= ' + str(ref_id)): has_result = True print_highlight(row[1] + ': ') print '\\t\\t\\t'",
"True: # ref_id = -1 # continue has_result = False print '' caused_id",
"\"\"\"Print in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): # \"\"\"Write to stdout",
"False: input_text = raw_input(\"Enter the ID you want to trace (Press Enter to",
"+ refs_table + ' where ID = ' + str(rid)): print row[0], row[1]",
"+ '\\n' sys.stdout.write(res) # while r != None: # writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)],",
"if len(sys.argv) == 3: all_refs_file = sys.argv[1]; all_trace_file = sys.argv[2]; else: all_refs_file =",
"TEXT, CONS TEXT, CAUSEDBY TEXT, CAUSEDID INTEGER)') conn.commit() # Dump the data print",
"row[2] + ' --> ' + row[3] print 'Due to:' print_highlight(row[4] + \"\\nCaused",
"data print 'Loading reference data from ' + all_refs_file + '...' f =",
"!= None: # writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)], 'red') # start = r.end(1) #",
"= 'trace.log' #conn = sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\") c = conn.cursor() # Create",
"'...' f = open(all_refs_file) for line in f: sql = 'INSERT INTO '",
"== 0 or auto_mode == False: input_text = raw_input(\"Enter the ID you want",
"sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p = re.compile('\\(([0-9]+)\\)') start = 0 r = p.search(text, start)",
"'...' f = open(all_trace_file) for line in f: sql = 'INSERT INTO '",
"start = r.end(1) r = p.search(text, start) res = res + text[start:len(text)] +",
"0; first_id = 0; for row in c.execute('SELECT * from ' + trace_table",
"NAME, ANNOS from ' + refs_table + ' where ID = ' +",
"r != None: # writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)], 'red') # start = r.end(1)",
"if ref_id == 0 or auto_mode == False: input_text = raw_input(\"Enter the ID",
"'1;34', # 'cyan': '0;36', 'bright green': '1;32', # 'red': '0;31', 'bright cyan': '1;36',",
"+ trace_table + ' VALUES (' is_first = True for s in line.split('|'):",
"!= None: res = res + text[start:r.start(1)] res = res + '\\033[0;31m' +",
"\"\\nCaused by: \" + row[5]) # print_highlight(\"caused by \" + row[5]) first_id =",
"\" + row[5]) first_id = caused_id; caused_id = row[6] # print '' if",
"'cyan': '0;36', 'bright green': '1;32', # 'red': '0;31', 'bright cyan': '1;36', # 'purple':",
"continue has_result = False print '' caused_id = 0; first_id = 0; for",
"+ ',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\") + '\\'' sql",
"+ text[r.start(0):r.end(0)] + '\\033[0m' start = r.end(0) r = p.search(text, start) res =",
"+ text[start:r.start(1)] res = res + '\\033[0;31m' + text[r.start(1):r.end(1)] + '\\033[0m' start =",
"p.search(text, start) res = res + text[start:len(text)] + '\\n' text = res p",
"print_highlight(row[1] + ': ') print '\\t\\t\\t' + row[2] + ' --> ' +",
"the ID you want to trace (Press Enter to exit): \") try: ref_id",
"#!/usr/bin/env python import sqlite3 import sys import re auto_mode = True #codeCodes =",
"0 or first_id == caused_id: ref_id = caused_id else: ref_id = 0 conn.close()",
"'(ID INTEGER, NAME TEXT, OLD_ANNOS TEXT, NEW_ANNOS TEXT, CONS TEXT, CAUSEDBY TEXT, CAUSEDID",
"True for s in line.split('|'): if is_first: is_first = False else: sql =",
"text[start:r.start(0)] res = res + '\\033[0;34m' + text[r.start(0):r.end(0)] + '\\033[0m' start = r.end(0)",
"f.close() print 'Done' ref_id = 0 # Now ready to trace trace_list =",
"-1 # continue has_result = False print '' caused_id = 0; first_id =",
"sys.exit(1) if ref_id in trace_list: print str(ref_id) + ' is in the trace",
"r.end(1) r = p.search(text, start) res = res + text[start:len(text)] + '\\n' text",
"res = res + text[start:len(text)] + '\\n' sys.stdout.write(res) # while r != None:",
"# continue has_result = False print '' caused_id = 0; first_id = 0;",
"color): # \"\"\"Write to stdout in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p =",
"NAME TEXT, ANNOS TEXT)') c.execute('create table ' + trace_table + '(ID INTEGER, NAME",
"start = r.end(1) # r = p.search(text, start) # writec(text[start:len(text)], 'normal') # writec('\\n',",
"+ text[start:r.start(0)] res = res + '\\033[0;34m' + text[r.start(0):r.end(0)] + '\\033[0m' start =",
"if auto_mode == True: # ref_id = -1 # continue has_result = False",
"refs_table + ' where ID = ' + str(rid)): print row[0], row[1] print",
"res = res + text[start:r.start(1)] res = res + '\\033[0;31m' + text[r.start(1):r.end(1)] +",
"\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): # \"\"\"Write to stdout in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def",
"'bright green': '1;32', # 'red': '0;31', 'bright cyan': '1;36', # 'purple': '0;35', 'bright",
"sqlite3.connect(\":memory:\") c = conn.cursor() # Create tables refs_table = 'refs' trace_table = 'trace'",
"refs_table = 'refs' trace_table = 'trace' c.execute('create table ' + refs_table + '(ID",
"= sys.argv[1]; all_trace_file = sys.argv[2]; else: all_refs_file = 'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log' #all_refs_file",
"for rid in trace_list: for row in c.execute('SELECT NAME, ANNOS from ' +",
"is:\\n' for rid in trace_list: for row in c.execute('SELECT NAME, ANNOS from '",
"in trace_list: for row in c.execute('SELECT NAME, ANNOS from ' + refs_table +",
"#conn = sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\") c = conn.cursor() # Create tables refs_table",
"TEXT)') c.execute('create table ' + trace_table + '(ID INTEGER, NAME TEXT, OLD_ANNOS TEXT,",
"caused_id = 0; first_id = 0; for row in c.execute('SELECT * from '",
"ID you want to trace (Press Enter to exit): \") try: ref_id =",
"#codeCodes = { # 'black': '0;30', 'bright gray': '0;37', # 'blue': '0;34', 'white':",
"blue': '1;34', # 'cyan': '0;36', 'bright green': '1;32', # 'red': '0;31', 'bright cyan':",
"res + '\\033[0;31m' + text[r.start(1):r.end(1)] + '\\033[0m' start = r.end(1) r = p.search(text,",
"in c.execute('SELECT NAME, ANNOS from ' + refs_table + ' where ID =",
"print 'Done' ref_id = 0 # Now ready to trace trace_list = []",
"= res + text[start:len(text)] + '\\n' sys.stdout.write(res) # while r != None: #",
"while r != None: res = res + text[start:r.start(0)] res = res +",
"conn = sqlite3.connect(\":memory:\") c = conn.cursor() # Create tables refs_table = 'refs' trace_table",
"writec('\\n', 'normal') if len(sys.argv) == 3: all_refs_file = sys.argv[1]; all_trace_file = sys.argv[2]; else:",
"ref_id == 0 or auto_mode == False: input_text = raw_input(\"Enter the ID you",
"ref_id in trace_list: trace_list.append(ref_id) else: print \"Not found\" if first_id == 0 or",
"True: print '' if ref_id == 0 or auto_mode == False: input_text =",
"str(rid)): print row[0], row[1] print ' | ' print ' V ' print",
"ref_id = 0 # Now ready to trace trace_list = [] while True:",
"except ValueError: ref_id = -1 if ref_id == -1: print 'The trace is:\\n'",
"'yellow': '0;33', 'bright purple':'1;35', # 'dark gray':'1;30', 'bright yellow':'1;33', # 'normal': '0' #}",
"print ' | ' print ' V ' print 'Done' sys.exit(1) if ref_id",
"found\" if first_id == 0 or first_id == caused_id: ref_id = caused_id else:",
"caused_id = row[6] # print '' if has_result and not ref_id in trace_list:",
"sys.argv[2]; else: all_refs_file = 'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log' #all_refs_file = 'all-refs.log' #all_trace_file =",
"+ text[start:len(text)] + '\\n' text = res p = re.compile('{[^{}]+}') start = 0",
"color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): # \"\"\"Write to stdout in color.\"\"\"",
"start = 0 r = p.search(text, start) res = '' while r !=",
"r = p.search(text, start) # writec(text[start:len(text)], 'normal') # writec('\\n', 'normal') if len(sys.argv) ==",
"sql + ')' try: c.execute(sql) except: print 'Skip invalid input: ' + line",
"by \" + row[5]) first_id = caused_id; caused_id = row[6] # print ''",
"= 0 # Now ready to trace trace_list = [] while True: print",
"exit): \") try: ref_id = int(input_text.strip()) except ValueError: ref_id = -1 if ref_id",
"in trace_list: trace_list.append(ref_id) else: print \"Not found\" if first_id == 0 or first_id",
"trace_list: for row in c.execute('SELECT NAME, ANNOS from ' + refs_table + '",
"# 'purple': '0;35', 'bright red': '1;31', # 'yellow': '0;33', 'bright purple':'1;35', # 'dark",
"line in f: sql = 'INSERT INTO ' + trace_table + ' VALUES",
"for row in c.execute('SELECT * from ' + trace_table + ' where ID",
"table ' + refs_table + '(ID INTEGER, NAME TEXT, ANNOS TEXT)') c.execute('create table",
"r.end(0) r = p.search(text, start) res = res + text[start:len(text)] + '\\n' sys.stdout.write(res)",
"row[5]) # print_highlight(\"caused by \" + row[5]) first_id = caused_id; caused_id = row[6]",
"#all_trace_file = 'trace.log' #conn = sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\") c = conn.cursor() #",
"if ref_id in trace_list: print str(ref_id) + ' is in the trace list.",
"auto_mode == True: # ref_id = -1 # continue has_result = False print",
"# print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): # \"\"\"Write to stdout in color.\"\"\" #",
"line # print sql # raise conn.commit() f.close() print 'Done' ref_id = 0",
"has_result = False print '' caused_id = 0; first_id = 0; for row",
"row[6] # print '' if has_result and not ref_id in trace_list: trace_list.append(ref_id) else:",
"trace_table + '(ID INTEGER, NAME TEXT, OLD_ANNOS TEXT, NEW_ANNOS TEXT, CONS TEXT, CAUSEDBY",
"'Skip invalid input: ' + line # print sql # raise conn.commit() f.close()",
"'0;31', 'bright cyan': '1;36', # 'purple': '0;35', 'bright red': '1;31', # 'yellow': '0;33',",
"'black': '0;30', 'bright gray': '0;37', # 'blue': '0;34', 'white': '1;37', # 'green': '0;32',",
"= True print_highlight(row[1] + ': ') print '\\t\\t\\t' + row[2] + ' -->",
"for row in c.execute('SELECT NAME, ANNOS from ' + refs_table + ' where",
"+ line # print sql # raise conn.commit() f.close() print 'Done' print 'Loading",
"# writec('\\n', 'normal') if len(sys.argv) == 3: all_refs_file = sys.argv[1]; all_trace_file = sys.argv[2];",
"\" + row[5]) # print_highlight(\"caused by \" + row[5]) first_id = caused_id; caused_id",
"= sql + ',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\")",
"first_id == 0 or first_id == caused_id: ref_id = caused_id else: ref_id =",
"None: res = res + text[start:r.start(0)] res = res + '\\033[0;34m' + text[r.start(0):r.end(0)]",
"from ' + trace_table + ' where ID = ' + str(ref_id)): has_result",
"# 'black': '0;30', 'bright gray': '0;37', # 'blue': '0;34', 'white': '1;37', # 'green':",
"# ref_id = -1 # continue has_result = False print '' caused_id =",
"\"\") + '\\'' sql = sql + ')' # print sql try: c.execute(sql)",
"'0;30', 'bright gray': '0;37', # 'blue': '0;34', 'white': '1;37', # 'green': '0;32', 'bright",
"print \"Not found\" if first_id == 0 or first_id == caused_id: ref_id =",
"'blue': '0;34', 'white': '1;37', # 'green': '0;32', 'bright blue': '1;34', # 'cyan': '0;36',",
"0; for row in c.execute('SELECT * from ' + trace_table + ' where",
"trace_list = [] while True: print '' if ref_id == 0 or auto_mode",
"'bright purple':'1;35', # 'dark gray':'1;30', 'bright yellow':'1;33', # 'normal': '0' #} #def printc(text,",
"start) res = res + text[start:len(text)] + '\\n' sys.stdout.write(res) # while r !=",
"'\\t\\t\\t' + row[2] + ' --> ' + row[3] print 'Due to:' print_highlight(row[4]",
"printc(text, color): # \"\"\"Print in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): #",
"+ ' VALUES (' is_first = True for s in line.split('|'): if is_first:",
"sql = sql + ')' # print sql try: c.execute(sql) except: print 'Skip",
"s in line.split('|'): if is_first: is_first = False else: sql = sql +",
"# writec(text[start:len(text)], 'normal') # writec('\\n', 'normal') if len(sys.argv) == 3: all_refs_file = sys.argv[1];",
"+ '\\'' + s.strip().replace(\"\\'\", \"\") + '\\'' sql = sql + ')' try:",
"# print_highlight(\"caused by \" + row[5]) first_id = caused_id; caused_id = row[6] #",
"p.search(text, start) res = '' while r != None: res = res +",
"p = re.compile('{[^{}]+}') start = 0 r = p.search(text, start) res = ''",
"conn.cursor() # Create tables refs_table = 'refs' trace_table = 'trace' c.execute('create table '",
"print 'Done' print 'Loading trace data from ' + all_trace_file + '...' f",
"res + text[start:r.start(1)] res = res + '\\033[0;31m' + text[r.start(1):r.end(1)] + '\\033[0m' start",
"ValueError: ref_id = -1 if ref_id == -1: print 'The trace is:\\n' for",
"start) # writec(text[start:len(text)], 'normal') # writec('\\n', 'normal') if len(sys.argv) == 3: all_refs_file =",
"= True #codeCodes = { # 'black': '0;30', 'bright gray': '0;37', # 'blue':",
"= raw_input(\"Enter the ID you want to trace (Press Enter to exit): \")",
"' print 'Done' sys.exit(1) if ref_id in trace_list: print str(ref_id) + ' is",
"' + trace_table + ' where ID = ' + str(ref_id)): has_result =",
"# 'red': '0;31', 'bright cyan': '1;36', # 'purple': '0;35', 'bright red': '1;31', #",
"stdout in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p = re.compile('\\(([0-9]+)\\)') start = 0",
"+ '\\033[0;34m' + text[r.start(0):r.end(0)] + '\\033[0m' start = r.end(0) r = p.search(text, start)",
"str(ref_id)): has_result = True print_highlight(row[1] + ': ') print '\\t\\t\\t' + row[2] +",
"= open(all_refs_file) for line in f: sql = 'INSERT INTO ' + refs_table",
"= open(all_trace_file) for line in f: sql = 'INSERT INTO ' + trace_table",
"' + all_refs_file + '...' f = open(all_refs_file) for line in f: sql",
"re.compile('{[^{}]+}') start = 0 r = p.search(text, start) res = '' while r",
"= p.search(text, start) # writec(text[start:len(text)], 'normal') # writec('\\n', 'normal') if len(sys.argv) == 3:",
"= res + text[start:r.start(0)] res = res + '\\033[0;34m' + text[r.start(0):r.end(0)] + '\\033[0m'",
"ref_id in trace_list: print str(ref_id) + ' is in the trace list. You",
"or auto_mode == False: input_text = raw_input(\"Enter the ID you want to trace",
"ref_id == -1: print 'The trace is:\\n' for rid in trace_list: for row",
"TEXT, NEW_ANNOS TEXT, CONS TEXT, CAUSEDBY TEXT, CAUSEDID INTEGER)') conn.commit() # Dump the",
"')' try: c.execute(sql) except: print 'Skip invalid input: ' + line # print",
"# while r != None: # writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)], 'red') # start",
"sql + '\\'' + s.strip().replace(\"\\'\", \"\") + '\\'' sql = sql + ')'",
"| ' print ' V ' print 'Done' sys.exit(1) if ref_id in trace_list:",
"print '' if has_result and not ref_id in trace_list: trace_list.append(ref_id) else: print \"Not",
"text[r.start(0):r.end(0)] + '\\033[0m' start = r.end(0) r = p.search(text, start) res = res",
"You may have entered it before.' # if auto_mode == True: # ref_id",
"+ ' where ID = ' + str(ref_id)): has_result = True print_highlight(row[1] +",
"writec(text[r.start(1):r.end(1)], 'red') # start = r.end(1) # r = p.search(text, start) # writec(text[start:len(text)],",
"# Create tables refs_table = 'refs' trace_table = 'trace' c.execute('create table ' +",
"INTO ' + refs_table + ' VALUES (' is_first = True for s",
"start = r.end(0) r = p.search(text, start) res = res + text[start:len(text)] +",
"= sql + ',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\") +",
"open(all_trace_file) for line in f: sql = 'INSERT INTO ' + trace_table +",
"print 'Skip invalid input: ' + line # print sql # raise conn.commit()",
"text[start:r.start(1)] res = res + '\\033[0;31m' + text[r.start(1):r.end(1)] + '\\033[0m' start = r.end(1)",
"+ '\\n' text = res p = re.compile('{[^{}]+}') start = 0 r =",
"+ ': ') print '\\t\\t\\t' + row[2] + ' --> ' + row[3]",
"raise conn.commit() f.close() print 'Done' ref_id = 0 # Now ready to trace",
"= sys.argv[2]; else: all_refs_file = 'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log' #all_refs_file = 'all-refs.log' #all_trace_file",
"in line.split('|'): if is_first: is_first = False else: sql = sql + ','",
"f.close() print 'Done' print 'Loading trace data from ' + all_trace_file + '...'",
"+ text[r.start(1):r.end(1)] + '\\033[0m' start = r.end(1) r = p.search(text, start) res =",
"CAUSEDBY TEXT, CAUSEDID INTEGER)') conn.commit() # Dump the data print 'Loading reference data",
"+ trace_table + '(ID INTEGER, NAME TEXT, OLD_ANNOS TEXT, NEW_ANNOS TEXT, CONS TEXT,",
"# print sql try: c.execute(sql) except: print 'Skip invalid input: ' + line",
"refs_table + ' VALUES (' is_first = True for s in line.split('|'): if",
"print_highlight(\"caused by \" + row[5]) first_id = caused_id; caused_id = row[6] # print",
"'0;34', 'white': '1;37', # 'green': '0;32', 'bright blue': '1;34', # 'cyan': '0;36', 'bright",
"conn.commit() f.close() print 'Done' ref_id = 0 # Now ready to trace trace_list",
"c.execute('create table ' + refs_table + '(ID INTEGER, NAME TEXT, ANNOS TEXT)') c.execute('create",
"first_id = caused_id; caused_id = row[6] # print '' if has_result and not",
"'0;33', 'bright purple':'1;35', # 'dark gray':'1;30', 'bright yellow':'1;33', # 'normal': '0' #} #def",
"# writec(text[r.start(1):r.end(1)], 'red') # start = r.end(1) # r = p.search(text, start) #",
"sql = 'INSERT INTO ' + trace_table + ' VALUES (' is_first =",
"s.strip().replace(\"\\'\", \"\") + '\\'' sql = sql + ')' try: c.execute(sql) except: print",
"= ' + str(rid)): print row[0], row[1] print ' | ' print '",
"= p.search(text, start) res = res + text[start:len(text)] + '\\n' text = res",
"for s in line.split('|'): if is_first: is_first = False else: sql = sql",
"all_trace_file = sys.argv[2]; else: all_refs_file = 'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log' #all_refs_file = 'all-refs.log'",
"'Done' ref_id = 0 # Now ready to trace trace_list = [] while",
"sys.argv[1]; all_trace_file = sys.argv[2]; else: all_refs_file = 'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log' #all_refs_file =",
"' + trace_table + ' VALUES (' is_first = True for s in",
"auto_mode == False: input_text = raw_input(\"Enter the ID you want to trace (Press",
"== True: # ref_id = -1 # continue has_result = False print ''",
"' where ID = ' + str(ref_id)): has_result = True print_highlight(row[1] + ':",
"# sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p = re.compile('\\(([0-9]+)\\)') start = 0 r = p.search(text,",
"auto_mode = True #codeCodes = { # 'black': '0;30', 'bright gray': '0;37', #",
"' V ' print 'Done' sys.exit(1) if ref_id in trace_list: print str(ref_id) +",
"the data print 'Loading reference data from ' + all_refs_file + '...' f",
"+ '\\033[0m' start = r.end(0) r = p.search(text, start) res = res +",
"'Loading trace data from ' + all_trace_file + '...' f = open(all_trace_file) for",
"writec(text, color): # \"\"\"Write to stdout in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p",
"print row[0], row[1] print ' | ' print ' V ' print 'Done'",
"TEXT, CAUSEDID INTEGER)') conn.commit() # Dump the data print 'Loading reference data from",
"+ refs_table + '(ID INTEGER, NAME TEXT, ANNOS TEXT)') c.execute('create table ' +",
"= sqlite3.connect(\":memory:\") c = conn.cursor() # Create tables refs_table = 'refs' trace_table =",
"print str(ref_id) + ' is in the trace list. You may have entered",
"'bright yellow':'1;33', # 'normal': '0' #} #def printc(text, color): # \"\"\"Print in color.\"\"\"",
"+ '...' f = open(all_refs_file) for line in f: sql = 'INSERT INTO",
"# 'blue': '0;34', 'white': '1;37', # 'green': '0;32', 'bright blue': '1;34', # 'cyan':",
"# r = p.search(text, start) # writec(text[start:len(text)], 'normal') # writec('\\n', 'normal') if len(sys.argv)",
"print '' caused_id = 0; first_id = 0; for row in c.execute('SELECT *",
"not ref_id in trace_list: trace_list.append(ref_id) else: print \"Not found\" if first_id == 0",
"res + text[start:r.start(0)] res = res + '\\033[0;34m' + text[r.start(0):r.end(0)] + '\\033[0m' start",
"sql + ',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") +",
"= sql + ')' # print sql try: c.execute(sql) except: print 'Skip invalid",
"'infer-output/trace.log' #all_refs_file = 'all-refs.log' #all_trace_file = 'trace.log' #conn = sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\")",
"p.search(text, start) res = res + text[start:len(text)] + '\\n' sys.stdout.write(res) # while r",
"is_first = True for s in line.split('|'): if is_first: is_first = False else:",
"ANNOS TEXT)') c.execute('create table ' + trace_table + '(ID INTEGER, NAME TEXT, OLD_ANNOS",
"= int(input_text.strip()) except ValueError: ref_id = -1 if ref_id == -1: print 'The",
"= res + '\\033[0;34m' + text[r.start(0):r.end(0)] + '\\033[0m' start = r.end(0) r =",
"= caused_id; caused_id = row[6] # print '' if has_result and not ref_id",
"True #codeCodes = { # 'black': '0;30', 'bright gray': '0;37', # 'blue': '0;34',",
"to trace (Press Enter to exit): \") try: ref_id = int(input_text.strip()) except ValueError:",
"import sqlite3 import sys import re auto_mode = True #codeCodes = { #",
"= conn.cursor() # Create tables refs_table = 'refs' trace_table = 'trace' c.execute('create table",
"+ ' is in the trace list. You may have entered it before.'",
"f = open(all_refs_file) for line in f: sql = 'INSERT INTO ' +",
"start) res = res + text[start:len(text)] + '\\n' text = res p =",
"* from ' + trace_table + ' where ID = ' + str(ref_id)):",
"trace_list: trace_list.append(ref_id) else: print \"Not found\" if first_id == 0 or first_id ==",
"{ # 'black': '0;30', 'bright gray': '0;37', # 'blue': '0;34', 'white': '1;37', #",
"res = res + text[start:r.start(0)] res = res + '\\033[0;34m' + text[r.start(0):r.end(0)] +",
"text = res p = re.compile('{[^{}]+}') start = 0 r = p.search(text, start)",
"',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") + '\\'' sql",
"in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): # \"\"\"Write to stdout in",
"',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\") + '\\'' sql =",
"gray': '0;37', # 'blue': '0;34', 'white': '1;37', # 'green': '0;32', 'bright blue': '1;34',",
"Now ready to trace trace_list = [] while True: print '' if ref_id",
"for line in f: sql = 'INSERT INTO ' + refs_table + '",
"res = res + '\\033[0;31m' + text[r.start(1):r.end(1)] + '\\033[0m' start = r.end(1) r",
"# print sql # raise conn.commit() f.close() print 'Done' ref_id = 0 #",
"'red': '0;31', 'bright cyan': '1;36', # 'purple': '0;35', 'bright red': '1;31', # 'yellow':",
"re auto_mode = True #codeCodes = { # 'black': '0;30', 'bright gray': '0;37',",
"+ s.strip().replace(\"\\'\", \"\") + '\\'' sql = sql + ')' try: c.execute(sql) except:",
"c.execute('create table ' + trace_table + '(ID INTEGER, NAME TEXT, OLD_ANNOS TEXT, NEW_ANNOS",
"+ '(ID INTEGER, NAME TEXT, ANNOS TEXT)') c.execute('create table ' + trace_table +",
"= -1 # continue has_result = False print '' caused_id = 0; first_id",
"first_id = 0; for row in c.execute('SELECT * from ' + trace_table +",
"print 'Due to:' print_highlight(row[4] + \"\\nCaused by: \" + row[5]) # print_highlight(\"caused by",
"3: all_refs_file = sys.argv[1]; all_trace_file = sys.argv[2]; else: all_refs_file = 'infer-output/all-refs.log' all_trace_file =",
"'bright gray': '0;37', # 'blue': '0;34', 'white': '1;37', # 'green': '0;32', 'bright blue':",
"!= None: res = res + text[start:r.start(0)] res = res + '\\033[0;34m' +",
"import re auto_mode = True #codeCodes = { # 'black': '0;30', 'bright gray':",
"sql # raise conn.commit() f.close() print 'Done' print 'Loading trace data from '",
"'' while r != None: res = res + text[start:r.start(1)] res = res",
"' --> ' + row[3] print 'Due to:' print_highlight(row[4] + \"\\nCaused by: \"",
"purple':'1;35', # 'dark gray':'1;30', 'bright yellow':'1;33', # 'normal': '0' #} #def printc(text, color):",
"+ str(ref_id)): has_result = True print_highlight(row[1] + ': ') print '\\t\\t\\t' + row[2]",
"'1;37', # 'green': '0;32', 'bright blue': '1;34', # 'cyan': '0;36', 'bright green': '1;32',",
"row[0], row[1] print ' | ' print ' V ' print 'Done' sys.exit(1)",
"res + text[start:len(text)] + '\\n' text = res p = re.compile('{[^{}]+}') start =",
"'\\033[0;34m' + text[r.start(0):r.end(0)] + '\\033[0m' start = r.end(0) r = p.search(text, start) res",
"# print '' if has_result and not ref_id in trace_list: trace_list.append(ref_id) else: print",
"green': '1;32', # 'red': '0;31', 'bright cyan': '1;36', # 'purple': '0;35', 'bright red':",
"res + text[start:len(text)] + '\\n' sys.stdout.write(res) # while r != None: # writec(text[start:r.start(1)],",
"#all_refs_file = 'all-refs.log' #all_trace_file = 'trace.log' #conn = sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\") c",
"+ ',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") + '\\''",
"-1 if ref_id == -1: print 'The trace is:\\n' for rid in trace_list:",
"else: sql = sql + ',' sql = sql + '\\'' + s.strip().replace(\"\\'\",",
"'0;37', # 'blue': '0;34', 'white': '1;37', # 'green': '0;32', 'bright blue': '1;34', #",
"p = re.compile('\\(([0-9]+)\\)') start = 0 r = p.search(text, start) res = ''",
"invalid input: ' + line # print sql # raise conn.commit() f.close() print",
"'0;32', 'bright blue': '1;34', # 'cyan': '0;36', 'bright green': '1;32', # 'red': '0;31',",
"= res + text[start:r.start(1)] res = res + '\\033[0;31m' + text[r.start(1):r.end(1)] + '\\033[0m'",
"raise conn.commit() f.close() print 'Done' print 'Loading trace data from ' + all_trace_file",
"TEXT, OLD_ANNOS TEXT, NEW_ANNOS TEXT, CONS TEXT, CAUSEDBY TEXT, CAUSEDID INTEGER)') conn.commit() #",
"in f: sql = 'INSERT INTO ' + refs_table + ' VALUES ('",
"trace list. You may have entered it before.' # if auto_mode == True:",
"may have entered it before.' # if auto_mode == True: # ref_id =",
"OLD_ANNOS TEXT, NEW_ANNOS TEXT, CONS TEXT, CAUSEDBY TEXT, CAUSEDID INTEGER)') conn.commit() # Dump",
"')' # print sql try: c.execute(sql) except: print 'Skip invalid input: ' +",
"#def printc(text, color): # \"\"\"Print in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color):",
"before.' # if auto_mode == True: # ref_id = -1 # continue has_result",
"'\\n' sys.stdout.write(res) # while r != None: # writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)], 'red')",
"all_trace_file + '...' f = open(all_trace_file) for line in f: sql = 'INSERT",
"to:' print_highlight(row[4] + \"\\nCaused by: \" + row[5]) # print_highlight(\"caused by \" +",
"= sql + '\\'' + s.strip().replace(\"\\'\", \"\") + '\\'' sql = sql +",
"sql + '\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") + '\\'' sql = sql +",
"import sys import re auto_mode = True #codeCodes = { # 'black': '0;30',",
"' + line # print sql # raise conn.commit() f.close() print 'Done' ref_id",
"VALUES (' is_first = True for s in line.split('|'): if is_first: is_first =",
"start) res = '' while r != None: res = res + text[start:r.start(1)]",
"'bright cyan': '1;36', # 'purple': '0;35', 'bright red': '1;31', # 'yellow': '0;33', 'bright",
"None: res = res + text[start:r.start(1)] res = res + '\\033[0;31m' + text[r.start(1):r.end(1)]",
"= 'all-refs.log' #all_trace_file = 'trace.log' #conn = sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\") c =",
"for line in f: sql = 'INSERT INTO ' + trace_table + '",
"data from ' + all_refs_file + '...' f = open(all_refs_file) for line in",
"0 r = p.search(text, start) res = '' while r != None: res",
"+ all_trace_file + '...' f = open(all_trace_file) for line in f: sql =",
"if has_result and not ref_id in trace_list: trace_list.append(ref_id) else: print \"Not found\" if",
"res + '\\033[0;34m' + text[r.start(0):r.end(0)] + '\\033[0m' start = r.end(0) r = p.search(text,",
"have entered it before.' # if auto_mode == True: # ref_id = -1",
"r != None: res = res + text[start:r.start(0)] res = res + '\\033[0;34m'",
"sql # raise conn.commit() f.close() print 'Done' ref_id = 0 # Now ready",
"trace is:\\n' for rid in trace_list: for row in c.execute('SELECT NAME, ANNOS from",
"= 'INSERT INTO ' + refs_table + ' VALUES (' is_first = True",
"CAUSEDID INTEGER)') conn.commit() # Dump the data print 'Loading reference data from '",
"# if auto_mode == True: # ref_id = -1 # continue has_result =",
"'trace' c.execute('create table ' + refs_table + '(ID INTEGER, NAME TEXT, ANNOS TEXT)')",
"red': '1;31', # 'yellow': '0;33', 'bright purple':'1;35', # 'dark gray':'1;30', 'bright yellow':'1;33', #",
"= sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\") c = conn.cursor() # Create tables refs_table =",
"'INSERT INTO ' + trace_table + ' VALUES (' is_first = True for",
"'0' #} #def printc(text, color): # \"\"\"Print in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def",
"= 0; first_id = 0; for row in c.execute('SELECT * from ' +",
"'\\'' sql = sql + ')' try: c.execute(sql) except: print 'Skip invalid input:",
"the trace list. You may have entered it before.' # if auto_mode ==",
"open(all_refs_file) for line in f: sql = 'INSERT INTO ' + refs_table +",
"(' is_first = True for s in line.split('|'): if is_first: is_first = False",
"'The trace is:\\n' for rid in trace_list: for row in c.execute('SELECT NAME, ANNOS",
"ANNOS from ' + refs_table + ' where ID = ' + str(rid)):",
"Dump the data print 'Loading reference data from ' + all_refs_file + '...'",
"= re.compile('\\(([0-9]+)\\)') start = 0 r = p.search(text, start) res = '' while",
"TEXT, ANNOS TEXT)') c.execute('create table ' + trace_table + '(ID INTEGER, NAME TEXT,",
"'(ID INTEGER, NAME TEXT, ANNOS TEXT)') c.execute('create table ' + trace_table + '(ID",
"= sql + '\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") + '\\'' sql = sql",
"+ ')' # print sql try: c.execute(sql) except: print 'Skip invalid input: '",
"'\\033[0;31m' + text[r.start(1):r.end(1)] + '\\033[0m' start = r.end(1) r = p.search(text, start) res",
"in f: sql = 'INSERT INTO ' + trace_table + ' VALUES ('",
"= -1 if ref_id == -1: print 'The trace is:\\n' for rid in",
"'\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") + '\\'' sql = sql + ')' #",
"entered it before.' # if auto_mode == True: # ref_id = -1 #",
"# 'cyan': '0;36', 'bright green': '1;32', # 'red': '0;31', 'bright cyan': '1;36', #",
"while r != None: res = res + text[start:r.start(1)] res = res +",
"Enter to exit): \") try: ref_id = int(input_text.strip()) except ValueError: ref_id = -1",
"conn.commit() # Dump the data print 'Loading reference data from ' + all_refs_file",
"= 'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log' #all_refs_file = 'all-refs.log' #all_trace_file = 'trace.log' #conn =",
"+ '(ID INTEGER, NAME TEXT, OLD_ANNOS TEXT, NEW_ANNOS TEXT, CONS TEXT, CAUSEDBY TEXT,",
"conn.commit() f.close() print 'Done' print 'Loading trace data from ' + all_trace_file +",
"row in c.execute('SELECT * from ' + trace_table + ' where ID =",
"'\\033[0m' start = r.end(0) r = p.search(text, start) res = res + text[start:len(text)]",
"INTEGER, NAME TEXT, OLD_ANNOS TEXT, NEW_ANNOS TEXT, CONS TEXT, CAUSEDBY TEXT, CAUSEDID INTEGER)')",
"'Due to:' print_highlight(row[4] + \"\\nCaused by: \" + row[5]) # print_highlight(\"caused by \"",
"sql = sql + ')' try: c.execute(sql) except: print 'Skip invalid input: '",
"in the trace list. You may have entered it before.' # if auto_mode",
"' is in the trace list. You may have entered it before.' #",
"= 0; for row in c.execute('SELECT * from ' + trace_table + '",
"by: \" + row[5]) # print_highlight(\"caused by \" + row[5]) first_id = caused_id;",
"False else: sql = sql + ',' sql = sql + '\\'' +",
"= res + '\\033[0;31m' + text[r.start(1):r.end(1)] + '\\033[0m' start = r.end(1) r =",
"# \"\"\"Write to stdout in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p = re.compile('\\(([0-9]+)\\)')",
"+ '\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") + '\\'' sql = sql + ')'",
"p.search(text, start) # writec(text[start:len(text)], 'normal') # writec('\\n', 'normal') if len(sys.argv) == 3: all_refs_file",
"# print sql # raise conn.commit() f.close() print 'Done' print 'Loading trace data",
"line in f: sql = 'INSERT INTO ' + refs_table + ' VALUES",
"INTEGER, NAME TEXT, ANNOS TEXT)') c.execute('create table ' + trace_table + '(ID INTEGER,",
"' + row[3] print 'Due to:' print_highlight(row[4] + \"\\nCaused by: \" + row[5])",
"' + trace_table + '(ID INTEGER, NAME TEXT, OLD_ANNOS TEXT, NEW_ANNOS TEXT, CONS",
"' + refs_table + ' VALUES (' is_first = True for s in",
"'normal') # writec(text[r.start(1):r.end(1)], 'red') # start = r.end(1) # r = p.search(text, start)",
"len(sys.argv) == 3: all_refs_file = sys.argv[1]; all_trace_file = sys.argv[2]; else: all_refs_file = 'infer-output/all-refs.log'",
"None: # writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)], 'red') # start = r.end(1) # r",
"'white': '1;37', # 'green': '0;32', 'bright blue': '1;34', # 'cyan': '0;36', 'bright green':",
"+ '\\033[0m' start = r.end(1) r = p.search(text, start) res = res +",
"'all-refs.log' #all_trace_file = 'trace.log' #conn = sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\") c = conn.cursor()",
"def print_highlight(text): p = re.compile('\\(([0-9]+)\\)') start = 0 r = p.search(text, start) res",
"= row[6] # print '' if has_result and not ref_id in trace_list: trace_list.append(ref_id)",
"= 'INSERT INTO ' + trace_table + ' VALUES (' is_first = True",
"# Now ready to trace trace_list = [] while True: print '' if",
"'Done' print 'Loading trace data from ' + all_trace_file + '...' f =",
"'normal': '0' #} #def printc(text, color): # \"\"\"Print in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\"",
"+ all_refs_file + '...' f = open(all_refs_file) for line in f: sql =",
"'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log' #all_refs_file = 'all-refs.log' #all_trace_file = 'trace.log' #conn = sqlite3.connect(\"trace.db\")",
"res = '' while r != None: res = res + text[start:r.start(1)] res",
"' + refs_table + '(ID INTEGER, NAME TEXT, ANNOS TEXT)') c.execute('create table '",
"INTEGER)') conn.commit() # Dump the data print 'Loading reference data from ' +",
"from ' + refs_table + ' where ID = ' + str(rid)): print",
"False print '' caused_id = 0; first_id = 0; for row in c.execute('SELECT",
"'0;35', 'bright red': '1;31', # 'yellow': '0;33', 'bright purple':'1;35', # 'dark gray':'1;30', 'bright",
"= p.search(text, start) res = '' while r != None: res = res",
"' | ' print ' V ' print 'Done' sys.exit(1) if ref_id in",
"'refs' trace_table = 'trace' c.execute('create table ' + refs_table + '(ID INTEGER, NAME",
"python import sqlite3 import sys import re auto_mode = True #codeCodes = {",
"+ s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") + '\\'' sql = sql + ')' # print",
"= '' while r != None: res = res + text[start:r.start(1)] res =",
"'bright red': '1;31', # 'yellow': '0;33', 'bright purple':'1;35', # 'dark gray':'1;30', 'bright yellow':'1;33',",
"to exit): \") try: ref_id = int(input_text.strip()) except ValueError: ref_id = -1 if",
"is_first = False else: sql = sql + ',' sql = sql +",
"table ' + trace_table + '(ID INTEGER, NAME TEXT, OLD_ANNOS TEXT, NEW_ANNOS TEXT,",
"reference data from ' + all_refs_file + '...' f = open(all_refs_file) for line",
"sqlite3 import sys import re auto_mode = True #codeCodes = { # 'black':",
"' VALUES (' is_first = True for s in line.split('|'): if is_first: is_first",
"\") try: ref_id = int(input_text.strip()) except ValueError: ref_id = -1 if ref_id ==",
"where ID = ' + str(rid)): print row[0], row[1] print ' | '",
"'normal') # writec('\\n', 'normal') if len(sys.argv) == 3: all_refs_file = sys.argv[1]; all_trace_file =",
"c = conn.cursor() # Create tables refs_table = 'refs' trace_table = 'trace' c.execute('create",
"= 0 r = p.search(text, start) res = '' while r != None:",
"all_refs_file = 'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log' #all_refs_file = 'all-refs.log' #all_trace_file = 'trace.log' #conn",
"all_refs_file = sys.argv[1]; all_trace_file = sys.argv[2]; else: all_refs_file = 'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log'",
"'Loading reference data from ' + all_refs_file + '...' f = open(all_refs_file) for",
"= re.compile('{[^{}]+}') start = 0 r = p.search(text, start) res = '' while",
"try: c.execute(sql) except: print 'Skip invalid input: ' + line # print sql",
"caused_id; caused_id = row[6] # print '' if has_result and not ref_id in",
"'dark gray':'1;30', 'bright yellow':'1;33', # 'normal': '0' #} #def printc(text, color): # \"\"\"Print",
"+ '\\033[0;31m' + text[r.start(1):r.end(1)] + '\\033[0m' start = r.end(1) r = p.search(text, start)",
"ID = ' + str(rid)): print row[0], row[1] print ' | ' print",
"= r.end(0) r = p.search(text, start) res = res + text[start:len(text)] + '\\n'",
"# Dump the data print 'Loading reference data from ' + all_refs_file +",
"' + all_trace_file + '...' f = open(all_trace_file) for line in f: sql",
"c.execute(sql) except: print 'Skip invalid input: ' + line # print sql #",
"c.execute('SELECT * from ' + trace_table + ' where ID = ' +",
"sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\") c = conn.cursor() # Create tables refs_table = 'refs'",
"+ ' where ID = ' + str(rid)): print row[0], row[1] print '",
"data from ' + all_trace_file + '...' f = open(all_trace_file) for line in",
"print 'Loading reference data from ' + all_refs_file + '...' f = open(all_refs_file)",
"0 # Now ready to trace trace_list = [] while True: print ''",
"except: print 'Skip invalid input: ' + line # print sql # raise",
"'\\'' + s.strip().replace(\"\\'\", \"\") + '\\'' sql = sql + ')' try: c.execute(sql)",
"== 3: all_refs_file = sys.argv[1]; all_trace_file = sys.argv[2]; else: all_refs_file = 'infer-output/all-refs.log' all_trace_file",
"+ '...' f = open(all_trace_file) for line in f: sql = 'INSERT INTO",
"-1: print 'The trace is:\\n' for rid in trace_list: for row in c.execute('SELECT",
"re.compile('\\(([0-9]+)\\)') start = 0 r = p.search(text, start) res = '' while r",
"\"\").replace(\"\\n\", \"\") + '\\'' sql = sql + ')' # print sql try:",
"want to trace (Press Enter to exit): \") try: ref_id = int(input_text.strip()) except",
"' print ' V ' print 'Done' sys.exit(1) if ref_id in trace_list: print",
"if is_first: is_first = False else: sql = sql + ',' sql =",
"sql = 'INSERT INTO ' + refs_table + ' VALUES (' is_first =",
"sql = sql + ',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\",",
"yellow':'1;33', # 'normal': '0' #} #def printc(text, color): # \"\"\"Print in color.\"\"\" #",
"int(input_text.strip()) except ValueError: ref_id = -1 if ref_id == -1: print 'The trace",
"= r.end(1) # r = p.search(text, start) # writec(text[start:len(text)], 'normal') # writec('\\n', 'normal')",
"ref_id = -1 # continue has_result = False print '' caused_id = 0;",
"+ row[5]) first_id = caused_id; caused_id = row[6] # print '' if has_result",
"== 0 or first_id == caused_id: ref_id = caused_id else: ref_id = 0",
"#def writec(text, color): # \"\"\"Write to stdout in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text):",
"+ text[start:len(text)] + '\\n' sys.stdout.write(res) # while r != None: # writec(text[start:r.start(1)], 'normal')",
"print sql # raise conn.commit() f.close() print 'Done' ref_id = 0 # Now",
"line.split('|'): if is_first: is_first = False else: sql = sql + ',' sql",
"is_first: is_first = False else: sql = sql + ',' sql = sql",
"has_result and not ref_id in trace_list: trace_list.append(ref_id) else: print \"Not found\" if first_id",
"= False print '' caused_id = 0; first_id = 0; for row in",
"+ \"\\nCaused by: \" + row[5]) # print_highlight(\"caused by \" + row[5]) first_id",
"print '' if ref_id == 0 or auto_mode == False: input_text = raw_input(\"Enter",
"ready to trace trace_list = [] while True: print '' if ref_id ==",
"V ' print 'Done' sys.exit(1) if ref_id in trace_list: print str(ref_id) + '",
"'normal') if len(sys.argv) == 3: all_refs_file = sys.argv[1]; all_trace_file = sys.argv[2]; else: all_refs_file",
"+ '\\'' sql = sql + ')' try: c.execute(sql) except: print 'Skip invalid",
"print_highlight(text): p = re.compile('\\(([0-9]+)\\)') start = 0 r = p.search(text, start) res =",
"res = res + text[start:len(text)] + '\\n' text = res p = re.compile('{[^{}]+}')",
"'1;32', # 'red': '0;31', 'bright cyan': '1;36', # 'purple': '0;35', 'bright red': '1;31',",
"= '' while r != None: res = res + text[start:r.start(0)] res =",
"'bright blue': '1;34', # 'cyan': '0;36', 'bright green': '1;32', # 'red': '0;31', 'bright",
"sys import re auto_mode = True #codeCodes = { # 'black': '0;30', 'bright",
"# \"\"\"Print in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): # \"\"\"Write to",
"+ ' --> ' + row[3] print 'Due to:' print_highlight(row[4] + \"\\nCaused by:",
"sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\") + '\\'' sql = sql",
"' + str(ref_id)): has_result = True print_highlight(row[1] + ': ') print '\\t\\t\\t' +",
"trace_list.append(ref_id) else: print \"Not found\" if first_id == 0 or first_id == caused_id:",
"row[1] print ' | ' print ' V ' print 'Done' sys.exit(1) if",
"'green': '0;32', 'bright blue': '1;34', # 'cyan': '0;36', 'bright green': '1;32', # 'red':",
"while True: print '' if ref_id == 0 or auto_mode == False: input_text",
"refs_table + '(ID INTEGER, NAME TEXT, ANNOS TEXT)') c.execute('create table ' + trace_table",
"text[start:len(text)] + '\\n' sys.stdout.write(res) # while r != None: # writec(text[start:r.start(1)], 'normal') #",
"' + refs_table + ' where ID = ' + str(rid)): print row[0],",
"ref_id = -1 if ref_id == -1: print 'The trace is:\\n' for rid",
"trace_table + ' VALUES (' is_first = True for s in line.split('|'): if",
"+ row[2] + ' --> ' + row[3] print 'Due to:' print_highlight(row[4] +",
"print '\\t\\t\\t' + row[2] + ' --> ' + row[3] print 'Due to:'",
"'purple': '0;35', 'bright red': '1;31', # 'yellow': '0;33', 'bright purple':'1;35', # 'dark gray':'1;30',",
"+ str(rid)): print row[0], row[1] print ' | ' print ' V '",
"gray':'1;30', 'bright yellow':'1;33', # 'normal': '0' #} #def printc(text, color): # \"\"\"Print in",
"all_refs_file + '...' f = open(all_refs_file) for line in f: sql = 'INSERT",
"trace data from ' + all_trace_file + '...' f = open(all_trace_file) for line",
"r.end(1) # r = p.search(text, start) # writec(text[start:len(text)], 'normal') # writec('\\n', 'normal') if",
"res = res + '\\033[0;34m' + text[r.start(0):r.end(0)] + '\\033[0m' start = r.end(0) r",
"else: print \"Not found\" if first_id == 0 or first_id == caused_id: ref_id",
"color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p = re.compile('\\(([0-9]+)\\)') start = 0 r =",
"row in c.execute('SELECT NAME, ANNOS from ' + refs_table + ' where ID",
"is in the trace list. You may have entered it before.' # if",
"text[r.start(1):r.end(1)] + '\\033[0m' start = r.end(1) r = p.search(text, start) res = res",
"'trace.log' #conn = sqlite3.connect(\"trace.db\") conn = sqlite3.connect(\":memory:\") c = conn.cursor() # Create tables",
"ID = ' + str(ref_id)): has_result = True print_highlight(row[1] + ': ') print",
"' + str(rid)): print row[0], row[1] print ' | ' print ' V",
"'' while r != None: res = res + text[start:r.start(0)] res = res",
"TEXT, CAUSEDBY TEXT, CAUSEDID INTEGER)') conn.commit() # Dump the data print 'Loading reference",
"if first_id == 0 or first_id == caused_id: ref_id = caused_id else: ref_id",
"= r.end(1) r = p.search(text, start) res = res + text[start:len(text)] + '\\n'",
"else: all_refs_file = 'infer-output/all-refs.log' all_trace_file = 'infer-output/trace.log' #all_refs_file = 'all-refs.log' #all_trace_file = 'trace.log'",
"True print_highlight(row[1] + ': ') print '\\t\\t\\t' + row[2] + ' --> '",
"trace_list: print str(ref_id) + ' is in the trace list. You may have",
"= False else: sql = sql + ',' sql = sql + '\\''",
"= True for s in line.split('|'): if is_first: is_first = False else: sql",
"start) res = '' while r != None: res = res + text[start:r.start(0)]",
"= p.search(text, start) res = res + text[start:len(text)] + '\\n' sys.stdout.write(res) # while",
"= 'trace' c.execute('create table ' + refs_table + '(ID INTEGER, NAME TEXT, ANNOS",
"trace trace_list = [] while True: print '' if ref_id == 0 or",
"'\\033[0m' start = r.end(1) r = p.search(text, start) res = res + text[start:len(text)]",
"r = p.search(text, start) res = res + text[start:len(text)] + '\\n' text =",
"while r != None: # writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)], 'red') # start =",
"s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") + '\\'' sql = sql + ')' # print sql",
"(Press Enter to exit): \") try: ref_id = int(input_text.strip()) except ValueError: ref_id =",
"str(ref_id) + ' is in the trace list. You may have entered it",
"you want to trace (Press Enter to exit): \") try: ref_id = int(input_text.strip())",
"# 'normal': '0' #} #def printc(text, color): # \"\"\"Print in color.\"\"\" # print",
"--> ' + row[3] print 'Due to:' print_highlight(row[4] + \"\\nCaused by: \" +",
"print 'The trace is:\\n' for rid in trace_list: for row in c.execute('SELECT NAME,",
"rid in trace_list: for row in c.execute('SELECT NAME, ANNOS from ' + refs_table",
"writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)], 'red') # start = r.end(1) # r = p.search(text,",
"NAME TEXT, OLD_ANNOS TEXT, NEW_ANNOS TEXT, CONS TEXT, CAUSEDBY TEXT, CAUSEDID INTEGER)') conn.commit()",
"+ ')' try: c.execute(sql) except: print 'Skip invalid input: ' + line #",
"print_highlight(row[4] + \"\\nCaused by: \" + row[5]) # print_highlight(\"caused by \" + row[5])",
"trace_table + ' where ID = ' + str(ref_id)): has_result = True print_highlight(row[1]",
"in trace_list: print str(ref_id) + ' is in the trace list. You may",
"it before.' # if auto_mode == True: # ref_id = -1 # continue",
"'' if ref_id == 0 or auto_mode == False: input_text = raw_input(\"Enter the",
"# writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)], 'red') # start = r.end(1) # r =",
"r != None: res = res + text[start:r.start(1)] res = res + '\\033[0;31m'",
"+ row[5]) # print_highlight(\"caused by \" + row[5]) first_id = caused_id; caused_id =",
"all_trace_file = 'infer-output/trace.log' #all_refs_file = 'all-refs.log' #all_trace_file = 'trace.log' #conn = sqlite3.connect(\"trace.db\") conn",
"'1;36', # 'purple': '0;35', 'bright red': '1;31', # 'yellow': '0;33', 'bright purple':'1;35', #",
"'1;31', # 'yellow': '0;33', 'bright purple':'1;35', # 'dark gray':'1;30', 'bright yellow':'1;33', # 'normal':",
"'' if has_result and not ref_id in trace_list: trace_list.append(ref_id) else: print \"Not found\"",
"sql try: c.execute(sql) except: print 'Skip invalid input: ' + line # print",
"res = '' while r != None: res = res + text[start:r.start(0)] res",
"\"\"\"Write to stdout in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p = re.compile('\\(([0-9]+)\\)') start",
"trace (Press Enter to exit): \") try: ref_id = int(input_text.strip()) except ValueError: ref_id",
"+ trace_table + ' where ID = ' + str(ref_id)): has_result = True",
"text[start:len(text)] + '\\n' text = res p = re.compile('{[^{}]+}') start = 0 r",
"r = p.search(text, start) res = res + text[start:len(text)] + '\\n' sys.stdout.write(res) #",
"in c.execute('SELECT * from ' + trace_table + ' where ID = '",
"+ '\\'' sql = sql + ')' # print sql try: c.execute(sql) except:",
"+ row[3] print 'Due to:' print_highlight(row[4] + \"\\nCaused by: \" + row[5]) #",
"r = p.search(text, start) res = '' while r != None: res =",
"CONS TEXT, CAUSEDBY TEXT, CAUSEDID INTEGER)') conn.commit() # Dump the data print 'Loading",
"print 'Loading trace data from ' + all_trace_file + '...' f = open(all_trace_file)",
"= 'infer-output/trace.log' #all_refs_file = 'all-refs.log' #all_trace_file = 'trace.log' #conn = sqlite3.connect(\"trace.db\") conn =",
"== -1: print 'The trace is:\\n' for rid in trace_list: for row in",
"tables refs_table = 'refs' trace_table = 'trace' c.execute('create table ' + refs_table +",
"if ref_id == -1: print 'The trace is:\\n' for rid in trace_list: for",
"' where ID = ' + str(rid)): print row[0], row[1] print ' |",
"writec(text[start:len(text)], 'normal') # writec('\\n', 'normal') if len(sys.argv) == 3: all_refs_file = sys.argv[1]; all_trace_file",
"'Done' sys.exit(1) if ref_id in trace_list: print str(ref_id) + ' is in the",
"#} #def printc(text, color): # \"\"\"Print in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text,",
"to trace trace_list = [] while True: print '' if ref_id == 0",
"# raise conn.commit() f.close() print 'Done' ref_id = 0 # Now ready to",
"print ' V ' print 'Done' sys.exit(1) if ref_id in trace_list: print str(ref_id)",
"== False: input_text = raw_input(\"Enter the ID you want to trace (Press Enter",
"' + line # print sql # raise conn.commit() f.close() print 'Done' print",
"has_result = True print_highlight(row[1] + ': ') print '\\t\\t\\t' + row[2] + '",
"print sql # raise conn.commit() f.close() print 'Done' print 'Loading trace data from",
"from ' + all_trace_file + '...' f = open(all_trace_file) for line in f:",
"= res p = re.compile('{[^{}]+}') start = 0 r = p.search(text, start) res",
"print 'Done' sys.exit(1) if ref_id in trace_list: print str(ref_id) + ' is in",
"\"Not found\" if first_id == 0 or first_id == caused_id: ref_id = caused_id",
"= sql + ')' try: c.execute(sql) except: print 'Skip invalid input: ' +",
"Create tables refs_table = 'refs' trace_table = 'trace' c.execute('create table ' + refs_table",
"\"\") + '\\'' sql = sql + ')' try: c.execute(sql) except: print 'Skip",
"input: ' + line # print sql # raise conn.commit() f.close() print 'Done'",
"ref_id = int(input_text.strip()) except ValueError: ref_id = -1 if ref_id == -1: print",
"and not ref_id in trace_list: trace_list.append(ref_id) else: print \"Not found\" if first_id ==",
"'INSERT INTO ' + refs_table + ' VALUES (' is_first = True for",
"'' caused_id = 0; first_id = 0; for row in c.execute('SELECT * from",
"sql + ',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\") + '\\''",
"INTO ' + trace_table + ' VALUES (' is_first = True for s",
"[] while True: print '' if ref_id == 0 or auto_mode == False:",
"# raise conn.commit() f.close() print 'Done' print 'Loading trace data from ' +",
"# start = r.end(1) # r = p.search(text, start) # writec(text[start:len(text)], 'normal') #",
"': ') print '\\t\\t\\t' + row[2] + ' --> ' + row[3] print",
"# 'yellow': '0;33', 'bright purple':'1;35', # 'dark gray':'1;30', 'bright yellow':'1;33', # 'normal': '0'",
"f: sql = 'INSERT INTO ' + refs_table + ' VALUES (' is_first",
"') print '\\t\\t\\t' + row[2] + ' --> ' + row[3] print 'Due",
"'0;36', 'bright green': '1;32', # 'red': '0;31', 'bright cyan': '1;36', # 'purple': '0;35',",
"sys.stdout.write(res) # while r != None: # writec(text[start:r.start(1)], 'normal') # writec(text[r.start(1):r.end(1)], 'red') #",
"input_text = raw_input(\"Enter the ID you want to trace (Press Enter to exit):",
"# 'dark gray':'1;30', 'bright yellow':'1;33', # 'normal': '0' #} #def printc(text, color): #",
"= [] while True: print '' if ref_id == 0 or auto_mode ==",
"row[5]) first_id = caused_id; caused_id = row[6] # print '' if has_result and",
"'\\'' sql = sql + ')' # print sql try: c.execute(sql) except: print",
"color): # \"\"\"Print in color.\"\"\" # print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): # \"\"\"Write",
"sql + ')' # print sql try: c.execute(sql) except: print 'Skip invalid input:",
"print \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\" #def writec(text, color): # \"\"\"Write to stdout in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\")",
"print sql try: c.execute(sql) except: print 'Skip invalid input: ' + line #",
"line # print sql # raise conn.commit() f.close() print 'Done' print 'Loading trace",
"NEW_ANNOS TEXT, CONS TEXT, CAUSEDBY TEXT, CAUSEDID INTEGER)') conn.commit() # Dump the data",
"'\\n' text = res p = re.compile('{[^{}]+}') start = 0 r = p.search(text,",
"sql = sql + ',' sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\")",
"# 'green': '0;32', 'bright blue': '1;34', # 'cyan': '0;36', 'bright green': '1;32', #",
"f = open(all_trace_file) for line in f: sql = 'INSERT INTO ' +",
"row[3] print 'Due to:' print_highlight(row[4] + \"\\nCaused by: \" + row[5]) # print_highlight(\"caused",
"= res + text[start:len(text)] + '\\n' text = res p = re.compile('{[^{}]+}') start",
"f: sql = 'INSERT INTO ' + trace_table + ' VALUES (' is_first",
"from ' + all_refs_file + '...' f = open(all_refs_file) for line in f:",
"sql = sql + '\\'' + s.strip().replace(\"\\'\", \"\").replace(\"\\n\", \"\") + '\\'' sql =",
"to stdout in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p = re.compile('\\(([0-9]+)\\)') start =",
"0 or auto_mode == False: input_text = raw_input(\"Enter the ID you want to",
"trace_table = 'trace' c.execute('create table ' + refs_table + '(ID INTEGER, NAME TEXT,",
"raw_input(\"Enter the ID you want to trace (Press Enter to exit): \") try:",
"res p = re.compile('{[^{}]+}') start = 0 r = p.search(text, start) res =",
"try: ref_id = int(input_text.strip()) except ValueError: ref_id = -1 if ref_id == -1:",
"= { # 'black': '0;30', 'bright gray': '0;37', # 'blue': '0;34', 'white': '1;37',",
"'red') # start = r.end(1) # r = p.search(text, start) # writec(text[start:len(text)], 'normal')",
"in color.\"\"\" # sys.stdout.write(\"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\") def print_highlight(text): p = re.compile('\\(([0-9]+)\\)') start = 0 r",
"+ refs_table + ' VALUES (' is_first = True for s in line.split('|'):",
"where ID = ' + str(ref_id)): has_result = True print_highlight(row[1] + ': ')",
"c.execute('SELECT NAME, ANNOS from ' + refs_table + ' where ID = '",
"= 'refs' trace_table = 'trace' c.execute('create table ' + refs_table + '(ID INTEGER,",
"+ line # print sql # raise conn.commit() f.close() print 'Done' ref_id =",
"cyan': '1;36', # 'purple': '0;35', 'bright red': '1;31', # 'yellow': '0;33', 'bright purple':'1;35',",
"list. You may have entered it before.' # if auto_mode == True: #"
] |
[
"< 0: return 'Invalid input. Must be a value greater than 0' if",
"* factorial(input - 1) # smart factorial that doesn't perform the full operation",
"else: result = n ** k print(f'Result: {result}') if __name__ == '__main__': main()",
"'(C)': result = combination(n, k) elif operation == '(P)': result = permutation(n, k)",
"the following options:') for key in options: print(f'>> {key}') operation_choice = input('Please choose",
"the full operation and saves time def fact_with_div(n, mid, k): result = 1",
"result *= n n -= 1 return result # method that performs the",
"only accept integer inputs' if input < 0: return 'Invalid input. Must be",
"!= k: result *= n n -= 1 return result # method that",
"'Ordered with Replacement':'(OR)', 'OR':'(OR)'} # reading input for operation type until correct operation_choice",
"input < 0: return 'Invalid input. Must be a value greater than 0'",
"range 0 \\u2264 k \\u2264 n.' + f'\\nYour values are k = {k}",
"# options for operations and matching code options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with",
"= int(input('Number of spaces to fit to (k): ')) while k > n",
"performs the combination formula def combination(n, k): numerator = fact_with_div(n, n - k,",
"calculates factorials def factorial(input): if type(input) != int: return 'Can only accept integer",
"performs the permutation formula def permutation(n, k): numerator = fact_with_div(n, n - k,",
"values until correct n = int(input('Number of elements to pick from (n): '))",
"integer inputs' if input < 0: return 'Invalid input. Must be a value",
"0' if input == 0 or input == 1: return 1 return input",
"- 1) # smart factorial that doesn't perform the full operation and saves",
"perform the full operation and saves time def fact_with_div(n, mid, k): result =",
"*= n n -= 1 return result # method that performs the combination",
"= options[operation_choice] # reading n and k values until correct n = int(input('Number",
"one of the following options:') for key in options: print(f'>> {key}') operation_choice =",
"result # method that performs the combination formula def combination(n, k): numerator =",
"# operation choosing if operation == '(C)': result = combination(n, k) elif operation",
"def fact_with_div(n, mid, k): result = 1 if mid > k: while n",
"formula def permutation(n, k): numerator = fact_with_div(n, n - k, 0) return numerator",
"formula def combination(n, k): numerator = fact_with_div(n, n - k, k) denominator =",
"'(P)': result = permutation(n, k) else: result = n ** k print(f'Result: {result}')",
"following options:') for key in options: print(f'>> {key}') operation_choice = input('Please choose an",
"- k, k) denominator = factorial(k) if k < n - k else",
"elements to pick from (n): ')) k = int(input('Number of spaces to fit",
"elif operation == '(P)': result = permutation(n, k) else: result = n **",
"# smart factorial that doesn't perform the full operation and saves time def",
"= fact_with_div(n, n - k, 0) return numerator def main(): # options for",
"k): numerator = fact_with_div(n, n - k, 0) return numerator def main(): #",
"# method that calculates factorials def factorial(input): if type(input) != int: return 'Can",
"and matching code options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)', 'OR':'(OR)'} # reading",
"1: return 1 return input * factorial(input - 1) # smart factorial that",
"permutation(n, k): numerator = fact_with_div(n, n - k, 0) return numerator def main():",
"mid: result *= n n -= 1 else: while n != k: result",
"0 or input == 1: return 1 return input * factorial(input - 1)",
"operation == '(C)': result = combination(n, k) elif operation == '(P)': result =",
"!= int: return 'Can only accept integer inputs' if input < 0: return",
"def factorial(input): if type(input) != int: return 'Can only accept integer inputs' if",
"option. Please select one of the following options:') for key in options: print(f'>>",
"of elements to pick from: ')) k = int(input('Number of spaces to fit",
"= int(input('Number of elements to pick from: ')) k = int(input('Number of spaces",
"doesn't perform the full operation and saves time def fact_with_div(n, mid, k): result",
"result = permutation(n, k) else: result = n ** k print(f'Result: {result}') if",
"accept integer inputs' if input < 0: return 'Invalid input. Must be a",
"n n -= 1 return result # method that performs the combination formula",
"\\u2264 n.' + f'\\nYour values are k = {k} and n = {n}')",
"the permutation formula def permutation(n, k): numerator = fact_with_div(n, n - k, 0)",
"if mid > k: while n != mid: result *= n n -=",
"are k = {k} and n = {n}') n = int(input('Number of elements",
"n and k values until correct n = int(input('Number of elements to pick",
"method that performs the permutation formula def permutation(n, k): numerator = fact_with_div(n, n",
"k = {k} and n = {n}') n = int(input('Number of elements to",
"# method that performs the combination formula def combination(n, k): numerator = fact_with_div(n,",
"= factorial(k) if k < n - k else factorial(n - k) return",
"int(numerator / denominator) # method that performs the permutation formula def permutation(n, k):",
"= combination(n, k) elif operation == '(P)': result = permutation(n, k) else: result",
"that doesn't perform the full operation and saves time def fact_with_div(n, mid, k):",
"- k) return int(numerator / denominator) # method that performs the permutation formula",
"result = combination(n, k) elif operation == '(P)': result = permutation(n, k) else:",
"k values until correct n = int(input('Number of elements to pick from (n):",
"fit to (k): ')) while k > n or k < 0 or",
"\\u2264 k \\u2264 n.' + f'\\nYour values are k = {k} and n",
"of the following options:') for key in options: print(f'>> {key}') operation_choice = input('Please",
"choosing if operation == '(C)': result = combination(n, k) elif operation == '(P)':",
"1 return result # method that performs the combination formula def combination(n, k):",
"factorials def factorial(input): if type(input) != int: return 'Can only accept integer inputs'",
"combination(n, k) elif operation == '(P)': result = permutation(n, k) else: result =",
"in options: print(f'>> {key}') operation_choice = input('Please choose an operation: ') operation =",
"n -= 1 return result # method that performs the combination formula def",
"= fact_with_div(n, n - k, k) denominator = factorial(k) if k < n",
"pick from (n): ')) k = int(input('Number of spaces to fit to (k):",
"> n or k < 0 or n < 0: print('Both values have",
"if type(input) != int: return 'Can only accept integer inputs' if input <",
"from (n): ')) k = int(input('Number of spaces to fit to (k): '))",
"correct operation_choice = input('Please choose an operation: ') while operation_choice not in options:",
"return result # method that performs the combination formula def combination(n, k): numerator",
"= int(input('Number of elements to pick from (n): ')) k = int(input('Number of",
"n < 0: print('Both values have to be in the range 0 \\u2264",
"int(input('Number of elements to pick from: ')) k = int(input('Number of spaces to",
"k) denominator = factorial(k) if k < n - k else factorial(n -",
"while n != k: result *= n n -= 1 return result #",
"saves time def fact_with_div(n, mid, k): result = 1 if mid > k:",
"k else factorial(n - k) return int(numerator / denominator) # method that performs",
"0 \\u2264 k \\u2264 n.' + f'\\nYour values are k = {k} and",
"that performs the permutation formula def permutation(n, k): numerator = fact_with_div(n, n -",
"import sys # method that calculates factorials def factorial(input): if type(input) != int:",
"pick from: ')) k = int(input('Number of spaces to fit to: ')) #",
"k: while n != mid: result *= n n -= 1 else: while",
"values have to be in the range 0 \\u2264 k \\u2264 n.' +",
"1 if mid > k: while n != mid: result *= n n",
"return 'Can only accept integer inputs' if input < 0: return 'Invalid input.",
"operation == '(P)': result = permutation(n, k) else: result = n ** k",
"k < n - k else factorial(n - k) return int(numerator / denominator)",
"k > n or k < 0 or n < 0: print('Both values",
"-= 1 return result # method that performs the combination formula def combination(n,",
"< n - k else factorial(n - k) return int(numerator / denominator) #",
"factorial(n - k) return int(numerator / denominator) # method that performs the permutation",
"< 0 or n < 0: print('Both values have to be in the",
"<reponame>RikGhosh487/Combinations-Permutations<filename>perm_comb.py<gh_stars>0 import sys # method that calculates factorials def factorial(input): if type(input) !=",
"k = int(input('Number of spaces to fit to (k): ')) while k >",
"{'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)', 'OR':'(OR)'} # reading input for operation type until",
"== '(C)': result = combination(n, k) elif operation == '(P)': result = permutation(n,",
"0: print('Both values have to be in the range 0 \\u2264 k \\u2264",
"method that performs the combination formula def combination(n, k): numerator = fact_with_div(n, n",
"correct n = int(input('Number of elements to pick from (n): ')) k =",
"')) # operation choosing if operation == '(C)': result = combination(n, k) elif",
"of elements to pick from (n): ')) k = int(input('Number of spaces to",
"and k values until correct n = int(input('Number of elements to pick from",
"invalid option. Please select one of the following options:') for key in options:",
"'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)', 'OR':'(OR)'} # reading input for operation type until correct",
"def permutation(n, k): numerator = fact_with_div(n, n - k, 0) return numerator def",
"choose an operation: ') operation = options[operation_choice] # reading n and k values",
"< 0: print('Both values have to be in the range 0 \\u2264 k",
"result *= n n -= 1 else: while n != k: result *=",
"that performs the combination formula def combination(n, k): numerator = fact_with_div(n, n -",
"options:') for key in options: print(f'>> {key}') operation_choice = input('Please choose an operation:",
"= input('Please choose an operation: ') while operation_choice not in options: print('That is",
"operation_choice not in options: print('That is an invalid option. Please select one of",
"+ f'\\nYour values are k = {k} and n = {n}') n =",
"spaces to fit to: ')) # operation choosing if operation == '(C)': result",
"time def fact_with_div(n, mid, k): result = 1 if mid > k: while",
"while n != mid: result *= n n -= 1 else: while n",
"result = 1 if mid > k: while n != mid: result *=",
"') while operation_choice not in options: print('That is an invalid option. Please select",
"to (k): ')) while k > n or k < 0 or n",
"print('Both values have to be in the range 0 \\u2264 k \\u2264 n.'",
"mid > k: while n != mid: result *= n n -= 1",
"Must be a value greater than 0' if input == 0 or input",
"smart factorial that doesn't perform the full operation and saves time def fact_with_div(n,",
"operation choosing if operation == '(C)': result = combination(n, k) elif operation ==",
"combination formula def combination(n, k): numerator = fact_with_div(n, n - k, k) denominator",
"# reading input for operation type until correct operation_choice = input('Please choose an",
"until correct operation_choice = input('Please choose an operation: ') while operation_choice not in",
"fit to: ')) # operation choosing if operation == '(C)': result = combination(n,",
"key in options: print(f'>> {key}') operation_choice = input('Please choose an operation: ') operation",
"k < 0 or n < 0: print('Both values have to be in",
"- k else factorial(n - k) return int(numerator / denominator) # method that",
"def main(): # options for operations and matching code options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)',",
"options[operation_choice] # reading n and k values until correct n = int(input('Number of",
"print('That is an invalid option. Please select one of the following options:') for",
"= permutation(n, k) else: result = n ** k print(f'Result: {result}') if __name__",
"') operation = options[operation_choice] # reading n and k values until correct n",
"have to be in the range 0 \\u2264 k \\u2264 n.' + f'\\nYour",
"*= n n -= 1 else: while n != k: result *= n",
"k, 0) return numerator def main(): # options for operations and matching code",
"input for operation type until correct operation_choice = input('Please choose an operation: ')",
"be a value greater than 0' if input == 0 or input ==",
"numerator def main(): # options for operations and matching code options = {'Combinations':'(C)','C':'(C)',",
"n != mid: result *= n n -= 1 else: while n !=",
"operation_choice = input('Please choose an operation: ') while operation_choice not in options: print('That",
"')) while k > n or k < 0 or n < 0:",
"operation and saves time def fact_with_div(n, mid, k): result = 1 if mid",
"to pick from: ')) k = int(input('Number of spaces to fit to: '))",
"n n -= 1 else: while n != k: result *= n n",
"while k > n or k < 0 or n < 0: print('Both",
"denominator) # method that performs the permutation formula def permutation(n, k): numerator =",
"inputs' if input < 0: return 'Invalid input. Must be a value greater",
"main(): # options for operations and matching code options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered",
"method that calculates factorials def factorial(input): if type(input) != int: return 'Can only",
"sys # method that calculates factorials def factorial(input): if type(input) != int: return",
"permutation formula def permutation(n, k): numerator = fact_with_div(n, n - k, 0) return",
"or n < 0: print('Both values have to be in the range 0",
"code options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)', 'OR':'(OR)'} # reading input for",
"elements to pick from: ')) k = int(input('Number of spaces to fit to:",
"full operation and saves time def fact_with_div(n, mid, k): result = 1 if",
"options: print(f'>> {key}') operation_choice = input('Please choose an operation: ') operation = options[operation_choice]",
"value greater than 0' if input == 0 or input == 1: return",
"options for operations and matching code options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)',",
"1 return input * factorial(input - 1) # smart factorial that doesn't perform",
"n or k < 0 or n < 0: print('Both values have to",
"to fit to (k): ')) while k > n or k < 0",
"> k: while n != mid: result *= n n -= 1 else:",
"return input * factorial(input - 1) # smart factorial that doesn't perform the",
"or k < 0 or n < 0: print('Both values have to be",
"# method that performs the permutation formula def permutation(n, k): numerator = fact_with_div(n,",
"int(input('Number of spaces to fit to: ')) # operation choosing if operation ==",
"for operations and matching code options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)', 'OR':'(OR)'}",
"n - k, 0) return numerator def main(): # options for operations and",
"to be in the range 0 \\u2264 k \\u2264 n.' + f'\\nYour values",
"options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)', 'OR':'(OR)'} # reading input for operation",
"reading n and k values until correct n = int(input('Number of elements to",
"to fit to: ')) # operation choosing if operation == '(C)': result =",
"if input == 0 or input == 1: return 1 return input *",
"reading input for operation type until correct operation_choice = input('Please choose an operation:",
"!= mid: result *= n n -= 1 else: while n != k:",
"= 1 if mid > k: while n != mid: result *= n",
"mid, k): result = 1 if mid > k: while n != mid:",
"= {k} and n = {n}') n = int(input('Number of elements to pick",
"the range 0 \\u2264 k \\u2264 n.' + f'\\nYour values are k =",
"an operation: ') operation = options[operation_choice] # reading n and k values until",
"n - k, k) denominator = factorial(k) if k < n - k",
"- k, 0) return numerator def main(): # options for operations and matching",
"input('Please choose an operation: ') while operation_choice not in options: print('That is an",
"== 1: return 1 return input * factorial(input - 1) # smart factorial",
"and saves time def fact_with_div(n, mid, k): result = 1 if mid >",
"input * factorial(input - 1) # smart factorial that doesn't perform the full",
"Please select one of the following options:') for key in options: print(f'>> {key}')",
"spaces to fit to (k): ')) while k > n or k <",
"operation = options[operation_choice] # reading n and k values until correct n =",
"{key}') operation_choice = input('Please choose an operation: ') operation = options[operation_choice] # reading",
"k \\u2264 n.' + f'\\nYour values are k = {k} and n =",
"not in options: print('That is an invalid option. Please select one of the",
"k = int(input('Number of spaces to fit to: ')) # operation choosing if",
"k) return int(numerator / denominator) # method that performs the permutation formula def",
"with Replacement':'(OR)', 'OR':'(OR)'} # reading input for operation type until correct operation_choice =",
"else: while n != k: result *= n n -= 1 return result",
"operation_choice = input('Please choose an operation: ') operation = options[operation_choice] # reading n",
"int(input('Number of spaces to fit to (k): ')) while k > n or",
"'Invalid input. Must be a value greater than 0' if input == 0",
"else factorial(n - k) return int(numerator / denominator) # method that performs the",
"'Can only accept integer inputs' if input < 0: return 'Invalid input. Must",
"0: return 'Invalid input. Must be a value greater than 0' if input",
"n != k: result *= n n -= 1 return result # method",
"for operation type until correct operation_choice = input('Please choose an operation: ') while",
"values are k = {k} and n = {n}') n = int(input('Number of",
"input == 1: return 1 return input * factorial(input - 1) # smart",
"operation: ') while operation_choice not in options: print('That is an invalid option. Please",
"choose an operation: ') while operation_choice not in options: print('That is an invalid",
"in options: print('That is an invalid option. Please select one of the following",
"type(input) != int: return 'Can only accept integer inputs' if input < 0:",
"operations and matching code options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)', 'OR':'(OR)'} #",
"= {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)', 'OR':'(OR)'} # reading input for operation type",
"0 or n < 0: print('Both values have to be in the range",
"1) # smart factorial that doesn't perform the full operation and saves time",
"n = int(input('Number of elements to pick from (n): ')) k = int(input('Number",
"k): result = 1 if mid > k: while n != mid: result",
"return int(numerator / denominator) # method that performs the permutation formula def permutation(n,",
"is an invalid option. Please select one of the following options:') for key",
"print(f'>> {key}') operation_choice = input('Please choose an operation: ') operation = options[operation_choice] #",
"of spaces to fit to: ')) # operation choosing if operation == '(C)':",
"k) else: result = n ** k print(f'Result: {result}') if __name__ == '__main__':",
"n - k else factorial(n - k) return int(numerator / denominator) # method",
"n.' + f'\\nYour values are k = {k} and n = {n}') n",
"than 0' if input == 0 or input == 1: return 1 return",
"')) k = int(input('Number of spaces to fit to: ')) # operation choosing",
"{n}') n = int(input('Number of elements to pick from: ')) k = int(input('Number",
"a value greater than 0' if input == 0 or input == 1:",
"of spaces to fit to (k): ')) while k > n or k",
"the combination formula def combination(n, k): numerator = fact_with_div(n, n - k, k)",
"= int(input('Number of spaces to fit to: ')) # operation choosing if operation",
"return 'Invalid input. Must be a value greater than 0' if input ==",
"if input < 0: return 'Invalid input. Must be a value greater than",
"in the range 0 \\u2264 k \\u2264 n.' + f'\\nYour values are k",
"f'\\nYour values are k = {k} and n = {n}') n = int(input('Number",
"until correct n = int(input('Number of elements to pick from (n): ')) k",
"{k} and n = {n}') n = int(input('Number of elements to pick from:",
"matching code options = {'Combinations':'(C)','C':'(C)', 'Permutations':'(P)','P':'(P)', 'Ordered with Replacement':'(OR)', 'OR':'(OR)'} # reading input",
"numerator = fact_with_div(n, n - k, 0) return numerator def main(): # options",
"== 0 or input == 1: return 1 return input * factorial(input -",
"options: print('That is an invalid option. Please select one of the following options:')",
"be in the range 0 \\u2264 k \\u2264 n.' + f'\\nYour values are",
"n -= 1 else: while n != k: result *= n n -=",
"combination(n, k): numerator = fact_with_div(n, n - k, k) denominator = factorial(k) if",
"fact_with_div(n, mid, k): result = 1 if mid > k: while n !=",
"numerator = fact_with_div(n, n - k, k) denominator = factorial(k) if k <",
"type until correct operation_choice = input('Please choose an operation: ') while operation_choice not",
"input. Must be a value greater than 0' if input == 0 or",
"# reading n and k values until correct n = int(input('Number of elements",
"to pick from (n): ')) k = int(input('Number of spaces to fit to",
"to: ')) # operation choosing if operation == '(C)': result = combination(n, k)",
"== '(P)': result = permutation(n, k) else: result = n ** k print(f'Result:",
"from: ')) k = int(input('Number of spaces to fit to: ')) # operation",
"n = {n}') n = int(input('Number of elements to pick from: ')) k",
"(k): ')) while k > n or k < 0 or n <",
"fact_with_div(n, n - k, 0) return numerator def main(): # options for operations",
"k: result *= n n -= 1 return result # method that performs",
"'OR':'(OR)'} # reading input for operation type until correct operation_choice = input('Please choose",
"return numerator def main(): # options for operations and matching code options =",
"for key in options: print(f'>> {key}') operation_choice = input('Please choose an operation: ')",
"/ denominator) # method that performs the permutation formula def permutation(n, k): numerator",
"select one of the following options:') for key in options: print(f'>> {key}') operation_choice",
"-= 1 else: while n != k: result *= n n -= 1",
"if operation == '(C)': result = combination(n, k) elif operation == '(P)': result",
"denominator = factorial(k) if k < n - k else factorial(n - k)",
"fact_with_div(n, n - k, k) denominator = factorial(k) if k < n -",
"or input == 1: return 1 return input * factorial(input - 1) #",
"(n): ')) k = int(input('Number of spaces to fit to (k): ')) while",
"int: return 'Can only accept integer inputs' if input < 0: return 'Invalid",
"an invalid option. Please select one of the following options:') for key in",
"factorial(k) if k < n - k else factorial(n - k) return int(numerator",
"1 else: while n != k: result *= n n -= 1 return",
"factorial that doesn't perform the full operation and saves time def fact_with_div(n, mid,",
"return 1 return input * factorial(input - 1) # smart factorial that doesn't",
"operation: ') operation = options[operation_choice] # reading n and k values until correct",
"and n = {n}') n = int(input('Number of elements to pick from: '))",
"= {n}') n = int(input('Number of elements to pick from: ')) k =",
"an operation: ') while operation_choice not in options: print('That is an invalid option.",
"def combination(n, k): numerator = fact_with_div(n, n - k, k) denominator = factorial(k)",
"= input('Please choose an operation: ') operation = options[operation_choice] # reading n and",
"factorial(input - 1) # smart factorial that doesn't perform the full operation and",
"if k < n - k else factorial(n - k) return int(numerator /",
"factorial(input): if type(input) != int: return 'Can only accept integer inputs' if input",
"n = int(input('Number of elements to pick from: ')) k = int(input('Number of",
"k) elif operation == '(P)': result = permutation(n, k) else: result = n",
"k, k) denominator = factorial(k) if k < n - k else factorial(n",
"permutation(n, k) else: result = n ** k print(f'Result: {result}') if __name__ ==",
"int(input('Number of elements to pick from (n): ')) k = int(input('Number of spaces",
"input('Please choose an operation: ') operation = options[operation_choice] # reading n and k",
"')) k = int(input('Number of spaces to fit to (k): ')) while k",
"that calculates factorials def factorial(input): if type(input) != int: return 'Can only accept",
"k): numerator = fact_with_div(n, n - k, k) denominator = factorial(k) if k",
"input == 0 or input == 1: return 1 return input * factorial(input",
"greater than 0' if input == 0 or input == 1: return 1",
"Replacement':'(OR)', 'OR':'(OR)'} # reading input for operation type until correct operation_choice = input('Please",
"while operation_choice not in options: print('That is an invalid option. Please select one",
"operation type until correct operation_choice = input('Please choose an operation: ') while operation_choice",
"0) return numerator def main(): # options for operations and matching code options"
] |
[
"from .models import Branch,Product,Transfer,Vendor,Model # Register your models here. admin.site.register(Branch) admin.site.register(Product) admin.site.register(Transfer) admin.site.register(Vendor)",
"<reponame>rishthas/ProdTracker from django.contrib import admin from .models import Branch,Product,Transfer,Vendor,Model # Register your models",
"admin from .models import Branch,Product,Transfer,Vendor,Model # Register your models here. admin.site.register(Branch) admin.site.register(Product) admin.site.register(Transfer)",
"import admin from .models import Branch,Product,Transfer,Vendor,Model # Register your models here. admin.site.register(Branch) admin.site.register(Product)",
".models import Branch,Product,Transfer,Vendor,Model # Register your models here. admin.site.register(Branch) admin.site.register(Product) admin.site.register(Transfer) admin.site.register(Vendor) admin.site.register(Model)",
"django.contrib import admin from .models import Branch,Product,Transfer,Vendor,Model # Register your models here. admin.site.register(Branch)",
"from django.contrib import admin from .models import Branch,Product,Transfer,Vendor,Model # Register your models here."
] |
[
"models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel(",
"('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_ciudad', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.ciudades')),",
"models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ], ), migrations.CreateModel( name='Ciudades',",
"migrations.CreateModel( name='Paises', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura',",
"20:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True",
"initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Paises', fields=[",
"Generated by Django 3.1.1 on 2020-10-30 20:55 from django.db import migrations, models import",
"('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ], ), migrations.CreateModel( name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True,",
"Django 3.1.1 on 2020-10-30 20:55 from django.db import migrations, models import django.db.models.deletion class",
"migrations.CreateModel( name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil',",
"models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel( name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)),",
"to='afiliados.paises')), ], ), migrations.CreateModel( name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)),",
"models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')),",
"operations = [ migrations.CreateModel( name='Paises', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)),",
"('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_ciudad', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.ciudades')), ], ),",
"models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_ciudad', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date",
"models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel( name='Afiliados', fields=[ ('id',",
"('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True,",
"Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Paises',",
"creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ], ), migrations.CreateModel( name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"= [ migrations.CreateModel( name='Paises', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre',",
"('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ], ), migrations.CreateModel( name='Ciudades', fields=[",
"), migrations.CreateModel( name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)),",
"('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ], ), migrations.CreateModel( name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"2020-10-30 20:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion',",
"('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ], ), migrations.CreateModel(",
"('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_ciudad',",
"on 2020-10-30 20:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial",
"('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ],",
"update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel( name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True,",
"models.DateTimeField(verbose_name='Date update')), ], ), migrations.CreateModel( name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo',",
"models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_ciudad', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.ciudades')), ], ), ]",
"name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)),",
"('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel( name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()),",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies",
"dependencies = [ ] operations = [ migrations.CreateModel( name='Paises', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado',",
"null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel( name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ], ), migrations.CreateModel( name='Ciudades', fields=[ ('id',",
"models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True,",
"name='Paises', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)),",
"('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')),",
"('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais',",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email',",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [",
"import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations =",
"models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')),",
"= [ ] operations = [ migrations.CreateModel( name='Paises', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel( name='Afiliados', fields=[",
"3.1.1 on 2020-10-30 20:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"], ), migrations.CreateModel( name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos',",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =",
"class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel(",
"by Django 3.1.1 on 2020-10-30 20:55 from django.db import migrations, models import django.db.models.deletion",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado',",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)),",
"models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion',",
"verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)),",
"django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [",
"verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion',",
"models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ], ),",
"] operations = [ migrations.CreateModel( name='Paises', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo',",
"serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')),",
"on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel( name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombres',",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion',",
"# Generated by Django 3.1.1 on 2020-10-30 20:55 from django.db import migrations, models",
"<reponame>FabianBedoya/Frameworks-7a-2020B # Generated by Django 3.1.1 on 2020-10-30 20:55 from django.db import migrations,",
"models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ], ), migrations.CreateModel( name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ),",
"migrations.CreateModel( name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura',",
"models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_ciudad', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.ciudades')), ],",
"= True dependencies = [ ] operations = [ migrations.CreateModel( name='Paises', fields=[ ('id',",
"models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion',",
"('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)), ('abreviatura', models.CharField(max_length=5)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date",
"True dependencies = [ ] operations = [ migrations.CreateModel( name='Paises', fields=[ ('id', models.AutoField(auto_created=True,",
"models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations",
"], ), migrations.CreateModel( name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre',",
"[ migrations.CreateModel( name='Paises', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)), ('nombre', models.CharField(max_length=20)),",
"models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ],",
"('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date",
"[ ] operations = [ migrations.CreateModel( name='Paises', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_ciudad', models.ForeignKey(blank=True, null=True,",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ]",
"('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')),",
"creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_pais', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='afiliados.paises')), ], ), migrations.CreateModel( name='Afiliados',",
"), migrations.CreateModel( name='Afiliados', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)),",
"models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date",
"primary_key=True, serialize=False, verbose_name='ID')), ('nombres', models.CharField(max_length=25)), ('apellidos', models.CharField(max_length=25)), ('numero_movil', models.BigIntegerField()), ('direccion', models.CharField(max_length=100)), ('email', models.CharField(max_length=70)),",
"update')), ], ), migrations.CreateModel( name='Ciudades', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.CharField(max_length=20)),",
"models.CharField(max_length=100)), ('email', models.CharField(max_length=70)), ('estado', models.BooleanField(default=True)), ('fecha_creacion', models.DateTimeField(verbose_name='Date creatio')), ('fecha_modificacion', models.DateTimeField(verbose_name='Date update')), ('id_ciudad', models.ForeignKey(blank=True,"
] |
[
"import Flask from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment import",
"Flask from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment import Moment",
"config from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import LoginManager, UserMixin, login_user, logout_user, login_required",
"from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .csudadmin import csudadmin as csudadmin_blueprint",
"from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment import Moment from",
"models['User'] @lm.user_loader def load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) #",
"flask.ext.login import LoginManager, UserMixin, login_user, logout_user, login_required bootstrap = Bootstrap() mail = Mail()",
"= APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension() lm = LoginManager() lm.login_view = 'main.login' def create_app(config_name,",
"pas ... # api_manager.create_api(models['User'], methods=['GET', 'DELETE']) # api_manager.init_app(app) # initialisation de la barre",
"APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension() lm = LoginManager() lm.login_view = 'main.login' def create_app(config_name, models={}):",
"lm = LoginManager() lm.login_view = 'main.login' def create_app(config_name, models={}): app = Flask(__name__) lm.init_app(app)",
"mail.init_app(app) moment.init_app(app) db.init_app(app) # initialisation de l'api REST ==> ne fonctionne pas ...",
"initialisation de la barre de déboguage # toolbar.init_app(app) # Blueprint main from .main",
"import LoginManager, UserMixin, login_user, logout_user, login_required bootstrap = Bootstrap() mail = Mail() moment",
"api_manager.create_api(models['User'], methods=['GET', 'DELETE']) # api_manager.init_app(app) # initialisation de la barre de déboguage #",
"config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) # initialisation de l'api REST ==> ne fonctionne",
"as main_blueprint app.register_blueprint(main_blueprint) from .csudadmin import csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from .sendmail",
"Flask(__name__) lm.init_app(app) User = models['User'] @lm.user_loader def load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app)",
"déboguage # toolbar.init_app(app) # Blueprint main from .main import main as main_blueprint app.register_blueprint(main_blueprint)",
"def create_app(config_name, models={}): app = Flask(__name__) lm.init_app(app) User = models['User'] @lm.user_loader def load_user(id):",
"moment.init_app(app) db.init_app(app) # initialisation de l'api REST ==> ne fonctionne pas ... #",
"la barre de déboguage # toolbar.init_app(app) # Blueprint main from .main import main",
"l'api REST ==> ne fonctionne pas ... # api_manager.create_api(models['User'], methods=['GET', 'DELETE']) # api_manager.init_app(app)",
"# initialisation de l'api REST ==> ne fonctionne pas ... # api_manager.create_api(models['User'], methods=['GET',",
"Blueprint main from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .csudadmin import csudadmin",
"@lm.user_loader def load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) # initialisation",
"= models['User'] @lm.user_loader def load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app)",
"User = models['User'] @lm.user_loader def load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app)",
"'DELETE']) # api_manager.init_app(app) # initialisation de la barre de déboguage # toolbar.init_app(app) #",
"# Blueprint main from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .csudadmin import",
"app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) # initialisation de l'api REST ==> ne",
"bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) # initialisation de l'api REST ==> ne fonctionne pas",
"= DebugToolbarExtension() lm = LoginManager() lm.login_view = 'main.login' def create_app(config_name, models={}): app =",
"config import config from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import LoginManager, UserMixin, login_user,",
"SQLAlchemy() # api_manager = APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension() lm = LoginManager() lm.login_view =",
"==> ne fonctionne pas ... # api_manager.create_api(models['User'], methods=['GET', 'DELETE']) # api_manager.init_app(app) # initialisation",
"flask_mail import Mail from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from config",
"flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import LoginManager, UserMixin, login_user, logout_user, login_required bootstrap =",
"logout_user, login_required bootstrap = Bootstrap() mail = Mail() moment = Moment() db =",
"DebugToolbarExtension() lm = LoginManager() lm.login_view = 'main.login' def create_app(config_name, models={}): app = Flask(__name__)",
"lm.init_app(app) User = models['User'] @lm.user_loader def load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app)",
"'main.login' def create_app(config_name, models={}): app = Flask(__name__) lm.init_app(app) User = models['User'] @lm.user_loader def",
"import Moment from flask_sqlalchemy import SQLAlchemy from config import config from flask_debugtoolbar import",
"= Moment() db = SQLAlchemy() # api_manager = APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension() lm",
"def load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) # initialisation de",
"db = SQLAlchemy() # api_manager = APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension() lm = LoginManager()",
"Mail() moment = Moment() db = SQLAlchemy() # api_manager = APIManager(flask_sqlalchemy_db=db) toolbar =",
"db.init_app(app) # initialisation de l'api REST ==> ne fonctionne pas ... # api_manager.create_api(models['User'],",
"flask_sqlalchemy import SQLAlchemy from config import config from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login",
"Moment from flask_sqlalchemy import SQLAlchemy from config import config from flask_debugtoolbar import DebugToolbarExtension",
"login_required bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy()",
"DebugToolbarExtension from flask.ext.login import LoginManager, UserMixin, login_user, logout_user, login_required bootstrap = Bootstrap() mail",
"from flask.ext.login import LoginManager, UserMixin, login_user, logout_user, login_required bootstrap = Bootstrap() mail =",
"UserMixin, login_user, logout_user, login_required bootstrap = Bootstrap() mail = Mail() moment = Moment()",
".csudadmin import csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from .sendmail import sendmail as sendmail_blueprint",
"initialisation de l'api REST ==> ne fonctionne pas ... # api_manager.create_api(models['User'], methods=['GET', 'DELETE'])",
"de la barre de déboguage # toolbar.init_app(app) # Blueprint main from .main import",
"# api_manager = APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension() lm = LoginManager() lm.login_view = 'main.login'",
"flask import Flask from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment",
"Mail from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from config import config",
"import DebugToolbarExtension from flask.ext.login import LoginManager, UserMixin, login_user, logout_user, login_required bootstrap = Bootstrap()",
"flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from config import config from flask_debugtoolbar",
"csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from .sendmail import sendmail as sendmail_blueprint app.register_blueprint(sendmail_blueprint, url_prefix='/sendmail') return app",
"lm.login_view = 'main.login' def create_app(config_name, models={}): app = Flask(__name__) lm.init_app(app) User = models['User']",
"toolbar.init_app(app) # Blueprint main from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .csudadmin",
"... # api_manager.create_api(models['User'], methods=['GET', 'DELETE']) # api_manager.init_app(app) # initialisation de la barre de",
"bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() #",
"from flask_sqlalchemy import SQLAlchemy from config import config from flask_debugtoolbar import DebugToolbarExtension from",
".main import main as main_blueprint app.register_blueprint(main_blueprint) from .csudadmin import csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint,",
"app = Flask(__name__) lm.init_app(app) User = models['User'] @lm.user_loader def load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name])",
"mail = Mail() moment = Moment() db = SQLAlchemy() # api_manager = APIManager(flask_sqlalchemy_db=db)",
"app.register_blueprint(main_blueprint) from .csudadmin import csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from .sendmail import sendmail",
"load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) # initialisation de l'api",
"import Bootstrap from flask_mail import Mail from flask_moment import Moment from flask_sqlalchemy import",
"LoginManager, UserMixin, login_user, logout_user, login_required bootstrap = Bootstrap() mail = Mail() moment =",
"main_blueprint app.register_blueprint(main_blueprint) from .csudadmin import csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from .sendmail import",
"= 'main.login' def create_app(config_name, models={}): app = Flask(__name__) lm.init_app(app) User = models['User'] @lm.user_loader",
"= LoginManager() lm.login_view = 'main.login' def create_app(config_name, models={}): app = Flask(__name__) lm.init_app(app) User",
"# api_manager.init_app(app) # initialisation de la barre de déboguage # toolbar.init_app(app) # Blueprint",
"import Mail from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from config import",
"from config import config from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import LoginManager, UserMixin,",
"import csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from .sendmail import sendmail as sendmail_blueprint app.register_blueprint(sendmail_blueprint,",
"REST ==> ne fonctionne pas ... # api_manager.create_api(models['User'], methods=['GET', 'DELETE']) # api_manager.init_app(app) #",
"User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) # initialisation de l'api REST ==>",
"<reponame>csud-reservation/flask-backend from flask import Flask from flask_bootstrap import Bootstrap from flask_mail import Mail",
"import config from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import LoginManager, UserMixin, login_user, logout_user,",
"methods=['GET', 'DELETE']) # api_manager.init_app(app) # initialisation de la barre de déboguage # toolbar.init_app(app)",
"# api_manager.create_api(models['User'], methods=['GET', 'DELETE']) # api_manager.init_app(app) # initialisation de la barre de déboguage",
"= Mail() moment = Moment() db = SQLAlchemy() # api_manager = APIManager(flask_sqlalchemy_db=db) toolbar",
"models={}): app = Flask(__name__) lm.init_app(app) User = models['User'] @lm.user_loader def load_user(id): return User.query.get(int(id))",
"from .csudadmin import csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from .sendmail import sendmail as",
"Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() # api_manager =",
"# toolbar.init_app(app) # Blueprint main from .main import main as main_blueprint app.register_blueprint(main_blueprint) from",
"SQLAlchemy from config import config from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import LoginManager,",
"main from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .csudadmin import csudadmin as",
"return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) # initialisation de l'api REST",
"LoginManager() lm.login_view = 'main.login' def create_app(config_name, models={}): app = Flask(__name__) lm.init_app(app) User =",
"= Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() # api_manager",
"import SQLAlchemy from config import config from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import",
"# initialisation de la barre de déboguage # toolbar.init_app(app) # Blueprint main from",
"from flask import Flask from flask_bootstrap import Bootstrap from flask_mail import Mail from",
"login_user, logout_user, login_required bootstrap = Bootstrap() mail = Mail() moment = Moment() db",
"Moment() db = SQLAlchemy() # api_manager = APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension() lm =",
"from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import LoginManager, UserMixin, login_user, logout_user, login_required bootstrap",
"de l'api REST ==> ne fonctionne pas ... # api_manager.create_api(models['User'], methods=['GET', 'DELETE']) #",
"main as main_blueprint app.register_blueprint(main_blueprint) from .csudadmin import csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from",
"de déboguage # toolbar.init_app(app) # Blueprint main from .main import main as main_blueprint",
"flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment import Moment from flask_sqlalchemy",
"api_manager.init_app(app) # initialisation de la barre de déboguage # toolbar.init_app(app) # Blueprint main",
"from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from config import config from",
"moment = Moment() db = SQLAlchemy() # api_manager = APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension()",
"ne fonctionne pas ... # api_manager.create_api(models['User'], methods=['GET', 'DELETE']) # api_manager.init_app(app) # initialisation de",
"from flask_mail import Mail from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from",
"barre de déboguage # toolbar.init_app(app) # Blueprint main from .main import main as",
"api_manager = APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension() lm = LoginManager() lm.login_view = 'main.login' def",
"csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from .sendmail import sendmail as sendmail_blueprint app.register_blueprint(sendmail_blueprint, url_prefix='/sendmail')",
"Bootstrap from flask_mail import Mail from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy",
"toolbar = DebugToolbarExtension() lm = LoginManager() lm.login_view = 'main.login' def create_app(config_name, models={}): app",
"import main as main_blueprint app.register_blueprint(main_blueprint) from .csudadmin import csudadmin as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin')",
"as csudadmin_blueprint app.register_blueprint(csudadmin_blueprint, url_prefix='/csudadmin') from .sendmail import sendmail as sendmail_blueprint app.register_blueprint(sendmail_blueprint, url_prefix='/sendmail') return",
"fonctionne pas ... # api_manager.create_api(models['User'], methods=['GET', 'DELETE']) # api_manager.init_app(app) # initialisation de la",
"= SQLAlchemy() # api_manager = APIManager(flask_sqlalchemy_db=db) toolbar = DebugToolbarExtension() lm = LoginManager() lm.login_view",
"= Flask(__name__) lm.init_app(app) User = models['User'] @lm.user_loader def load_user(id): return User.query.get(int(id)) app.config.from_object(config[config_name]) config[config_name].init_app(app)",
"create_app(config_name, models={}): app = Flask(__name__) lm.init_app(app) User = models['User'] @lm.user_loader def load_user(id): return"
] |
[
"'').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO() elif",
"param=None): resp = '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220 Ready to",
"STARTTLS with openssl s_client -connect 127.0.0.1:25 -starttls smtp ''' from .basehandler import TcpHandler",
"def _EHLO(self, param=None): resp = '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220",
"''' self.session = True TcpHandler.__init__(self, *args) def base_handle(self): self.send_response('220 {} ESMTP CallbackCatcher service",
"False else: self.session = False def _HELO(self, param=\"\"): resp = '220 Hello {}",
"class smtp(TcpHandler): NAME = \"SMTP\" DESCRIPTION = '''Another basic mail server. Records LOGIN",
"15 Sep 2017 @author: gavin test STARTTLS with openssl s_client -connect 127.0.0.1:25 -starttls",
"\"SMTP\" DESCRIPTION = '''Another basic mail server. Records LOGIN AUTH and AUTH PLAIN",
"_HELO(self, param=\"\"): resp = '220 Hello {} pleased to meet you\\r\\n'.format(param) self.send_response(resp.encode()) def",
"Ok\\r\\n') def _RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n') def _DATA(self): while True: data = self.handle_request()",
"self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT() except Exception as",
"def _MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n') def _DATA(self): while",
"Username\", creds[1]) self.add_secret(\"SMTP Password\", creds[2]) else: self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235",
"param=None): self.send_response(b'250 Ok\\r\\n') def _DATA(self): while True: data = self.handle_request() if data.startswith(b'.'): self.send_response(b'250",
"{ 'hostname': 'catcher.pentestlabs.co.uk', } def __init__(self, *args): ''' Constructor ''' self.session = True",
"= '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220 Ready to start TLS\\r\\n')",
"e: raise self.session = False else: self.session = False def _HELO(self, param=\"\"): resp",
"== 3: self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP Password\", creds[2]) else: self.add_secret(\"SMTP",
"PLAIN to secrets.''' CONFIG = { 'hostname': 'catcher.pentestlabs.co.uk', } def __init__(self, *args): '''",
"creds = credsline.split(b\"\\0\") if len(creds) == 3: self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP Username\", creds[1])",
"try: if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'):",
"openssl s_client -connect 127.0.0.1:25 -starttls smtp ''' from .basehandler import TcpHandler from catcher.settings",
"with openssl s_client -connect 127.0.0.1:25 -starttls smtp ''' from .basehandler import TcpHandler from",
"= '220 Hello {} pleased to meet you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self, param=None): resp",
"def _STARTTLS(self): self.send_response(b'220 Ready to start TLS\\r\\n') self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True)",
"UGFzc3dvcmQ6\\r\\n') password = self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235 Authentication successful\\r\\n') def _QUIT(self): self.send_response(b'221",
"SSL_KEY, SSL_CERT import ssl import os import base64 class smtp(TcpHandler): NAME = \"SMTP\"",
"self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n') def _DATA(self): while True: data =",
"__init__(self, *args): ''' Constructor ''' self.session = True TcpHandler.__init__(self, *args) def base_handle(self): self.send_response('220",
"self.session is True: data = self.handle_request().decode('utf-8') if data: line = data.rstrip() try: if",
"pleased to meet you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self, param=None): resp = '250 Hello {}\\r\\n250",
"= self.handle_request().decode('utf-8') if data: line = data.rstrip() try: if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip())",
"ssl import os import base64 class smtp(TcpHandler): NAME = \"SMTP\" DESCRIPTION = '''Another",
"PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT() except Exception",
"ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session is True: data = self.handle_request().decode('utf-8') if",
"line.startswith('QUIT'): self._QUIT() except Exception as e: raise self.session = False else: self.session =",
"self._QUIT() except Exception as e: raise self.session = False else: self.session = False",
"as e: raise self.session = False else: self.session = False def _HELO(self, param=\"\"):",
"base64.b64decode(param) creds = credsline.split(b\"\\0\") if len(creds) == 3: self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP Username\",",
"def base_handle(self): self.send_response('220 {} ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session is True:",
"AUTH PLAIN to secrets.''' CONFIG = { 'hostname': 'catcher.pentestlabs.co.uk', } def __init__(self, *args):",
"False def _HELO(self, param=\"\"): resp = '220 Hello {} pleased to meet you\\r\\n'.format(param)",
"'').strip()) elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM()",
"self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP Password\", creds[2]) else: self.add_secret(\"SMTP Username\", creds[0])",
"gavin test STARTTLS with openssl s_client -connect 127.0.0.1:25 -starttls smtp ''' from .basehandler",
"= self.handle_request() credsline = base64.b64decode(param) creds = credsline.split(b\"\\0\") if len(creds) == 3: self.add_secret(\"SMTP",
"'hostname': 'catcher.pentestlabs.co.uk', } def __init__(self, *args): ''' Constructor ''' self.session = True TcpHandler.__init__(self,",
"def _RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n') def _DATA(self): while True: data = self.handle_request() if",
"if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break def _AUTH_PLAIN(self, param=\"\"): if param == \"\": self.send_response(b'334\\r\\n')",
"PLAIN', '').strip()) elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT() except Exception as e:",
"server. Records LOGIN AUTH and AUTH PLAIN to secrets.''' CONFIG = { 'hostname':",
"credsline.split(b\"\\0\") if len(creds) == 3: self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP Password\",",
"TO'): self._RCPT_TO() elif line.startswith('DATA'): self._DATA() elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif line.startswith('AUTH",
".basehandler import TcpHandler from catcher.settings import SSL_KEY, SSL_CERT import ssl import os import",
"= { 'hostname': 'catcher.pentestlabs.co.uk', } def __init__(self, *args): ''' Constructor ''' self.session =",
"certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n') def",
"data.rstrip() try: if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif",
"_RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n') def _DATA(self): while True: data = self.handle_request() if data.startswith(b'.'):",
"to secrets.''' CONFIG = { 'hostname': 'catcher.pentestlabs.co.uk', } def __init__(self, *args): ''' Constructor",
"creds[1]) self.send_response(b'235 Authentication successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username = self.handle_request() self.add_secret(\"SMTP Username\",",
"= False else: self.session = False def _HELO(self, param=\"\"): resp = '220 Hello",
"Ready to start TLS\\r\\n') self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self, param=\"\"):",
"else: self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235 Authentication successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334",
"resp = '220 Hello {} pleased to meet you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self, param=None):",
"creds[1]) self.add_secret(\"SMTP Password\", creds[2]) else: self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235 Authentication",
"param == \"\": self.send_response(b'334\\r\\n') param = self.handle_request() credsline = base64.b64decode(param) creds = credsline.split(b\"\\0\")",
"= self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password = self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip()))",
"127.0.0.1:25 -starttls smtp ''' from .basehandler import TcpHandler from catcher.settings import SSL_KEY, SSL_CERT",
"Created on 15 Sep 2017 @author: gavin test STARTTLS with openssl s_client -connect",
"line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO() elif line.startswith('DATA'): self._DATA()",
"line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT() except",
"self.handle_request() if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break def _AUTH_PLAIN(self, param=\"\"): if param == \"\":",
"self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password = self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235",
"def __init__(self, *args): ''' Constructor ''' self.session = True TcpHandler.__init__(self, *args) def base_handle(self):",
"self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password = self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235 Authentication",
"on 15 Sep 2017 @author: gavin test STARTTLS with openssl s_client -connect 127.0.0.1:25",
"VXNlcm5hbWU6\\r\\n') username = self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password = self.handle_request() self.add_secret(\"SMTP",
"*args): ''' Constructor ''' self.session = True TcpHandler.__init__(self, *args) def base_handle(self): self.send_response('220 {}",
"LOGIN AUTH and AUTH PLAIN to secrets.''' CONFIG = { 'hostname': 'catcher.pentestlabs.co.uk', }",
"import os import base64 class smtp(TcpHandler): NAME = \"SMTP\" DESCRIPTION = '''Another basic",
"self.handle_request() credsline = base64.b64decode(param) creds = credsline.split(b\"\\0\") if len(creds) == 3: self.add_secret(\"SMTP Identity\",",
"is True: data = self.handle_request().decode('utf-8') if data: line = data.rstrip() try: if line.startswith('HELO'):",
"line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT() except Exception as e: raise self.session =",
"self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235 Authentication successful\\r\\n') def _QUIT(self): self.send_response(b'221 Bye\\r\\n') self.session =",
"NAME = \"SMTP\" DESCRIPTION = '''Another basic mail server. Records LOGIN AUTH and",
"self.session = False def _HELO(self, param=\"\"): resp = '220 Hello {} pleased to",
"self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT() except Exception as e: raise self.session = False else:",
"start TLS\\r\\n') self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n')",
"= self.handle_request() if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break def _AUTH_PLAIN(self, param=\"\"): if param ==",
"Exception as e: raise self.session = False else: self.session = False def _HELO(self,",
"successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username = self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n')",
"base64 class smtp(TcpHandler): NAME = \"SMTP\" DESCRIPTION = '''Another basic mail server. Records",
"self.add_secret(\"SMTP Password\", creds[2]) else: self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235 Authentication successful\\r\\n')",
"data: line = data.rstrip() try: if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'): self.set_fingerprint()",
"self.send_response(b'235 Authentication successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username = self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip()))",
"smtp ''' from .basehandler import TcpHandler from catcher.settings import SSL_KEY, SSL_CERT import ssl",
"= self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235 Authentication successful\\r\\n') def _QUIT(self): self.send_response(b'221 Bye\\r\\n') self.session",
"_DATA(self): while True: data = self.handle_request() if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break def _AUTH_PLAIN(self,",
"== \"\": self.send_response(b'334\\r\\n') param = self.handle_request() credsline = base64.b64decode(param) creds = credsline.split(b\"\\0\") if",
"elif line.startswith('QUIT'): self._QUIT() except Exception as e: raise self.session = False else: self.session",
"credsline = base64.b64decode(param) creds = credsline.split(b\"\\0\") if len(creds) == 3: self.add_secret(\"SMTP Identity\", creds[0])",
"creds[0]) self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235 Authentication successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username =",
"= base64.b64decode(param) creds = credsline.split(b\"\\0\") if len(creds) == 3: self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP",
"Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220 Ready to start TLS\\r\\n') self.request =",
"{} pleased to meet you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self, param=None): resp = '250 Hello",
"self.send_response('220 {} ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session is True: data =",
"if data: line = data.rstrip() try: if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'):",
"self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220 Ready to start TLS\\r\\n') self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT,",
"if param == \"\": self.send_response(b'334\\r\\n') param = self.handle_request() credsline = base64.b64decode(param) creds =",
"self.send_response(b'220 Ready to start TLS\\r\\n') self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self,",
"secrets.''' CONFIG = { 'hostname': 'catcher.pentestlabs.co.uk', } def __init__(self, *args): ''' Constructor '''",
"you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self, param=None): resp = '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def",
"elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif",
"self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'):",
"line = data.rstrip() try: if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO',",
"line.startswith('RCPT TO'): self._RCPT_TO() elif line.startswith('DATA'): self._DATA() elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif",
"def _AUTH_PLAIN(self, param=\"\"): if param == \"\": self.send_response(b'334\\r\\n') param = self.handle_request() credsline =",
"os import base64 class smtp(TcpHandler): NAME = \"SMTP\" DESCRIPTION = '''Another basic mail",
"AUTH and AUTH PLAIN to secrets.''' CONFIG = { 'hostname': 'catcher.pentestlabs.co.uk', } def",
"from .basehandler import TcpHandler from catcher.settings import SSL_KEY, SSL_CERT import ssl import os",
"creds[0]) self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP Password\", creds[2]) else: self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP Password\",",
"elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT() except Exception as e: raise self.session",
"self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO() elif line.startswith('DATA'): self._DATA() elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN',",
"-connect 127.0.0.1:25 -starttls smtp ''' from .basehandler import TcpHandler from catcher.settings import SSL_KEY,",
"data = self.handle_request() if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break def _AUTH_PLAIN(self, param=\"\"): if param",
"CONFIG = { 'hostname': 'catcher.pentestlabs.co.uk', } def __init__(self, *args): ''' Constructor ''' self.session",
"self.handle_request().decode('utf-8') if data: line = data.rstrip() try: if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif",
"STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220 Ready to start TLS\\r\\n') self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY,",
"username = self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password = self.handle_request() self.add_secret(\"SMTP Password\",",
"self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235 Authentication successful\\r\\n') def _QUIT(self): self.send_response(b'221 Bye\\r\\n') self.session = False",
"_AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username = self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password =",
"True TcpHandler.__init__(self, *args) def base_handle(self): self.send_response('220 {} ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8') while",
"from catcher.settings import SSL_KEY, SSL_CERT import ssl import os import base64 class smtp(TcpHandler):",
"TLS\\r\\n') self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n') def",
"self.session = True TcpHandler.__init__(self, *args) def base_handle(self): self.send_response('220 {} ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname),",
"self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP Password\", creds[2]) else: self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP Password\", creds[1])",
"_STARTTLS(self): self.send_response(b'220 Ready to start TLS\\r\\n') self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def",
"*args) def base_handle(self): self.send_response('220 {} ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session is",
"LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT() except Exception as e: raise self.session = False",
"server_side=True) def _MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n') def _DATA(self):",
"len(creds) == 3: self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP Password\", creds[2]) else:",
"2017 @author: gavin test STARTTLS with openssl s_client -connect 127.0.0.1:25 -starttls smtp '''",
"import SSL_KEY, SSL_CERT import ssl import os import base64 class smtp(TcpHandler): NAME =",
"self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235 Authentication successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n')",
"data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break def _AUTH_PLAIN(self, param=\"\"): if param == \"\": self.send_response(b'334\\r\\n') param",
"self._RCPT_TO() elif line.startswith('DATA'): self._DATA() elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif line.startswith('AUTH LOGIN'):",
"elif line.startswith('RCPT TO'): self._RCPT_TO() elif line.startswith('DATA'): self._DATA() elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip())",
"SSL_CERT import ssl import os import base64 class smtp(TcpHandler): NAME = \"SMTP\" DESCRIPTION",
"keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n')",
"base_handle(self): self.send_response('220 {} ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session is True: data",
"= data.rstrip() try: if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip())",
"Password\", creds[2]) else: self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235 Authentication successful\\r\\n') def",
"if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'): self._STARTTLS()",
"self._DATA() elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'):",
"self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO() elif line.startswith('DATA'): self._DATA() elif",
"param=\"\"): self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n') def _DATA(self): while True: data",
"Authentication successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username = self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334",
"param = self.handle_request() credsline = base64.b64decode(param) creds = credsline.split(b\"\\0\") if len(creds) == 3:",
"self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO()",
"line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO() elif line.startswith('DATA'): self._DATA() elif line.startswith('AUTH PLAIN'):",
"= True TcpHandler.__init__(self, *args) def base_handle(self): self.send_response('220 {} ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8')",
"Sep 2017 @author: gavin test STARTTLS with openssl s_client -connect 127.0.0.1:25 -starttls smtp",
"self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'):",
"= False def _HELO(self, param=\"\"): resp = '220 Hello {} pleased to meet",
"TcpHandler from catcher.settings import SSL_KEY, SSL_CERT import ssl import os import base64 class",
"FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO() elif line.startswith('DATA'): self._DATA() elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH",
"creds[2]) else: self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235 Authentication successful\\r\\n') def _AUTH_LOGIN(self):",
"self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235 Authentication successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username = self.handle_request()",
"{} ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session is True: data = self.handle_request().decode('utf-8')",
"while True: data = self.handle_request() if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break def _AUTH_PLAIN(self, param=\"\"):",
"param=\"\"): resp = '220 Hello {} pleased to meet you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self,",
"password = self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235 Authentication successful\\r\\n') def _QUIT(self): self.send_response(b'221 Bye\\r\\n')",
"True: data = self.handle_request() if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break def _AUTH_PLAIN(self, param=\"\"): if",
"\"\": self.send_response(b'334\\r\\n') param = self.handle_request() credsline = base64.b64decode(param) creds = credsline.split(b\"\\0\") if len(creds)",
"CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session is True: data = self.handle_request().decode('utf-8') if data:",
"mail server. Records LOGIN AUTH and AUTH PLAIN to secrets.''' CONFIG = {",
"''' Created on 15 Sep 2017 @author: gavin test STARTTLS with openssl s_client",
"raise self.session = False else: self.session = False def _HELO(self, param=\"\"): resp =",
"Records LOGIN AUTH and AUTH PLAIN to secrets.''' CONFIG = { 'hostname': 'catcher.pentestlabs.co.uk',",
"resp = '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220 Ready to start",
"= ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self, param=None):",
"elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO() elif line.startswith('DATA'):",
"Username\", creds[0]) self.add_secret(\"SMTP Password\", creds[1]) self.send_response(b'235 Authentication successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username",
"line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif",
"base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password = self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235 Authentication successful\\r\\n') def",
"import TcpHandler from catcher.settings import SSL_KEY, SSL_CERT import ssl import os import base64",
"self.send_response(b'334\\r\\n') param = self.handle_request() credsline = base64.b64decode(param) creds = credsline.split(b\"\\0\") if len(creds) ==",
"DESCRIPTION = '''Another basic mail server. Records LOGIN AUTH and AUTH PLAIN to",
"= credsline.split(b\"\\0\") if len(creds) == 3: self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP",
"service ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session is True: data = self.handle_request().decode('utf-8') if data: line",
"} def __init__(self, *args): ''' Constructor ''' self.session = True TcpHandler.__init__(self, *args) def",
"ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session is True: data = self.handle_request().decode('utf-8') if data: line =",
"encoding='utf-8') while self.session is True: data = self.handle_request().decode('utf-8') if data: line = data.rstrip()",
"meet you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self, param=None): resp = '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode())",
"import ssl import os import base64 class smtp(TcpHandler): NAME = \"SMTP\" DESCRIPTION =",
"self.send_response(b'250 Ok\\r\\n') def _DATA(self): while True: data = self.handle_request() if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n')",
"self.session = False else: self.session = False def _HELO(self, param=\"\"): resp = '220",
"def _DATA(self): while True: data = self.handle_request() if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break def",
"break def _AUTH_PLAIN(self, param=\"\"): if param == \"\": self.send_response(b'334\\r\\n') param = self.handle_request() credsline",
"Password\", creds[1]) self.send_response(b'235 Authentication successful\\r\\n') def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username = self.handle_request() self.add_secret(\"SMTP",
"test STARTTLS with openssl s_client -connect 127.0.0.1:25 -starttls smtp ''' from .basehandler import",
"and AUTH PLAIN to secrets.''' CONFIG = { 'hostname': 'catcher.pentestlabs.co.uk', } def __init__(self,",
"self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username = self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password = self.handle_request()",
"while self.session is True: data = self.handle_request().decode('utf-8') if data: line = data.rstrip() try:",
"True: data = self.handle_request().decode('utf-8') if data: line = data.rstrip() try: if line.startswith('HELO'): self.set_fingerprint()",
"line.startswith('DATA'): self._DATA() elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif",
"Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password = self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235 Authentication successful\\r\\n')",
"= \"SMTP\" DESCRIPTION = '''Another basic mail server. Records LOGIN AUTH and AUTH",
"'''Another basic mail server. Records LOGIN AUTH and AUTH PLAIN to secrets.''' CONFIG",
"'220 Hello {} pleased to meet you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self, param=None): resp =",
"self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self,",
"Identity\", creds[0]) self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP Password\", creds[2]) else: self.add_secret(\"SMTP Username\", creds[0]) self.add_secret(\"SMTP",
"except Exception as e: raise self.session = False else: self.session = False def",
"if len(creds) == 3: self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP Password\", creds[2])",
"@author: gavin test STARTTLS with openssl s_client -connect 127.0.0.1:25 -starttls smtp ''' from",
"s_client -connect 127.0.0.1:25 -starttls smtp ''' from .basehandler import TcpHandler from catcher.settings import",
"catcher.settings import SSL_KEY, SSL_CERT import ssl import os import base64 class smtp(TcpHandler): NAME",
"self.set_fingerprint() self._HELO(line.replace('HELO', '').strip()) elif line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL",
"self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password = self.handle_request() self.add_secret(\"SMTP Password\", base64.b64decode(password.strip())) self.send_response(b'235 Authentication successful\\r\\n') def _QUIT(self):",
"to meet you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self, param=None): resp = '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param)",
"<gh_stars>1-10 ''' Created on 15 Sep 2017 @author: gavin test STARTTLS with openssl",
"def _AUTH_LOGIN(self): self.send_response(b'334 VXNlcm5hbWU6\\r\\n') username = self.handle_request() self.add_secret(\"SMTP Username\", base64.b64decode(username.strip())) self.send_response(b'334 UGFzc3dvcmQ6\\r\\n') password",
"_AUTH_PLAIN(self, param=\"\"): if param == \"\": self.send_response(b'334\\r\\n') param = self.handle_request() credsline = base64.b64decode(param)",
"_MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self, param=None): self.send_response(b'250 Ok\\r\\n') def _DATA(self): while True:",
"''' from .basehandler import TcpHandler from catcher.settings import SSL_KEY, SSL_CERT import ssl import",
"''' Constructor ''' self.session = True TcpHandler.__init__(self, *args) def base_handle(self): self.send_response('220 {} ESMTP",
"data = self.handle_request().decode('utf-8') if data: line = data.rstrip() try: if line.startswith('HELO'): self.set_fingerprint() self._HELO(line.replace('HELO',",
"= '''Another basic mail server. Records LOGIN AUTH and AUTH PLAIN to secrets.'''",
"line.startswith('EHLO'): self.set_fingerprint() self._EHLO(line.replace('EHLO', '').strip()) elif line.startswith('STARTTLS'): self._STARTTLS() elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT",
"elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT()",
"Ok\\r\\n') def _DATA(self): while True: data = self.handle_request() if data.startswith(b'.'): self.send_response(b'250 Ok\\r\\n') break",
"'catcher.pentestlabs.co.uk', } def __init__(self, *args): ''' Constructor ''' self.session = True TcpHandler.__init__(self, *args)",
"elif line.startswith('DATA'): self._DATA() elif line.startswith('AUTH PLAIN'): self._AUTH_PLAIN(line.replace('AUTH PLAIN', '').strip()) elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN()",
"import base64 class smtp(TcpHandler): NAME = \"SMTP\" DESCRIPTION = '''Another basic mail server.",
"def _HELO(self, param=\"\"): resp = '220 Hello {} pleased to meet you\\r\\n'.format(param) self.send_response(resp.encode())",
"TcpHandler.__init__(self, *args) def base_handle(self): self.send_response('220 {} ESMTP CallbackCatcher service ready\\r\\n'.format(self.hostname), encoding='utf-8') while self.session",
"Ok\\r\\n') break def _AUTH_PLAIN(self, param=\"\"): if param == \"\": self.send_response(b'334\\r\\n') param = self.handle_request()",
"3: self.add_secret(\"SMTP Identity\", creds[0]) self.add_secret(\"SMTP Username\", creds[1]) self.add_secret(\"SMTP Password\", creds[2]) else: self.add_secret(\"SMTP Username\",",
"Hello {} pleased to meet you\\r\\n'.format(param) self.send_response(resp.encode()) def _EHLO(self, param=None): resp = '250",
"to start TLS\\r\\n') self.request = ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self, param=\"\"): self.send_response(b'250",
"{}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220 Ready to start TLS\\r\\n') self.request = ssl.wrap_socket(self.request,",
"'').strip()) elif line.startswith('AUTH LOGIN'): self._AUTH_LOGIN() elif line.startswith('QUIT'): self._QUIT() except Exception as e: raise",
"self.send_response(resp.encode()) def _EHLO(self, param=None): resp = '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self):",
"else: self.session = False def _HELO(self, param=\"\"): resp = '220 Hello {} pleased",
"Constructor ''' self.session = True TcpHandler.__init__(self, *args) def base_handle(self): self.send_response('220 {} ESMTP CallbackCatcher",
"basic mail server. Records LOGIN AUTH and AUTH PLAIN to secrets.''' CONFIG =",
"-starttls smtp ''' from .basehandler import TcpHandler from catcher.settings import SSL_KEY, SSL_CERT import",
"ssl.wrap_socket(self.request, keyfile=SSL_KEY, certfile=SSL_CERT, server_side=True) def _MAIL_FROM(self, param=\"\"): self.send_response(b'250 Ok\\r\\n') def _RCPT_TO(self, param=None): self.send_response(b'250",
"_EHLO(self, param=None): resp = '250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220 Ready",
"elif line.startswith('MAIL FROM'): self._MAIL_FROM() elif line.startswith('RCPT TO'): self._RCPT_TO() elif line.startswith('DATA'): self._DATA() elif line.startswith('AUTH",
"param=\"\"): if param == \"\": self.send_response(b'334\\r\\n') param = self.handle_request() credsline = base64.b64decode(param) creds",
"self.send_response(b'250 Ok\\r\\n') break def _AUTH_PLAIN(self, param=\"\"): if param == \"\": self.send_response(b'334\\r\\n') param =",
"'250 Hello {}\\r\\n250 STARTTLS\\r\\n'.format(param) self.send_response(resp.encode()) def _STARTTLS(self): self.send_response(b'220 Ready to start TLS\\r\\n') self.request",
"smtp(TcpHandler): NAME = \"SMTP\" DESCRIPTION = '''Another basic mail server. Records LOGIN AUTH"
] |
[
"\"\"\" Takes 1000 documents at a time and batch queries all of the",
"pmids = [pmid.strip() for pmid in pmids.split(',')] # fixes issue where pmid numbers",
"from .date import add_date from Bio import Entrez from Bio import Medline from",
"pmids.split(',')] # fixes issue where pmid numbers under 10 is read as 04",
"\"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"] seasons = {\"spring\":",
"there is some kind of author if record.get('AU') or record.get('CN'): citation['author'] = []",
"with this pmid. PMID: %s, rec_id: %s', pmid, rec['_id']) # this fixes the",
"doc_list.append(doc) if pmids := doc.get('pmids'): pmid_list += [pmid.strip() for pmid in pmids.split(',')] #",
"pmid := record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding'] = funding funding = [] return ct_fd",
"the citation and funding to each doc in doc_list and yield for rec",
"generator with the completed documents \"\"\" # a temporary solution to make bigger",
"make a batch api call in crawler perferrably api_key = GEO_API_KEY email =",
"make batch api query take the next 1000 docs and collect all the",
"Y/M or Y/M-M take the first day of that month Dates with only",
"doc_list and yield for rec in doc_list: if pmids := rec.pop('pmids', None): pmids",
"in pmids] for pmid in pmids: if not eutils_info.get(pmid): logger.info('There is an issue",
"if not eutils_info.get(pmid): logger.info('There is an issue with this pmid. PMID: %s, rec_id:",
"\"winter\": \" dec 1\"} s_date = date.lower().split() date_len = len(s_date) # if length",
"corp_authors := record.get('CN'): for corp_author in corp_authors: citation['author'].append({'@type': 'Organization', 'name': corp_author}) # put",
"rettype=\"medline\", retmode=\"text\") records = Medline.parse(handle) # TODO: this can get an incompleteread error",
"pmids = [ele.lstrip('0') for ele in pmids] for pmid in pmids: if not",
"if date_published := record.get('DP'): if date := get_pub_date(date_published): citation['datePublished'] = date # make",
"# https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import orjson import yaml import",
"if pmids is str: # warnings.warn(f\"Got str:{pmids} as parameter, expecting an Iterable of",
"2: if s_date[1][:3] in months: return datetime.strptime(s_date[0] + ' ' + s_date[1][:3], '%Y",
"3: return datetime.strptime(s_date[0] + ' ' + s_date[1] + ' ' + s_date[2].split('-')[0],",
"records['PubmedArticle'] funding = [] for record in records: if grants := record['MedlineCitation']['Article'].get('GrantList'): for",
"the medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") # Have to",
"import add_date from Bio import Entrez from Bio import Medline from datetime import",
"of that year TODO: Not important since only one instance so far but",
"logging logger = logging.getLogger('nde-logger') def get_pub_date(date: str): \"\"\"helper method to solve the problem",
"Dates with Y/M/D-D take only the beginning day Dates with only Y/M or",
"List, Iterable, Dict from itertools import islice from config import GEO_API_KEY, GEO_EMAIL import",
"info in batch :param pmids: A list of PubMed PMIDs :param api_key: API",
"# https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import orjson import",
"PMIDs :param api_key: API Key from NCBI to access E-utilities :return: A dictionary",
"{} # api query to parse citations handle = Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\")",
"metrological start Winter: December 1 Spring: March 1 Summer: June 1 Fall: September",
"API Key from NCBI to access E-utilities :return: A dictionary containing the pmids",
"fixes the error where there is no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if",
"Dict from itertools import islice from config import GEO_API_KEY, GEO_EMAIL import logging logger",
"config import GEO_API_KEY, GEO_EMAIL import logging logger = logging.getLogger('nde-logger') def get_pub_date(date: str): \"\"\"helper",
"citations and funding # Helpful links to documentation of Biopython Package for writing",
"Y-Y take first day of that year TODO: Not important since only one",
"take only the beginning day Dates with only Y/M or Y/M-M take the",
"Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # add in the citation",
"= date # make an empty list if there is some kind of",
"Optional, List, Iterable, Dict from itertools import islice from config import GEO_API_KEY, GEO_EMAIL",
"None # TODO add retry decorator to this function if getting too many",
"second with API Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # get",
"email, api_key) # throttle request rates, NCBI says up to 10 requests per",
"config file comment out above and enter your own email # email =",
"date) return None # if length is 3 should be year month day",
"return datetime.strptime(s_date[0] + ' ' + s_date[1] + ' ' + s_date[2].split('-')[0], '%Y",
"documentation of Biopython Package for writing this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html #",
"to use Entrez.read() instead of Entrez.parse(). The problem is discussed here: https://github.com/biopython/biopython/issues/1027 #",
"variables. Email is required. Entrez.email = email if api_key: Entrez.api_key = api_key ct_fd",
"import orjson import yaml import time from .date import add_date from Bio import",
"case \"2020 Jan - Feb\" elif date_len == 4: if s_date[1] in months",
"citation and funding info in batch :param pmids: A list of PubMed PMIDs",
"\"summer\": \" jun 1\", \"fall\": \" sep 1\", \"winter\": \" dec 1\"} s_date",
"{} # rename keys if name := record.get('TI'): citation['name'] = name if pmid",
"yield for rec in doc_list: if pmids := rec.pop('pmids', None): pmids = [pmid.strip()",
"NCBI to access E-utilities :return: A dictionary containing the pmids which hold citations",
"such as \"2000 Spring\" into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted date depending",
"or year-year if date_len == 1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if length is",
"with only Y or Y-Y take first day of that year TODO: Not",
"request rates, NCBI says up to 10 requests per second with API Key,",
"== \"-\": return datetime.strptime(s_date[0] + ' ' + s_date[1], '%Y %b').date().isoformat() else: logger.warning(\"Need",
"Entrez.read() instead of Entrez.parse(). The problem is discussed here: https://github.com/biopython/biopython/issues/1027 # TODO: this",
"records = Entrez.read(handle) records = records['PubmedArticle'] funding = [] for record in records:",
"can either be year season or year month or year month-month elif date_len",
"else: time.sleep(0.35) # add in the citation and funding to each doc in",
"where pmid numbers under 10 is read as 04 instead of 4 pmids",
"[] for record in records: if grants := record['MedlineCitation']['Article'].get('GrantList'): for grant in grants:",
"+ ' ' + s_date[1] + ' ' + s_date[2].split('-')[0], '%Y %b %d').date().isoformat()",
"Package for writing this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch",
"= {'citation': citation} # throttle request rates, NCBI says up to 10 requests",
"issue where pmid numbers under 10 is read as 04 instead of 4",
"not eutils_info.get(pmid): logger.info('There is an issue with this pmid. PMID: %s, rec_id: %s',",
"funding funding = [] return ct_fd def load_pmid_ctfd(data_folder): \"\"\" Takes 1000 documents at",
"eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding'] += funding else: rec['funding'] = funding # add the",
"no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if citation := eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation)",
"return datetime.strptime(s_date[0] + season, '%Y %b %d').date().isoformat() else: logger.warning(\"Need to update isoformat transformation:",
"rec['citation'].append(citation) else: rec['citation'] = [citation] if funding := eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding'] +=",
"no access to config file comment out above and enter your own email",
"+ '/' if journal_name := record.get('JT'): citation['journalName'] = journal_name if date_published := record.get('DP'):",
"3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # add in the citation and",
"GEO_API_KEY, GEO_EMAIL import logging logger = logging.getLogger('nde-logger') def get_pub_date(date: str): \"\"\"helper method to",
"\"dec\"] seasons = {\"spring\": \" mar 1\", \"summer\": \" jun 1\", \"fall\": \"",
"orjson.loads(line) doc_list.append(doc) if pmids := doc.get('pmids'): pmid_list += [pmid.strip() for pmid in pmids.split(',')]",
"'Organization', 'name': corp_author}) # put citation in dictionary ct_fd[pmid] = {'citation': citation} #",
"need this line. Using python package, should work both ways. # if pmids",
"api query if this happens records = list(records) for record in records: citation",
"records: if grants := record['MedlineCitation']['Article'].get('GrantList'): for grant in grants: fund = {} if",
"Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\") records = Medline.parse(handle) # TODO: this can get an",
"months and s_date[3] in months and s_date[2] == \"-\": return datetime.strptime(s_date[0] + '",
"TODO add retry decorator to this function if getting too many imcompleteread errors",
"the citation and funding into the documents along with uploading the date field.",
"1 Dates with Y/M/D-D take only the beginning day Dates with only Y/M",
"eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation) else: rec['citation'] = [citation] if funding := eutils_info[pmid].get('funding'): if",
"if record.get('AU') or record.get('CN'): citation['author'] = [] if authors := record.get('AU'): for author",
"pmid, rec['_id']) # this fixes the error where there is no pmid #",
"get_pub_date(date: str): \"\"\"helper method to solve the problem transforming dates such as \"2000",
"to documentation of Biopython Package for writing this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html",
"some kind of author if record.get('AU') or record.get('CN'): citation['author'] = [] if authors",
"funding := eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding'] += funding else: rec['funding'] = funding #",
"call instead of multiple smaller calls in crawler to improve runtime # TODO:",
"1\"} s_date = date.lower().split() date_len = len(s_date) # if length is 1 can",
"date # make an empty list if there is some kind of author",
"ct_fd[pmid] = {'citation': citation} # throttle request rates, NCBI says up to 10",
":= record.get('CN'): for corp_author in corp_authors: citation['author'].append({'@type': 'Organization', 'name': corp_author}) # put citation",
"for grant in grants: fund = {} if grant_id := grant.get('GrantID'): fund['identifier'] =",
"batch query pmid_list = [] # docs to yield for each batch query",
"containing the pmids which hold citations and funding. \"\"\" # probably dont need",
"- Feb\" elif date_len == 4: if s_date[1] in months and s_date[3] in",
"fund['identifier'] = grant_id if agency := grant.get('Agency'): fund['funder'] = {'@type': 'Organization', 'name': agency}",
"import Entrez from Bio import Medline from datetime import datetime from typing import",
"take first day of that year TODO: Not important since only one instance",
"case \"2016 11-12\" \"\"\" months = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\",",
"+= funding else: rec['funding'] = funding # add the date tranformation before yielding",
"implementation to rerun api query if this happens records = Entrez.read(handle) records =",
"Jan - Feb\" elif date_len == 4: if s_date[1] in months and s_date[3]",
"time from .date import add_date from Bio import Entrez from Bio import Medline",
"\"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"] seasons = {\"spring\": \"",
"date_published := record.get('DP'): if date := get_pub_date(date_published): citation['datePublished'] = date # make an",
"\"oct\", \"nov\", \"dec\"] seasons = {\"spring\": \" mar 1\", \"summer\": \" jun 1\",",
"citation and funding into the documents along with uploading the date field. Returns:",
"str:{pmids} as parameter, expecting an Iterable of str\", RuntimeWarning) # set up Entrez",
"funding. \"\"\" # probably dont need this line. Using python package, should work",
"and collect all the pmids next_n_lines = list(islice(f, 1000)) if not next_n_lines: break",
"'Person', 'name': author}) if corp_authors := record.get('CN'): for corp_author in corp_authors: citation['author'].append({'@type': 'Organization',",
"only one instance so far but fix edge case \"2016 11-12\" \"\"\" months",
"'%Y %b').date().isoformat() elif season := seasons.get(s_date[1]): return datetime.strptime(s_date[0] + season, '%Y %b %d').date().isoformat()",
"citation['author'] = [] if authors := record.get('AU'): for author in authors: citation['author'].append({'@type': 'Person',",
"api query take the next 1000 docs and collect all the pmids next_n_lines",
"'name': author}) if corp_authors := record.get('CN'): for corp_author in corp_authors: citation['author'].append({'@type': 'Organization', 'name':",
"implementation to rerun api query if this happens records = list(records) for record",
"error need implementation to rerun api query if this happens records = Entrez.read(handle)",
"set up Entrez variables. Email is required. Entrez.email = email if api_key: Entrez.api_key",
"is required. Entrez.email = email if api_key: Entrez.api_key = api_key ct_fd = {}",
"== 4: if s_date[1] in months and s_date[3] in months and s_date[2] ==",
"comment out above and enter your own email # email = <EMAIL> with",
"4 pmids = [ele.lstrip('0') for ele in pmids] for pmid in pmids: if",
"dates such as \"2000 Spring\" into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted date",
"'%Y %b %d').date().isoformat() # exception case there are quite a few entries with",
"required. Entrez.email = email if api_key: Entrez.api_key = api_key ct_fd = {} #",
"record['MedlineCitation']['Article'].get('GrantList'): for grant in grants: fund = {} if grant_id := grant.get('GrantID'): fund['identifier']",
":= doc.get('pmids'): pmid_list += [pmid.strip() for pmid in pmids.split(',')] # check if there",
"batch :param pmids: A list of PubMed PMIDs :param api_key: API Key from",
"list if there is some kind of author if record.get('AU') or record.get('CN'): citation['author']",
"= [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"]",
"if this happens records = Entrez.read(handle) records = records['PubmedArticle'] funding = [] for",
"citation} # throttle request rates, NCBI says up to 10 requests per second",
"parameter, expecting an Iterable of str\", RuntimeWarning) # set up Entrez variables. Email",
"quite a few entries with this case \"2020 Jan - Feb\" elif date_len",
"'%Y %b').date().isoformat() else: logger.warning(\"Need to update isoformat transformation %s\", date) else: logger.warning(\"Need to",
"PubMed PMIDs :param api_key: API Key from NCBI to access E-utilities :return: A",
"records = records['PubmedArticle'] funding = [] for record in records: if grants :=",
"many imcompleteread errors def batch_get_pmid_eutils(pmids: Iterable[str], email: str, api_key: Optional[str] = None) ->",
"December 1 Spring: March 1 Summer: June 1 Fall: September 1 Dates with",
"records: citation = {} # rename keys if name := record.get('TI'): citation['name'] =",
"== 1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if length is 2 can either be",
"an empty list if there is some kind of author if record.get('AU') or",
"'name': corp_author}) # put citation in dictionary ct_fd[pmid] = {'citation': citation} # throttle",
"of that month Dates with only Y or Y-Y take first day of",
"seasons = {\"spring\": \" mar 1\", \"summer\": \" jun 1\", \"fall\": \" sep",
"Loads the citation and funding into the documents along with uploading the date",
"to update isoformat transformation: %s\", date) return None # if length is 3",
"each doc in doc_list and yield for rec in doc_list: if pmids :=",
"length is 2 can either be year season or year month or year",
"to rerun api query if this happens records = list(records) for record in",
"email: str, api_key: Optional[str] = None) -> Dict: \"\"\"Use pmid to retrieve both",
"a temporary solution to make bigger batch api call instead of multiple smaller",
"' ' + s_date[1] + ' ' + s_date[2].split('-')[0], '%Y %b %d').date().isoformat() #",
"str, api_key: Optional[str] = None) -> Dict: \"\"\"Use pmid to retrieve both citation",
"+= [pmid.strip() for pmid in pmids.split(',')] # check if there are any pmids",
"writing this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os",
"date) return None # TODO add retry decorator to this function if getting",
"queries all of the pmids in the documents to improve runtime. Loads the",
"update isoformat transformation: %s\", date) return None # TODO add retry decorator to",
"to retrieve both citation and funding info in batch :param pmids: A list",
"season, '%Y %b %d').date().isoformat() else: logger.warning(\"Need to update isoformat transformation: %s\", date) return",
"pmids: A list of PubMed PMIDs :param api_key: API Key from NCBI to",
"2 can either be year season or year month or year month-month elif",
"# if no access to config file comment out above and enter your",
"if pmid_list: # batch request eutils_info = batch_get_pmid_eutils(pmid_list, email, api_key) # throttle request",
"ct_fd[pmid]['funding'] = funding funding = [] return ct_fd def load_pmid_ctfd(data_folder): \"\"\" Takes 1000",
"without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # get the funding using xml file",
"pmids next_n_lines = list(islice(f, 1000)) if not next_n_lines: break for line in next_n_lines:",
"'https://pubmed.ncbi.nlm.nih.gov/' + pmid + '/' if journal_name := record.get('JT'): citation['journalName'] = journal_name if",
"itertools import islice from config import GEO_API_KEY, GEO_EMAIL import logging logger = logging.getLogger('nde-logger')",
"only Y/M or Y/M-M take the first day of that month Dates with",
"funding = [] return ct_fd def load_pmid_ctfd(data_folder): \"\"\" Takes 1000 documents at a",
"datetime from typing import Optional, List, Iterable, Dict from itertools import islice from",
"ele in pmids] for pmid in pmids: if not eutils_info.get(pmid): logger.info('There is an",
"== 3: return datetime.strptime(s_date[0] + ' ' + s_date[1] + ' ' +",
"None) -> Dict: \"\"\"Use pmid to retrieve both citation and funding info in",
"pmids which hold citations and funding. \"\"\" # probably dont need this line.",
"only Y or Y-Y take first day of that year TODO: Not important",
"api_key: Optional[str] = None) -> Dict: \"\"\"Use pmid to retrieve both citation and",
":= record['MedlineCitation']['Article'].get('GrantList'): for grant in grants: fund = {} if grant_id := grant.get('GrantID'):",
"if pmid := record.get('PMID'): citation['pmid'] = pmid citation['identifier'] = 'PMID:' + pmid citation['url']",
"def load_pmid_ctfd(data_folder): \"\"\" Takes 1000 documents at a time and batch queries all",
"to improve runtime. Loads the citation and funding into the documents along with",
"# batch request eutils_info = batch_get_pmid_eutils(pmid_list, email, api_key) # throttle request rates, NCBI",
"error need implementation to rerun api query if this happens records = list(records)",
"\"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"] seasons =",
"month-month elif date_len == 2: if s_date[1][:3] in months: return datetime.strptime(s_date[0] + '",
"authors: citation['author'].append({'@type': 'Person', 'name': author}) if corp_authors := record.get('CN'): for corp_author in corp_authors:",
"s_date[1][:3] in months: return datetime.strptime(s_date[0] + ' ' + s_date[1][:3], '%Y %b').date().isoformat() elif",
"this happens records = Entrez.read(handle) records = records['PubmedArticle'] funding = [] for record",
"email if api_key: Entrez.api_key = api_key ct_fd = {} # api query to",
"# make an empty list if there is some kind of author if",
"record.get('AU') or record.get('CN'): citation['author'] = [] if authors := record.get('AU'): for author in",
"year season or year month or year month-month elif date_len == 2: if",
"dec 1\"} s_date = date.lower().split() date_len = len(s_date) # if length is 1",
"%d').date().isoformat() else: logger.warning(\"Need to update isoformat transformation: %s\", date) return None # if",
"def get_pub_date(date: str): \"\"\"helper method to solve the problem transforming dates such as",
"Summer: June 1 Fall: September 1 Dates with Y/M/D-D take only the beginning",
"logger.warning(\"Need to update isoformat transformation: %s\", date) return None # if length is",
"few entries with this case \"2020 Jan - Feb\" elif date_len == 4:",
"in months and s_date[3] in months and s_date[2] == \"-\": return datetime.strptime(s_date[0] +",
"retry decorator to this function if getting too many imcompleteread errors def batch_get_pmid_eutils(pmids:",
"\"2000 Spring\" into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted date depending on context:",
"None # if length is 3 should be year month day or year",
"day-day elif date_len == 3: return datetime.strptime(s_date[0] + ' ' + s_date[1] +",
"expecting an Iterable of str\", RuntimeWarning) # set up Entrez variables. Email is",
"batch queries all of the pmids in the documents to improve runtime. Loads",
"\" sep 1\", \"winter\": \" dec 1\"} s_date = date.lower().split() date_len = len(s_date)",
"Fall: September 1 Dates with Y/M/D-D take only the beginning day Dates with",
"s_date[2] == \"-\": return datetime.strptime(s_date[0] + ' ' + s_date[1], '%Y %b').date().isoformat() else:",
"Bio import Entrez from Bio import Medline from datetime import datetime from typing",
"documents at a time and batch queries all of the pmids in the",
"GEO_API_KEY email = GEO_EMAIL # if no access to config file comment out",
"= batch_get_pmid_eutils(pmid_list, email, api_key) # throttle request rates, NCBI says up to 10",
"in doc_list and yield for rec in doc_list: if pmids := rec.pop('pmids', None):",
"rec.pop('pmids', None): pmids = [pmid.strip() for pmid in pmids.split(',')] # fixes issue where",
"if s_date[1] in months and s_date[3] in months and s_date[2] == \"-\": return",
"if funding := eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding'] += funding else: rec['funding'] = funding",
"date.lower().split() date_len = len(s_date) # if length is 1 can either be year",
"'%Y %b %d').date().isoformat() else: logger.warning(\"Need to update isoformat transformation: %s\", date) return None",
"kind of author if record.get('AU') or record.get('CN'): citation['author'] = [] if authors :=",
"# throttle request rates, NCBI says up to 10 requests per second with",
"pmid_list = [] # docs to yield for each batch query doc_list =",
"there are any pmids before requesting if pmid_list: # batch request eutils_info =",
"https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import orjson import yaml",
"Seasons use metrological start Winter: December 1 Spring: March 1 Summer: June 1",
"each batch query doc_list = [] # to make batch api query take",
"isoformat transformation %s\", date) else: logger.warning(\"Need to update isoformat transformation: %s\", date) return",
"need implementation to rerun api query if this happens records = Entrez.read(handle) records",
"Biopython Package for writing this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html #",
"and yield for rec in doc_list: if pmids := rec.pop('pmids', None): pmids =",
"%s\", date) return None # if length is 3 should be year month",
"citation := eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation) else: rec['citation'] = [citation] if funding :=",
"dictionary containing the pmids which hold citations and funding. \"\"\" # probably dont",
"pmid to retrieve both citation and funding info in batch :param pmids: A",
"Entrez variables. Email is required. Entrez.email = email if api_key: Entrez.api_key = api_key",
"funding: ct_fd[pmid]['funding'] = funding funding = [] return ct_fd def load_pmid_ctfd(data_folder): \"\"\" Takes",
"3 should be year month day or year month day-day elif date_len ==",
"under 10 is read as 04 instead of 4 pmids = [ele.lstrip('0') for",
"this pmid. PMID: %s, rec_id: %s', pmid, rec['_id']) # this fixes the error",
"since only one instance so far but fix edge case \"2016 11-12\" \"\"\"",
"= pmid citation['identifier'] = 'PMID:' + pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' + pmid +",
"citation['identifier'] = 'PMID:' + pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' + pmid + '/' if",
"with API Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # get the",
"else: rec['funding'] = funding # add the date tranformation before yielding rec =",
"query doc_list = [] # to make batch api query take the next",
"= orjson.loads(line) doc_list.append(doc) if pmids := doc.get('pmids'): pmid_list += [pmid.strip() for pmid in",
"# Helper file to batch call pmids to get citations and funding #",
"date depending on context: Seasons use metrological start Winter: December 1 Spring: March",
"= {} # rename keys if name := record.get('TI'): citation['name'] = name if",
"as f: while True: # pmid list for batch query pmid_list = []",
"if authors := record.get('AU'): for author in authors: citation['author'].append({'@type': 'Person', 'name': author}) if",
"= Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\") records = Medline.parse(handle) # TODO: this can get",
"citation = {} # rename keys if name := record.get('TI'): citation['name'] = name",
"if agency := grant.get('Agency'): fund['funder'] = {'@type': 'Organization', 'name': agency} funding.append(fund) if pmid",
"Dates with only Y/M or Y/M-M take the first day of that month",
"Feb\" elif date_len == 4: if s_date[1] in months and s_date[3] in months",
"here: https://github.com/biopython/biopython/issues/1027 # TODO: this can get an incompleteread error need implementation to",
"in authors: citation['author'].append({'@type': 'Person', 'name': author}) if corp_authors := record.get('CN'): for corp_author in",
"field. Returns: A generator with the completed documents \"\"\" # a temporary solution",
"1 can either be year or year-year if date_len == 1: return datetime.strptime(s_date[0].split('-')[0],",
"both citation and funding info in batch :param pmids: A list of PubMed",
"an incompleteread error need implementation to rerun api query if this happens records",
"email = GEO_EMAIL # if no access to config file comment out above",
"add in the citation and funding to each doc in doc_list and yield",
"isoformatted date depending on context: Seasons use metrological start Winter: December 1 Spring:",
"datetime.strptime(s_date[0] + ' ' + s_date[1][:3], '%Y %b').date().isoformat() elif season := seasons.get(s_date[1]): return",
"records = list(records) for record in records: citation = {} # rename keys",
"for record in records: citation = {} # rename keys if name :=",
"edge case \"2016 11-12\" \"\"\" months = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\",",
"= 'PMID:' + pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' + pmid + '/' if journal_name",
":= record.get('JT'): citation['journalName'] = journal_name if date_published := record.get('DP'): if date := get_pub_date(date_published):",
"os import orjson import yaml import time from .date import add_date from Bio",
"instead of 4 pmids = [ele.lstrip('0') for ele in pmids] for pmid in",
"s_date = date.lower().split() date_len = len(s_date) # if length is 1 can either",
"# to make batch api query take the next 1000 docs and collect",
"in pmids.split(',')] # check if there are any pmids before requesting if pmid_list:",
":= get_pub_date(date_published): citation['datePublished'] = date # make an empty list if there is",
":= eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding'] += funding else: rec['funding'] = funding # add",
"if this happens records = list(records) for record in records: citation = {}",
"isoformat transformation: %s\", date) return None # TODO add retry decorator to this",
"transformation: %s\", date) return None # TODO add retry decorator to this function",
"+ pmid + '/' if journal_name := record.get('JT'): citation['journalName'] = journal_name if date_published",
"corp_authors: citation['author'].append({'@type': 'Organization', 'name': corp_author}) # put citation in dictionary ct_fd[pmid] = {'citation':",
"make bigger batch api call instead of multiple smaller calls in crawler to",
"1\", \"fall\": \" sep 1\", \"winter\": \" dec 1\"} s_date = date.lower().split() date_len",
"out how to make a batch api call in crawler perferrably api_key =",
"put citation in dictionary ct_fd[pmid] = {'citation': citation} # throttle request rates, NCBI",
"Key from NCBI to access E-utilities :return: A dictionary containing the pmids which",
"fund = {} if grant_id := grant.get('GrantID'): fund['identifier'] = grant_id if agency :=",
"https://github.com/biopython/biopython/issues/1027 # TODO: this can get an incompleteread error need implementation to rerun",
"4: if s_date[1] in months and s_date[3] in months and s_date[2] == \"-\":",
"pmid numbers under 10 is read as 04 instead of 4 pmids =",
"and s_date[2] == \"-\": return datetime.strptime(s_date[0] + ' ' + s_date[1], '%Y %b').date().isoformat()",
"transformation %s\", date) else: logger.warning(\"Need to update isoformat transformation: %s\", date) return None",
"rename keys if name := record.get('TI'): citation['name'] = name if pmid := record.get('PMID'):",
"Returns: An isoformatted date depending on context: Seasons use metrological start Winter: December",
"1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if length is 2 can either be year",
"as 04 instead of 4 pmids = [ele.lstrip('0') for ele in pmids] for",
"to get citations and funding # Helpful links to documentation of Biopython Package",
"entries with this case \"2020 Jan - Feb\" elif date_len == 4: if",
"fixes issue where pmid numbers under 10 is read as 04 instead of",
"Using python package, should work both ways. # if pmids is str: #",
"list(records) for record in records: citation = {} # rename keys if name",
"datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if length is 2 can either be year season or",
"\"\"\" # probably dont need this line. Using python package, should work both",
"[] # to make batch api query take the next 1000 docs and",
"Y or Y-Y take first day of that year TODO: Not important since",
"check if there are any pmids before requesting if pmid_list: # batch request",
"context: Seasons use metrological start Winter: December 1 Spring: March 1 Summer: June",
"Iterable[str], email: str, api_key: Optional[str] = None) -> Dict: \"\"\"Use pmid to retrieve",
"= None) -> Dict: \"\"\"Use pmid to retrieve both citation and funding info",
"python package, should work both ways. # if pmids is str: # warnings.warn(f\"Got",
"\"\"\" # a temporary solution to make bigger batch api call instead of",
"the problem transforming dates such as \"2000 Spring\" into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns:",
"per second with API Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) #",
"%b %d').date().isoformat() # exception case there are quite a few entries with this",
"happens records = list(records) for record in records: citation = {} # rename",
"= GEO_EMAIL # if no access to config file comment out above and",
"pmids.split(',')] # check if there are any pmids before requesting if pmid_list: #",
"to each doc in doc_list and yield for rec in doc_list: if pmids",
"True: # pmid list for batch query pmid_list = [] # docs to",
"in doc_list: if pmids := rec.pop('pmids', None): pmids = [pmid.strip() for pmid in",
"api query if this happens records = Entrez.read(handle) records = records['PubmedArticle'] funding =",
"month day or year month day-day elif date_len == 3: return datetime.strptime(s_date[0] +",
"= name if pmid := record.get('PMID'): citation['pmid'] = pmid citation['identifier'] = 'PMID:' +",
"documents \"\"\" # a temporary solution to make bigger batch api call instead",
"of Entrez.parse(). The problem is discussed here: https://github.com/biopython/biopython/issues/1027 # TODO: this can get",
"= email if api_key: Entrez.api_key = api_key ct_fd = {} # api query",
"elif season := seasons.get(s_date[1]): return datetime.strptime(s_date[0] + season, '%Y %b %d').date().isoformat() else: logger.warning(\"Need",
"year-year if date_len == 1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if length is 2",
"# rename keys if name := record.get('TI'): citation['name'] = name if pmid :=",
"# TODO: figure out how to make a batch api call in crawler",
"import Optional, List, Iterable, Dict from itertools import islice from config import GEO_API_KEY,",
"request eutils_info = batch_get_pmid_eutils(pmid_list, email, api_key) # throttle request rates, NCBI says up",
"time.sleep(0.1) else: time.sleep(0.35) # get the funding using xml file because of problems",
"uploading the date field. Returns: A generator with the completed documents \"\"\" #",
"API Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # add in the",
"pmid in pmids.split(',')] # check if there are any pmids before requesting if",
"\"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"] seasons = {\"spring\": \" mar",
"A generator with the completed documents \"\"\" # a temporary solution to make",
"errors def batch_get_pmid_eutils(pmids: Iterable[str], email: str, api_key: Optional[str] = None) -> Dict: \"\"\"Use",
"if citation := eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation) else: rec['citation'] = [citation] if funding",
"transforming dates such as \"2000 Spring\" into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted",
"pmid list for batch query pmid_list = [] # docs to yield for",
"add retry decorator to this function if getting too many imcompleteread errors def",
"name if pmid := record.get('PMID'): citation['pmid'] = pmid citation['identifier'] = 'PMID:' + pmid",
"should work both ways. # if pmids is str: # warnings.warn(f\"Got str:{pmids} as",
"day of that year TODO: Not important since only one instance so far",
"or record.get('CN'): citation['author'] = [] if authors := record.get('AU'): for author in authors:",
"smaller calls in crawler to improve runtime # TODO: figure out how to",
"10 requests per second with API Key, 3/s without. if api_key: time.sleep(0.1) else:",
"author in authors: citation['author'].append({'@type': 'Person', 'name': author}) if corp_authors := record.get('CN'): for corp_author",
"to config file comment out above and enter your own email # email",
"rec.get('citation'): rec['citation'].append(citation) else: rec['citation'] = [citation] if funding := eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding']",
"xml file because of problems parsing the medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle =",
"because of problems parsing the medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\", id=pmids,",
"package, should work both ways. # if pmids is str: # warnings.warn(f\"Got str:{pmids}",
"batch_get_pmid_eutils(pmids: Iterable[str], email: str, api_key: Optional[str] = None) -> Dict: \"\"\"Use pmid to",
"citation['author'].append({'@type': 'Organization', 'name': corp_author}) # put citation in dictionary ct_fd[pmid] = {'citation': citation}",
"import logging logger = logging.getLogger('nde-logger') def get_pub_date(date: str): \"\"\"helper method to solve the",
"\" mar 1\", \"summer\": \" jun 1\", \"fall\": \" sep 1\", \"winter\": \"",
"retmode=\"xml\") # Have to use Entrez.read() instead of Entrez.parse(). The problem is discussed",
"requesting if pmid_list: # batch request eutils_info = batch_get_pmid_eutils(pmid_list, email, api_key) # throttle",
"{'citation': citation} # throttle request rates, NCBI says up to 10 requests per",
"for pmid in pmids.split(',')] # fixes issue where pmid numbers under 10 is",
"this line. Using python package, should work both ways. # if pmids is",
"Spring: March 1 Summer: June 1 Fall: September 1 Dates with Y/M/D-D take",
"add_date from Bio import Entrez from Bio import Medline from datetime import datetime",
"retmode=\"text\") records = Medline.parse(handle) # TODO: this can get an incompleteread error need",
"with the completed documents \"\"\" # a temporary solution to make bigger batch",
"work both ways. # if pmids is str: # warnings.warn(f\"Got str:{pmids} as parameter,",
"Entrez.read(handle) records = records['PubmedArticle'] funding = [] for record in records: if grants",
"islice from config import GEO_API_KEY, GEO_EMAIL import logging logger = logging.getLogger('nde-logger') def get_pub_date(date:",
"= {'@type': 'Organization', 'name': agency} funding.append(fund) if pmid := record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding']",
"this fixes the error where there is no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid):",
"figure out how to make a batch api call in crawler perferrably api_key",
"date_len = len(s_date) # if length is 1 can either be year or",
"March 1 Summer: June 1 Fall: September 1 Dates with Y/M/D-D take only",
"time and batch queries all of the pmids in the documents to improve",
"and batch queries all of the pmids in the documents to improve runtime.",
"year or year-year if date_len == 1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if length",
"record in records: if grants := record['MedlineCitation']['Article'].get('GrantList'): for grant in grants: fund =",
"grants: fund = {} if grant_id := grant.get('GrantID'): fund['identifier'] = grant_id if agency",
"out above and enter your own email # email = <EMAIL> with open(os.path.join(data_folder,",
"that month Dates with only Y or Y-Y take first day of that",
"# TODO add retry decorator to this function if getting too many imcompleteread",
"Email is required. Entrez.email = email if api_key: Entrez.api_key = api_key ct_fd =",
"query if this happens records = Entrez.read(handle) records = records['PubmedArticle'] funding = []",
"rec.get('funding'): rec['funding'] += funding else: rec['funding'] = funding # add the date tranformation",
"'PMID:' + pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' + pmid + '/' if journal_name :=",
"# if length is 3 should be year month day or year month",
"journal_name if date_published := record.get('DP'): if date := get_pub_date(date_published): citation['datePublished'] = date #",
"isoformat transformation: %s\", date) return None # if length is 3 should be",
"from Bio import Entrez from Bio import Medline from datetime import datetime from",
"A list of PubMed PMIDs :param api_key: API Key from NCBI to access",
"yaml import time from .date import add_date from Bio import Entrez from Bio",
"is 1 can either be year or year-year if date_len == 1: return",
"and funding. \"\"\" # probably dont need this line. Using python package, should",
"\"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"] seasons = {\"spring\": \" mar 1\",",
"s_date[1], '%Y %b').date().isoformat() else: logger.warning(\"Need to update isoformat transformation %s\", date) else: logger.warning(\"Need",
"# TODO: this can get an incompleteread error need implementation to rerun api",
"corp_author}) # put citation in dictionary ct_fd[pmid] = {'citation': citation} # throttle request",
"and funding into the documents along with uploading the date field. Returns: A",
"api call instead of multiple smaller calls in crawler to improve runtime #",
"id=pmids, retmode=\"xml\") # Have to use Entrez.read() instead of Entrez.parse(). The problem is",
"while True: # pmid list for batch query pmid_list = [] # docs",
"api call in crawler perferrably api_key = GEO_API_KEY email = GEO_EMAIL # if",
"with this case \"2020 Jan - Feb\" elif date_len == 4: if s_date[1]",
"\"sep\", \"oct\", \"nov\", \"dec\"] seasons = {\"spring\": \" mar 1\", \"summer\": \" jun",
"= {} # api query to parse citations handle = Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\",",
"and funding to each doc in doc_list and yield for rec in doc_list:",
"there are quite a few entries with this case \"2020 Jan - Feb\"",
"Returns: A generator with the completed documents \"\"\" # a temporary solution to",
"\"nov\", \"dec\"] seasons = {\"spring\": \" mar 1\", \"summer\": \" jun 1\", \"fall\":",
"either be year season or year month or year month-month elif date_len ==",
"else: logger.warning(\"Need to update isoformat transformation: %s\", date) return None # TODO add",
"in months: return datetime.strptime(s_date[0] + ' ' + s_date[1][:3], '%Y %b').date().isoformat() elif season",
"parsing the medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") # Have",
"[] return ct_fd def load_pmid_ctfd(data_folder): \"\"\" Takes 1000 documents at a time and",
"https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import orjson import yaml import time from .date",
"logger.warning(\"Need to update isoformat transformation: %s\", date) return None # TODO add retry",
"from datetime import datetime from typing import Optional, List, Iterable, Dict from itertools",
"month Dates with only Y or Y-Y take first day of that year",
"numbers under 10 is read as 04 instead of 4 pmids = [ele.lstrip('0')",
"to solve the problem transforming dates such as \"2000 Spring\" into date().isoformat dates",
"%s, rec_id: %s', pmid, rec['_id']) # this fixes the error where there is",
"ways. # if pmids is str: # warnings.warn(f\"Got str:{pmids} as parameter, expecting an",
"imcompleteread errors def batch_get_pmid_eutils(pmids: Iterable[str], email: str, api_key: Optional[str] = None) -> Dict:",
"grant.get('Agency'): fund['funder'] = {'@type': 'Organization', 'name': agency} funding.append(fund) if pmid := record['MedlineCitation'].get('PMID'): if",
"typing import Optional, List, Iterable, Dict from itertools import islice from config import",
"= [ele.lstrip('0') for ele in pmids] for pmid in pmids: if not eutils_info.get(pmid):",
"https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted date depending on context: Seasons use metrological start Winter:",
"# fixes issue where pmid numbers under 10 is read as 04 instead",
"doc.get('pmids'): pmid_list += [pmid.strip() for pmid in pmids.split(',')] # check if there are",
"your own email # email = <EMAIL> with open(os.path.join(data_folder, 'data.ndjson'), 'rb') as f:",
"update isoformat transformation: %s\", date) return None # if length is 3 should",
"pmids before requesting if pmid_list: # batch request eutils_info = batch_get_pmid_eutils(pmid_list, email, api_key)",
"Helpful links to documentation of Biopython Package for writing this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162",
"%b').date().isoformat() else: logger.warning(\"Need to update isoformat transformation %s\", date) else: logger.warning(\"Need to update",
"# exception case there are quite a few entries with this case \"2020",
"return None # TODO add retry decorator to this function if getting too",
"E-utilities :return: A dictionary containing the pmids which hold citations and funding. \"\"\"",
"RuntimeWarning) # set up Entrez variables. Email is required. Entrez.email = email if",
"record in records: citation = {} # rename keys if name := record.get('TI'):",
"length is 3 should be year month day or year month day-day elif",
"if grants := record['MedlineCitation']['Article'].get('GrantList'): for grant in grants: fund = {} if grant_id",
"above and enter your own email # email = <EMAIL> with open(os.path.join(data_folder, 'data.ndjson'),",
"Not important since only one instance so far but fix edge case \"2016",
"pmid_list += [pmid.strip() for pmid in pmids.split(',')] # check if there are any",
"https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if citation := eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation) else: rec['citation'] =",
"line. Using python package, should work both ways. # if pmids is str:",
"sep 1\", \"winter\": \" dec 1\"} s_date = date.lower().split() date_len = len(s_date) #",
"the documents along with uploading the date field. Returns: A generator with the",
"break for line in next_n_lines: doc = orjson.loads(line) doc_list.append(doc) if pmids := doc.get('pmids'):",
"handle = Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") # Have to use Entrez.read() instead of Entrez.parse().",
"access to config file comment out above and enter your own email #",
"+ ' ' + s_date[2].split('-')[0], '%Y %b %d').date().isoformat() # exception case there are",
"get citations and funding # Helpful links to documentation of Biopython Package for",
"date_len == 2: if s_date[1][:3] in months: return datetime.strptime(s_date[0] + ' ' +",
"from config import GEO_API_KEY, GEO_EMAIL import logging logger = logging.getLogger('nde-logger') def get_pub_date(date: str):",
"links to documentation of Biopython Package for writing this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 #",
"use Entrez.read() instead of Entrez.parse(). The problem is discussed here: https://github.com/biopython/biopython/issues/1027 # TODO:",
"year month day-day elif date_len == 3: return datetime.strptime(s_date[0] + ' ' +",
"load_pmid_ctfd(data_folder): \"\"\" Takes 1000 documents at a time and batch queries all of",
"a batch api call in crawler perferrably api_key = GEO_API_KEY email = GEO_EMAIL",
"Have to use Entrez.read() instead of Entrez.parse(). The problem is discussed here: https://github.com/biopython/biopython/issues/1027",
"\"aug\", \"sep\", \"oct\", \"nov\", \"dec\"] seasons = {\"spring\": \" mar 1\", \"summer\": \"",
"An isoformatted date depending on context: Seasons use metrological start Winter: December 1",
"to update isoformat transformation: %s\", date) return None # TODO add retry decorator",
"+ s_date[2].split('-')[0], '%Y %b %d').date().isoformat() # exception case there are quite a few",
"this function if getting too many imcompleteread errors def batch_get_pmid_eutils(pmids: Iterable[str], email: str,",
":param api_key: API Key from NCBI to access E-utilities :return: A dictionary containing",
"'%Y').date().isoformat() # if length is 2 can either be year season or year",
":= record.get('AU'): for author in authors: citation['author'].append({'@type': 'Person', 'name': author}) if corp_authors :=",
"{} if grant_id := grant.get('GrantID'): fund['identifier'] = grant_id if agency := grant.get('Agency'): fund['funder']",
"first day of that month Dates with only Y or Y-Y take first",
"# a temporary solution to make bigger batch api call instead of multiple",
"of the pmids in the documents to improve runtime. Loads the citation and",
"if pmids := rec.pop('pmids', None): pmids = [pmid.strip() for pmid in pmids.split(',')] #",
"date_len == 4: if s_date[1] in months and s_date[3] in months and s_date[2]",
"happens records = Entrez.read(handle) records = records['PubmedArticle'] funding = [] for record in",
"docs to yield for each batch query doc_list = [] # to make",
"to this function if getting too many imcompleteread errors def batch_get_pmid_eutils(pmids: Iterable[str], email:",
"update isoformat transformation %s\", date) else: logger.warning(\"Need to update isoformat transformation: %s\", date)",
"batch api query take the next 1000 docs and collect all the pmids",
"= grant_id if agency := grant.get('Agency'): fund['funder'] = {'@type': 'Organization', 'name': agency} funding.append(fund)",
"for ele in pmids] for pmid in pmids: if not eutils_info.get(pmid): logger.info('There is",
"orjson import yaml import time from .date import add_date from Bio import Entrez",
"record.get('TI'): citation['name'] = name if pmid := record.get('PMID'): citation['pmid'] = pmid citation['identifier'] =",
"-> Dict: \"\"\"Use pmid to retrieve both citation and funding info in batch",
"from NCBI to access E-utilities :return: A dictionary containing the pmids which hold",
"author if record.get('AU') or record.get('CN'): citation['author'] = [] if authors := record.get('AU'): for",
"[pmid.strip() for pmid in pmids.split(',')] # fixes issue where pmid numbers under 10",
"Helper file to batch call pmids to get citations and funding # Helpful",
"call in crawler perferrably api_key = GEO_API_KEY email = GEO_EMAIL # if no",
"citation['journalName'] = journal_name if date_published := record.get('DP'): if date := get_pub_date(date_published): citation['datePublished'] =",
"1 Spring: March 1 Summer: June 1 Fall: September 1 Dates with Y/M/D-D",
"== 2: if s_date[1][:3] in months: return datetime.strptime(s_date[0] + ' ' + s_date[1][:3],",
"crawler to improve runtime # TODO: figure out how to make a batch",
"api_key ct_fd = {} # api query to parse citations handle = Entrez.efetch(db=\"pubmed\",",
"the pmids next_n_lines = list(islice(f, 1000)) if not next_n_lines: break for line in",
"dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted date depending on context: Seasons use metrological start",
"beginning day Dates with only Y/M or Y/M-M take the first day of",
"TODO: figure out how to make a batch api call in crawler perferrably",
"Iterable of str\", RuntimeWarning) # set up Entrez variables. Email is required. Entrez.email",
"id=pmids, rettype=\"medline\", retmode=\"text\") records = Medline.parse(handle) # TODO: this can get an incompleteread",
"or year month-month elif date_len == 2: if s_date[1][:3] in months: return datetime.strptime(s_date[0]",
"batch request eutils_info = batch_get_pmid_eutils(pmid_list, email, api_key) # throttle request rates, NCBI says",
"\"\"\" months = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\",",
"all the pmids next_n_lines = list(islice(f, 1000)) if not next_n_lines: break for line",
"can get an incompleteread error need implementation to rerun api query if this",
"with uploading the date field. Returns: A generator with the completed documents \"\"\"",
"author}) if corp_authors := record.get('CN'): for corp_author in corp_authors: citation['author'].append({'@type': 'Organization', 'name': corp_author})",
"[ele.lstrip('0') for ele in pmids] for pmid in pmids: if not eutils_info.get(pmid): logger.info('There",
"exception case there are quite a few entries with this case \"2020 Jan",
"if there is some kind of author if record.get('AU') or record.get('CN'): citation['author'] =",
"' ' + s_date[2].split('-')[0], '%Y %b %d').date().isoformat() # exception case there are quite",
"time.sleep(0.35) # add in the citation and funding to each doc in doc_list",
"return ct_fd def load_pmid_ctfd(data_folder): \"\"\" Takes 1000 documents at a time and batch",
"rec_id: %s', pmid, rec['_id']) # this fixes the error where there is no",
"= GEO_API_KEY email = GEO_EMAIL # if no access to config file comment",
"of problems parsing the medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\")",
"Entrez.api_key = api_key ct_fd = {} # api query to parse citations handle",
"04 instead of 4 pmids = [ele.lstrip('0') for ele in pmids] for pmid",
"improve runtime # TODO: figure out how to make a batch api call",
"if rec.get('citation'): rec['citation'].append(citation) else: rec['citation'] = [citation] if funding := eutils_info[pmid].get('funding'): if rec.get('funding'):",
"s_date[1] + ' ' + s_date[2].split('-')[0], '%Y %b %d').date().isoformat() # exception case there",
"June 1 Fall: September 1 Dates with Y/M/D-D take only the beginning day",
"%d').date().isoformat() # exception case there are quite a few entries with this case",
"grant.get('GrantID'): fund['identifier'] = grant_id if agency := grant.get('Agency'): fund['funder'] = {'@type': 'Organization', 'name':",
"that year TODO: Not important since only one instance so far but fix",
"the beginning day Dates with only Y/M or Y/M-M take the first day",
"as parameter, expecting an Iterable of str\", RuntimeWarning) # set up Entrez variables.",
"with only Y/M or Y/M-M take the first day of that month Dates",
"citation and funding to each doc in doc_list and yield for rec in",
"batch query doc_list = [] # to make batch api query take the",
"from Bio import Medline from datetime import datetime from typing import Optional, List,",
"[\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"] seasons",
"str\", RuntimeWarning) # set up Entrez variables. Email is required. Entrez.email = email",
"in corp_authors: citation['author'].append({'@type': 'Organization', 'name': corp_author}) # put citation in dictionary ct_fd[pmid] =",
"Takes 1000 documents at a time and batch queries all of the pmids",
"up Entrez variables. Email is required. Entrez.email = email if api_key: Entrez.api_key =",
"= Medline.parse(handle) # TODO: this can get an incompleteread error need implementation to",
"for author in authors: citation['author'].append({'@type': 'Person', 'name': author}) if corp_authors := record.get('CN'): for",
"citation in dictionary ct_fd[pmid] = {'citation': citation} # throttle request rates, NCBI says",
"file to batch call pmids to get citations and funding # Helpful links",
"api_key: API Key from NCBI to access E-utilities :return: A dictionary containing the",
"which hold citations and funding. \"\"\" # probably dont need this line. Using",
"# warnings.warn(f\"Got str:{pmids} as parameter, expecting an Iterable of str\", RuntimeWarning) # set",
"[] if authors := record.get('AU'): for author in authors: citation['author'].append({'@type': 'Person', 'name': author})",
"'rb') as f: while True: # pmid list for batch query pmid_list =",
"is some kind of author if record.get('AU') or record.get('CN'): citation['author'] = [] if",
"requests per second with API Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35)",
"= Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") # Have to use Entrez.read() instead of Entrez.parse(). The",
"elif date_len == 4: if s_date[1] in months and s_date[3] in months and",
"to parse citations handle = Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\") records = Medline.parse(handle) #",
"take the next 1000 docs and collect all the pmids next_n_lines = list(islice(f,",
"+ ' ' + s_date[1], '%Y %b').date().isoformat() else: logger.warning(\"Need to update isoformat transformation",
"\"fall\": \" sep 1\", \"winter\": \" dec 1\"} s_date = date.lower().split() date_len =",
"citation['author'].append({'@type': 'Person', 'name': author}) if corp_authors := record.get('CN'): for corp_author in corp_authors: citation['author'].append({'@type':",
"if length is 3 should be year month day or year month day-day",
"if date := get_pub_date(date_published): citation['datePublished'] = date # make an empty list if",
"PMID: %s, rec_id: %s', pmid, rec['_id']) # this fixes the error where there",
"handle = Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\") records = Medline.parse(handle) # TODO: this can",
"year month day or year month day-day elif date_len == 3: return datetime.strptime(s_date[0]",
"import GEO_API_KEY, GEO_EMAIL import logging logger = logging.getLogger('nde-logger') def get_pub_date(date: str): \"\"\"helper method",
"transformation: %s\", date) return None # if length is 3 should be year",
":= record.get('TI'): citation['name'] = name if pmid := record.get('PMID'): citation['pmid'] = pmid citation['identifier']",
"time.sleep(0.35) # get the funding using xml file because of problems parsing the",
"and funding # Helpful links to documentation of Biopython Package for writing this",
"pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if citation := eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation) else:",
"pmid citation['identifier'] = 'PMID:' + pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' + pmid + '/'",
"eutils_info.get(pmid): logger.info('There is an issue with this pmid. PMID: %s, rec_id: %s', pmid,",
"incompleteread error need implementation to rerun api query if this happens records =",
"need implementation to rerun api query if this happens records = list(records) for",
"s_date[3] in months and s_date[2] == \"-\": return datetime.strptime(s_date[0] + ' ' +",
"rec['citation'] = [citation] if funding := eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding'] += funding else:",
"# https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import orjson import yaml import time from .date import",
"into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted date depending on context: Seasons use",
"'/' if journal_name := record.get('JT'): citation['journalName'] = journal_name if date_published := record.get('DP'): if",
"batch_get_pmid_eutils(pmid_list, email, api_key) # throttle request rates, NCBI says up to 10 requests",
"pmids to get citations and funding # Helpful links to documentation of Biopython",
"list of PubMed PMIDs :param api_key: API Key from NCBI to access E-utilities",
"up to 10 requests per second with API Key, 3/s without. if api_key:",
"record.get('CN'): citation['author'] = [] if authors := record.get('AU'): for author in authors: citation['author'].append({'@type':",
"if api_key: time.sleep(0.1) else: time.sleep(0.35) # add in the citation and funding to",
"# pmid list for batch query pmid_list = [] # docs to yield",
"is read as 04 instead of 4 pmids = [ele.lstrip('0') for ele in",
"important since only one instance so far but fix edge case \"2016 11-12\"",
"elif date_len == 3: return datetime.strptime(s_date[0] + ' ' + s_date[1] + '",
"s_date[1] in months and s_date[3] in months and s_date[2] == \"-\": return datetime.strptime(s_date[0]",
"else: time.sleep(0.35) # get the funding using xml file because of problems parsing",
"problem transforming dates such as \"2000 Spring\" into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An",
"and s_date[3] in months and s_date[2] == \"-\": return datetime.strptime(s_date[0] + ' '",
"None): pmids = [pmid.strip() for pmid in pmids.split(',')] # fixes issue where pmid",
"pmids := doc.get('pmids'): pmid_list += [pmid.strip() for pmid in pmids.split(',')] # check if",
"# this fixes the error where there is no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if",
"= api_key ct_fd = {} # api query to parse citations handle =",
"pmid. PMID: %s, rec_id: %s', pmid, rec['_id']) # this fixes the error where",
"\" dec 1\"} s_date = date.lower().split() date_len = len(s_date) # if length is",
"# get the funding using xml file because of problems parsing the medline",
"date_len == 1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if length is 2 can either",
"collect all the pmids next_n_lines = list(islice(f, 1000)) if not next_n_lines: break for",
"error where there is no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if citation :=",
"elif date_len == 2: if s_date[1][:3] in months: return datetime.strptime(s_date[0] + ' '",
"10 is read as 04 instead of 4 pmids = [ele.lstrip('0') for ele",
"1000 docs and collect all the pmids next_n_lines = list(islice(f, 1000)) if not",
"%s', pmid, rec['_id']) # this fixes the error where there is no pmid",
"or year month or year month-month elif date_len == 2: if s_date[1][:3] in",
"+ season, '%Y %b %d').date().isoformat() else: logger.warning(\"Need to update isoformat transformation: %s\", date)",
"ct_fd = {} # api query to parse citations handle = Entrez.efetch(db=\"pubmed\", id=pmids,",
"citation['pmid'] = pmid citation['identifier'] = 'PMID:' + pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' + pmid",
"to rerun api query if this happens records = Entrez.read(handle) records = records['PubmedArticle']",
"record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding'] = funding funding = [] return ct_fd def load_pmid_ctfd(data_folder):",
"length is 1 can either be year or year-year if date_len == 1:",
"Iterable, Dict from itertools import islice from config import GEO_API_KEY, GEO_EMAIL import logging",
"record.get('PMID'): citation['pmid'] = pmid citation['identifier'] = 'PMID:' + pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' +",
"if pmids := doc.get('pmids'): pmid_list += [pmid.strip() for pmid in pmids.split(',')] # check",
"api_key = GEO_API_KEY email = GEO_EMAIL # if no access to config file",
"pmids] for pmid in pmids: if not eutils_info.get(pmid): logger.info('There is an issue with",
"datetime.strptime(s_date[0] + ' ' + s_date[1] + ' ' + s_date[2].split('-')[0], '%Y %b",
"grants := record['MedlineCitation']['Article'].get('GrantList'): for grant in grants: fund = {} if grant_id :=",
"from itertools import islice from config import GEO_API_KEY, GEO_EMAIL import logging logger =",
"Entrez from Bio import Medline from datetime import datetime from typing import Optional,",
"file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") # Have to use Entrez.read()",
"1000 documents at a time and batch queries all of the pmids in",
"next 1000 docs and collect all the pmids next_n_lines = list(islice(f, 1000)) if",
"access E-utilities :return: A dictionary containing the pmids which hold citations and funding.",
"or Y-Y take first day of that year TODO: Not important since only",
"months = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\",",
"# if pmids is str: # warnings.warn(f\"Got str:{pmids} as parameter, expecting an Iterable",
"getting too many imcompleteread errors def batch_get_pmid_eutils(pmids: Iterable[str], email: str, api_key: Optional[str] =",
"' ' + s_date[1][:3], '%Y %b').date().isoformat() elif season := seasons.get(s_date[1]): return datetime.strptime(s_date[0] +",
"method to solve the problem transforming dates such as \"2000 Spring\" into date().isoformat",
"import time from .date import add_date from Bio import Entrez from Bio import",
"' + s_date[2].split('-')[0], '%Y %b %d').date().isoformat() # exception case there are quite a",
":= record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding'] = funding funding = [] return ct_fd def",
"email = <EMAIL> with open(os.path.join(data_folder, 'data.ndjson'), 'rb') as f: while True: # pmid",
"https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") # Have to use Entrez.read() instead of",
"for record in records: if grants := record['MedlineCitation']['Article'].get('GrantList'): for grant in grants: fund",
"problems parsing the medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") #",
"a time and batch queries all of the pmids in the documents to",
"of author if record.get('AU') or record.get('CN'): citation['author'] = [] if authors := record.get('AU'):",
"to improve runtime # TODO: figure out how to make a batch api",
"rec['_id']) # this fixes the error where there is no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964",
"for rec in doc_list: if pmids := rec.pop('pmids', None): pmids = [pmid.strip() for",
"s_date[2].split('-')[0], '%Y %b %d').date().isoformat() # exception case there are quite a few entries",
"record.get('DP'): if date := get_pub_date(date_published): citation['datePublished'] = date # make an empty list",
"3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # get the funding using xml",
"completed documents \"\"\" # a temporary solution to make bigger batch api call",
"of PubMed PMIDs :param api_key: API Key from NCBI to access E-utilities :return:",
":= grant.get('GrantID'): fund['identifier'] = grant_id if agency := grant.get('Agency'): fund['funder'] = {'@type': 'Organization',",
"# put citation in dictionary ct_fd[pmid] = {'citation': citation} # throttle request rates,",
"is 3 should be year month day or year month day-day elif date_len",
"how to make a batch api call in crawler perferrably api_key = GEO_API_KEY",
"if api_key: time.sleep(0.1) else: time.sleep(0.35) # get the funding using xml file because",
"multiple smaller calls in crawler to improve runtime # TODO: figure out how",
"# probably dont need this line. Using python package, should work both ways.",
"API Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # get the funding",
"= logging.getLogger('nde-logger') def get_pub_date(date: str): \"\"\"helper method to solve the problem transforming dates",
"both ways. # if pmids is str: # warnings.warn(f\"Got str:{pmids} as parameter, expecting",
"logger = logging.getLogger('nde-logger') def get_pub_date(date: str): \"\"\"helper method to solve the problem transforming",
"Y/M-M take the first day of that month Dates with only Y or",
"corp_author in corp_authors: citation['author'].append({'@type': 'Organization', 'name': corp_author}) # put citation in dictionary ct_fd[pmid]",
"be year season or year month or year month-month elif date_len == 2:",
"open(os.path.join(data_folder, 'data.ndjson'), 'rb') as f: while True: # pmid list for batch query",
"for batch query pmid_list = [] # docs to yield for each batch",
"else: rec['citation'] = [citation] if funding := eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding'] += funding",
":= seasons.get(s_date[1]): return datetime.strptime(s_date[0] + season, '%Y %b %d').date().isoformat() else: logger.warning(\"Need to update",
"Dict: \"\"\"Use pmid to retrieve both citation and funding info in batch :param",
"this can get an incompleteread error need implementation to rerun api query if",
"query if this happens records = list(records) for record in records: citation =",
"\"\"\"helper method to solve the problem transforming dates such as \"2000 Spring\" into",
"= [] # to make batch api query take the next 1000 docs",
"to yield for each batch query doc_list = [] # to make batch",
"next_n_lines = list(islice(f, 1000)) if not next_n_lines: break for line in next_n_lines: doc",
"import os import orjson import yaml import time from .date import add_date from",
"funding = [] for record in records: if grants := record['MedlineCitation']['Article'].get('GrantList'): for grant",
"+ ' ' + s_date[1][:3], '%Y %b').date().isoformat() elif season := seasons.get(s_date[1]): return datetime.strptime(s_date[0]",
"+ s_date[1][:3], '%Y %b').date().isoformat() elif season := seasons.get(s_date[1]): return datetime.strptime(s_date[0] + season, '%Y",
"if corp_authors := record.get('CN'): for corp_author in corp_authors: citation['author'].append({'@type': 'Organization', 'name': corp_author}) #",
"if funding: ct_fd[pmid]['funding'] = funding funding = [] return ct_fd def load_pmid_ctfd(data_folder): \"\"\"",
"\" jun 1\", \"fall\": \" sep 1\", \"winter\": \" dec 1\"} s_date =",
"pmids in the documents to improve runtime. Loads the citation and funding into",
"enter your own email # email = <EMAIL> with open(os.path.join(data_folder, 'data.ndjson'), 'rb') as",
"[pmid.strip() for pmid in pmids.split(',')] # check if there are any pmids before",
"Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # get the funding using",
"temporary solution to make bigger batch api call instead of multiple smaller calls",
"mar 1\", \"summer\": \" jun 1\", \"fall\": \" sep 1\", \"winter\": \" dec",
"along with uploading the date field. Returns: A generator with the completed documents",
"# api query to parse citations handle = Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\") records",
"# check if there are any pmids before requesting if pmid_list: # batch",
":return: A dictionary containing the pmids which hold citations and funding. \"\"\" #",
"funding else: rec['funding'] = funding # add the date tranformation before yielding rec",
"logger.info('There is an issue with this pmid. PMID: %s, rec_id: %s', pmid, rec['_id'])",
"to make batch api query take the next 1000 docs and collect all",
"warnings.warn(f\"Got str:{pmids} as parameter, expecting an Iterable of str\", RuntimeWarning) # set up",
"<EMAIL> with open(os.path.join(data_folder, 'data.ndjson'), 'rb') as f: while True: # pmid list for",
"are quite a few entries with this case \"2020 Jan - Feb\" elif",
"in batch :param pmids: A list of PubMed PMIDs :param api_key: API Key",
"issue with this pmid. PMID: %s, rec_id: %s', pmid, rec['_id']) # this fixes",
"into the documents along with uploading the date field. Returns: A generator with",
"# https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if citation := eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation) else: rec['citation']",
"= [citation] if funding := eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding'] += funding else: rec['funding']",
"batch api call instead of multiple smaller calls in crawler to improve runtime",
"1000)) if not next_n_lines: break for line in next_n_lines: doc = orjson.loads(line) doc_list.append(doc)",
"if getting too many imcompleteread errors def batch_get_pmid_eutils(pmids: Iterable[str], email: str, api_key: Optional[str]",
"of multiple smaller calls in crawler to improve runtime # TODO: figure out",
"Bio import Medline from datetime import datetime from typing import Optional, List, Iterable,",
"= Entrez.read(handle) records = records['PubmedArticle'] funding = [] for record in records: if",
"with API Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # add in",
"this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import",
"of str\", RuntimeWarning) # set up Entrez variables. Email is required. Entrez.email =",
"to access E-utilities :return: A dictionary containing the pmids which hold citations and",
"Optional[str] = None) -> Dict: \"\"\"Use pmid to retrieve both citation and funding",
"TODO: this can get an incompleteread error need implementation to rerun api query",
"throttle request rates, NCBI says up to 10 requests per second with API",
"batch call pmids to get citations and funding # Helpful links to documentation",
"TODO: Not important since only one instance so far but fix edge case",
"else: logger.warning(\"Need to update isoformat transformation: %s\", date) return None # if length",
"of 4 pmids = [ele.lstrip('0') for ele in pmids] for pmid in pmids:",
"time.sleep(0.1) else: time.sleep(0.35) # add in the citation and funding to each doc",
"rerun api query if this happens records = Entrez.read(handle) records = records['PubmedArticle'] funding",
"return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if length is 2 can either be year season",
"a few entries with this case \"2020 Jan - Feb\" elif date_len ==",
"if name := record.get('TI'): citation['name'] = name if pmid := record.get('PMID'): citation['pmid'] =",
"api_key: Entrez.api_key = api_key ct_fd = {} # api query to parse citations",
"year TODO: Not important since only one instance so far but fix edge",
"use metrological start Winter: December 1 Spring: March 1 Summer: June 1 Fall:",
"make an empty list if there is some kind of author if record.get('AU')",
"bigger batch api call instead of multiple smaller calls in crawler to improve",
"len(s_date) # if length is 1 can either be year or year-year if",
"pmid in pmids.split(',')] # fixes issue where pmid numbers under 10 is read",
"return datetime.strptime(s_date[0] + ' ' + s_date[1][:3], '%Y %b').date().isoformat() elif season := seasons.get(s_date[1]):",
"if s_date[1][:3] in months: return datetime.strptime(s_date[0] + ' ' + s_date[1][:3], '%Y %b').date().isoformat()",
"1\", \"winter\": \" dec 1\"} s_date = date.lower().split() date_len = len(s_date) # if",
"pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' + pmid + '/' if journal_name := record.get('JT'): citation['journalName']",
"runtime # TODO: figure out how to make a batch api call in",
"citation['datePublished'] = date # make an empty list if there is some kind",
"or Y/M-M take the first day of that month Dates with only Y",
"line in next_n_lines: doc = orjson.loads(line) doc_list.append(doc) if pmids := doc.get('pmids'): pmid_list +=",
"funding using xml file because of problems parsing the medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr",
"but fix edge case \"2016 11-12\" \"\"\" months = [\"jan\", \"feb\", \"mar\", \"apr\",",
"'name': agency} funding.append(fund) if pmid := record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding'] = funding funding",
"GEO_EMAIL # if no access to config file comment out above and enter",
"for writing this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import",
"year month-month elif date_len == 2: if s_date[1][:3] in months: return datetime.strptime(s_date[0] +",
"= 'https://pubmed.ncbi.nlm.nih.gov/' + pmid + '/' if journal_name := record.get('JT'): citation['journalName'] = journal_name",
"documents to improve runtime. Loads the citation and funding into the documents along",
"journal_name := record.get('JT'): citation['journalName'] = journal_name if date_published := record.get('DP'): if date :=",
"using xml file because of problems parsing the medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle",
"agency} funding.append(fund) if pmid := record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding'] = funding funding =",
"year month or year month-month elif date_len == 2: if s_date[1][:3] in months:",
"= date.lower().split() date_len = len(s_date) # if length is 1 can either be",
"if pmid := record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding'] = funding funding = [] return",
"season or year month or year month-month elif date_len == 2: if s_date[1][:3]",
"for corp_author in corp_authors: citation['author'].append({'@type': 'Organization', 'name': corp_author}) # put citation in dictionary",
"agency := grant.get('Agency'): fund['funder'] = {'@type': 'Organization', 'name': agency} funding.append(fund) if pmid :=",
"if grant_id := grant.get('GrantID'): fund['identifier'] = grant_id if agency := grant.get('Agency'): fund['funder'] =",
"[] # docs to yield for each batch query doc_list = [] #",
"file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import orjson",
"one instance so far but fix edge case \"2016 11-12\" \"\"\" months =",
":= record.get('DP'): if date := get_pub_date(date_published): citation['datePublished'] = date # make an empty",
"rec['funding'] += funding else: rec['funding'] = funding # add the date tranformation before",
"rates, NCBI says up to 10 requests per second with API Key, 3/s",
"to 10 requests per second with API Key, 3/s without. if api_key: time.sleep(0.1)",
"name := record.get('TI'): citation['name'] = name if pmid := record.get('PMID'): citation['pmid'] = pmid",
"instead of Entrez.parse(). The problem is discussed here: https://github.com/biopython/biopython/issues/1027 # TODO: this can",
"# https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import orjson import yaml import time from",
"day of that month Dates with only Y or Y-Y take first day",
"retrieve both citation and funding info in batch :param pmids: A list of",
"parse citations handle = Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\") records = Medline.parse(handle) # TODO:",
"depending on context: Seasons use metrological start Winter: December 1 Spring: March 1",
"in records: citation = {} # rename keys if name := record.get('TI'): citation['name']",
"# Have to use Entrez.read() instead of Entrez.parse(). The problem is discussed here:",
"at a time and batch queries all of the pmids in the documents",
"\"-\": return datetime.strptime(s_date[0] + ' ' + s_date[1], '%Y %b').date().isoformat() else: logger.warning(\"Need to",
"A dictionary containing the pmids which hold citations and funding. \"\"\" # probably",
"in grants: fund = {} if grant_id := grant.get('GrantID'): fund['identifier'] = grant_id if",
"there is no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if citation := eutils_info[pmid].get('citation'): if",
"either be year or year-year if date_len == 1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() #",
"if eutils_info.get(pmid): if citation := eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation) else: rec['citation'] = [citation]",
"for pmid in pmids: if not eutils_info.get(pmid): logger.info('There is an issue with this",
"rerun api query if this happens records = list(records) for record in records:",
"if there are any pmids before requesting if pmid_list: # batch request eutils_info",
"grant_id if agency := grant.get('Agency'): fund['funder'] = {'@type': 'Organization', 'name': agency} funding.append(fund) if",
"import Medline from datetime import datetime from typing import Optional, List, Iterable, Dict",
"start Winter: December 1 Spring: March 1 Summer: June 1 Fall: September 1",
"' + s_date[1], '%Y %b').date().isoformat() else: logger.warning(\"Need to update isoformat transformation %s\", date)",
"on context: Seasons use metrological start Winter: December 1 Spring: March 1 Summer:",
"record.get('AU'): for author in authors: citation['author'].append({'@type': 'Person', 'name': author}) if corp_authors := record.get('CN'):",
"in crawler to improve runtime # TODO: figure out how to make a",
"before requesting if pmid_list: # batch request eutils_info = batch_get_pmid_eutils(pmid_list, email, api_key) #",
"pmids := rec.pop('pmids', None): pmids = [pmid.strip() for pmid in pmids.split(',')] # fixes",
"the funding using xml file because of problems parsing the medline file #",
"The problem is discussed here: https://github.com/biopython/biopython/issues/1027 # TODO: this can get an incompleteread",
":= rec.pop('pmids', None): pmids = [pmid.strip() for pmid in pmids.split(',')] # fixes issue",
"from typing import Optional, List, Iterable, Dict from itertools import islice from config",
"ct_fd def load_pmid_ctfd(data_folder): \"\"\" Takes 1000 documents at a time and batch queries",
"day Dates with only Y/M or Y/M-M take the first day of that",
"the first day of that month Dates with only Y or Y-Y take",
"be year month day or year month day-day elif date_len == 3: return",
"in months and s_date[2] == \"-\": return datetime.strptime(s_date[0] + ' ' + s_date[1],",
"probably dont need this line. Using python package, should work both ways. #",
"case there are quite a few entries with this case \"2020 Jan -",
"the documents to improve runtime. Loads the citation and funding into the documents",
"is 2 can either be year season or year month or year month-month",
"dont need this line. Using python package, should work both ways. # if",
"%s\", date) return None # TODO add retry decorator to this function if",
"' + s_date[1] + ' ' + s_date[2].split('-')[0], '%Y %b %d').date().isoformat() # exception",
"crawler perferrably api_key = GEO_API_KEY email = GEO_EMAIL # if no access to",
"record.get('JT'): citation['journalName'] = journal_name if date_published := record.get('DP'): if date := get_pub_date(date_published): citation['datePublished']",
"date := get_pub_date(date_published): citation['datePublished'] = date # make an empty list if there",
"= list(records) for record in records: citation = {} # rename keys if",
"get the funding using xml file because of problems parsing the medline file",
"= <EMAIL> with open(os.path.join(data_folder, 'data.ndjson'), 'rb') as f: while True: # pmid list",
"Dates with only Y or Y-Y take first day of that year TODO:",
"or year month day-day elif date_len == 3: return datetime.strptime(s_date[0] + ' '",
"Entrez.parse(). The problem is discussed here: https://github.com/biopython/biopython/issues/1027 # TODO: this can get an",
"funding to each doc in doc_list and yield for rec in doc_list: if",
"yield for each batch query doc_list = [] # to make batch api",
"funding into the documents along with uploading the date field. Returns: A generator",
"import yaml import time from .date import add_date from Bio import Entrez from",
"list(islice(f, 1000)) if not next_n_lines: break for line in next_n_lines: doc = orjson.loads(line)",
"date) else: logger.warning(\"Need to update isoformat transformation: %s\", date) return None # TODO",
"first day of that year TODO: Not important since only one instance so",
"the pmids in the documents to improve runtime. Loads the citation and funding",
"any pmids before requesting if pmid_list: # batch request eutils_info = batch_get_pmid_eutils(pmid_list, email,",
"for line in next_n_lines: doc = orjson.loads(line) doc_list.append(doc) if pmids := doc.get('pmids'): pmid_list",
"else: logger.warning(\"Need to update isoformat transformation %s\", date) else: logger.warning(\"Need to update isoformat",
"= records['PubmedArticle'] funding = [] for record in records: if grants := record['MedlineCitation']['Article'].get('GrantList'):",
"read as 04 instead of 4 pmids = [ele.lstrip('0') for ele in pmids]",
"rec in doc_list: if pmids := rec.pop('pmids', None): pmids = [pmid.strip() for pmid",
"and enter your own email # email = <EMAIL> with open(os.path.join(data_folder, 'data.ndjson'), 'rb')",
"str: # warnings.warn(f\"Got str:{pmids} as parameter, expecting an Iterable of str\", RuntimeWarning) #",
"to update isoformat transformation %s\", date) else: logger.warning(\"Need to update isoformat transformation: %s\",",
"' + s_date[1][:3], '%Y %b').date().isoformat() elif season := seasons.get(s_date[1]): return datetime.strptime(s_date[0] + season,",
"eutils_info = batch_get_pmid_eutils(pmid_list, email, api_key) # throttle request rates, NCBI says up to",
"= [pmid.strip() for pmid in pmids.split(',')] # fixes issue where pmid numbers under",
"s_date[1][:3], '%Y %b').date().isoformat() elif season := seasons.get(s_date[1]): return datetime.strptime(s_date[0] + season, '%Y %b",
"jun 1\", \"fall\": \" sep 1\", \"winter\": \" dec 1\"} s_date = date.lower().split()",
"to make a batch api call in crawler perferrably api_key = GEO_API_KEY email",
"pmid + '/' if journal_name := record.get('JT'): citation['journalName'] = journal_name if date_published :=",
"import datetime from typing import Optional, List, Iterable, Dict from itertools import islice",
"= [] for record in records: if grants := record['MedlineCitation']['Article'].get('GrantList'): for grant in",
"+ s_date[1] + ' ' + s_date[2].split('-')[0], '%Y %b %d').date().isoformat() # exception case",
"list for batch query pmid_list = [] # docs to yield for each",
"# Helpful links to documentation of Biopython Package for writing this file #",
"as \"2000 Spring\" into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted date depending on",
"problem is discussed here: https://github.com/biopython/biopython/issues/1027 # TODO: this can get an incompleteread error",
"to make bigger batch api call instead of multiple smaller calls in crawler",
"for pmid in pmids.split(',')] # check if there are any pmids before requesting",
"instance so far but fix edge case \"2016 11-12\" \"\"\" months = [\"jan\",",
"fund['funder'] = {'@type': 'Organization', 'name': agency} funding.append(fund) if pmid := record['MedlineCitation'].get('PMID'): if funding:",
"funding info in batch :param pmids: A list of PubMed PMIDs :param api_key:",
"Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") # Have to use Entrez.read() instead of Entrez.parse(). The problem",
":= record.get('PMID'): citation['pmid'] = pmid citation['identifier'] = 'PMID:' + pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/'",
"day or year month day-day elif date_len == 3: return datetime.strptime(s_date[0] + '",
"without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # add in the citation and funding",
"solve the problem transforming dates such as \"2000 Spring\" into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp",
"only the beginning day Dates with only Y/M or Y/M-M take the first",
"get an incompleteread error need implementation to rerun api query if this happens",
"month day-day elif date_len == 3: return datetime.strptime(s_date[0] + ' ' + s_date[1]",
"if api_key: Entrez.api_key = api_key ct_fd = {} # api query to parse",
"in pmids.split(',')] # fixes issue where pmid numbers under 10 is read as",
"with open(os.path.join(data_folder, 'data.ndjson'), 'rb') as f: while True: # pmid list for batch",
"api_key) # throttle request rates, NCBI says up to 10 requests per second",
"in the citation and funding to each doc in doc_list and yield for",
"doc = orjson.loads(line) doc_list.append(doc) if pmids := doc.get('pmids'): pmid_list += [pmid.strip() for pmid",
"= [] if authors := record.get('AU'): for author in authors: citation['author'].append({'@type': 'Person', 'name':",
"= funding # add the date tranformation before yielding rec = add_date(rec) yield",
"records = Medline.parse(handle) # TODO: this can get an incompleteread error need implementation",
"is an issue with this pmid. PMID: %s, rec_id: %s', pmid, rec['_id']) #",
"runtime. Loads the citation and funding into the documents along with uploading the",
"can either be year or year-year if date_len == 1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat()",
"so far but fix edge case \"2016 11-12\" \"\"\" months = [\"jan\", \"feb\",",
"month or year month-month elif date_len == 2: if s_date[1][:3] in months: return",
"improve runtime. Loads the citation and funding into the documents along with uploading",
"the date field. Returns: A generator with the completed documents \"\"\" # a",
"Medline from datetime import datetime from typing import Optional, List, Iterable, Dict from",
"def batch_get_pmid_eutils(pmids: Iterable[str], email: str, api_key: Optional[str] = None) -> Dict: \"\"\"Use pmid",
"solution to make bigger batch api call instead of multiple smaller calls in",
"with Y/M/D-D take only the beginning day Dates with only Y/M or Y/M-M",
"pmids is str: # warnings.warn(f\"Got str:{pmids} as parameter, expecting an Iterable of str\",",
"Medline.parse(handle) # TODO: this can get an incompleteread error need implementation to rerun",
"dictionary ct_fd[pmid] = {'citation': citation} # throttle request rates, NCBI says up to",
"logging.getLogger('nde-logger') def get_pub_date(date: str): \"\"\"helper method to solve the problem transforming dates such",
"citation['name'] = name if pmid := record.get('PMID'): citation['pmid'] = pmid citation['identifier'] = 'PMID:'",
"Winter: December 1 Spring: March 1 Summer: June 1 Fall: September 1 Dates",
"= [] # docs to yield for each batch query doc_list = []",
"pmids: if not eutils_info.get(pmid): logger.info('There is an issue with this pmid. PMID: %s,",
"authors := record.get('AU'): for author in authors: citation['author'].append({'@type': 'Person', 'name': author}) if corp_authors",
"# https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") # Have to use Entrez.read() instead",
"instead of multiple smaller calls in crawler to improve runtime # TODO: figure",
"take the first day of that month Dates with only Y or Y-Y",
"in next_n_lines: doc = orjson.loads(line) doc_list.append(doc) if pmids := doc.get('pmids'): pmid_list += [pmid.strip()",
"= [] return ct_fd def load_pmid_ctfd(data_folder): \"\"\" Takes 1000 documents at a time",
"\"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"] seasons = {\"spring\": \" mar 1\", \"summer\":",
"# if length is 2 can either be year season or year month",
"grant_id := grant.get('GrantID'): fund['identifier'] = grant_id if agency := grant.get('Agency'): fund['funder'] = {'@type':",
"next_n_lines: doc = orjson.loads(line) doc_list.append(doc) if pmids := doc.get('pmids'): pmid_list += [pmid.strip() for",
"record.get('CN'): for corp_author in corp_authors: citation['author'].append({'@type': 'Organization', 'name': corp_author}) # put citation in",
"the error where there is no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if citation",
".date import add_date from Bio import Entrez from Bio import Medline from datetime",
"too many imcompleteread errors def batch_get_pmid_eutils(pmids: Iterable[str], email: str, api_key: Optional[str] = None)",
"if journal_name := record.get('JT'): citation['journalName'] = journal_name if date_published := record.get('DP'): if date",
"far but fix edge case \"2016 11-12\" \"\"\" months = [\"jan\", \"feb\", \"mar\",",
"decorator to this function if getting too many imcompleteread errors def batch_get_pmid_eutils(pmids: Iterable[str],",
"file comment out above and enter your own email # email = <EMAIL>",
"is discussed here: https://github.com/biopython/biopython/issues/1027 # TODO: this can get an incompleteread error need",
"11-12\" \"\"\" months = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\",",
"months and s_date[2] == \"-\": return datetime.strptime(s_date[0] + ' ' + s_date[1], '%Y",
"in the documents to improve runtime. Loads the citation and funding into the",
"query pmid_list = [] # docs to yield for each batch query doc_list",
"query to parse citations handle = Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\") records = Medline.parse(handle)",
"%b').date().isoformat() elif season := seasons.get(s_date[1]): return datetime.strptime(s_date[0] + season, '%Y %b %d').date().isoformat() else:",
"for each batch query doc_list = [] # to make batch api query",
"return datetime.strptime(s_date[0] + ' ' + s_date[1], '%Y %b').date().isoformat() else: logger.warning(\"Need to update",
"this case \"2020 Jan - Feb\" elif date_len == 4: if s_date[1] in",
"documents along with uploading the date field. Returns: A generator with the completed",
"is str: # warnings.warn(f\"Got str:{pmids} as parameter, expecting an Iterable of str\", RuntimeWarning)",
"'Organization', 'name': agency} funding.append(fund) if pmid := record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding'] = funding",
"fix edge case \"2016 11-12\" \"\"\" months = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\",",
"hold citations and funding. \"\"\" # probably dont need this line. Using python",
"says up to 10 requests per second with API Key, 3/s without. if",
"\"2020 Jan - Feb\" elif date_len == 4: if s_date[1] in months and",
"all of the pmids in the documents to improve runtime. Loads the citation",
"September 1 Dates with Y/M/D-D take only the beginning day Dates with only",
"empty list if there is some kind of author if record.get('AU') or record.get('CN'):",
"doc in doc_list and yield for rec in doc_list: if pmids := rec.pop('pmids',",
"+ pmid citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' + pmid + '/' if journal_name := record.get('JT'):",
"an issue with this pmid. PMID: %s, rec_id: %s', pmid, rec['_id']) # this",
"doc_list: if pmids := rec.pop('pmids', None): pmids = [pmid.strip() for pmid in pmids.split(',')]",
"if length is 1 can either be year or year-year if date_len ==",
"where there is no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if citation := eutils_info[pmid].get('citation'):",
"function if getting too many imcompleteread errors def batch_get_pmid_eutils(pmids: Iterable[str], email: str, api_key:",
"not next_n_lines: break for line in next_n_lines: doc = orjson.loads(line) doc_list.append(doc) if pmids",
"in records: if grants := record['MedlineCitation']['Article'].get('GrantList'): for grant in grants: fund = {}",
"be year or year-year if date_len == 1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if",
"= {} if grant_id := grant.get('GrantID'): fund['identifier'] = grant_id if agency := grant.get('Agency'):",
"1 Fall: September 1 Dates with Y/M/D-D take only the beginning day Dates",
"date_len == 3: return datetime.strptime(s_date[0] + ' ' + s_date[1] + ' '",
"str): \"\"\"helper method to solve the problem transforming dates such as \"2000 Spring\"",
"= {\"spring\": \" mar 1\", \"summer\": \" jun 1\", \"fall\": \" sep 1\",",
"%b %d').date().isoformat() else: logger.warning(\"Need to update isoformat transformation: %s\", date) return None #",
"%s\", date) else: logger.warning(\"Need to update isoformat transformation: %s\", date) return None #",
"keys if name := record.get('TI'): citation['name'] = name if pmid := record.get('PMID'): citation['pmid']",
"next_n_lines: break for line in next_n_lines: doc = orjson.loads(line) doc_list.append(doc) if pmids :=",
"https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html # https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import orjson import yaml import time",
"if date_len == 1: return datetime.strptime(s_date[0].split('-')[0], '%Y').date().isoformat() # if length is 2 can",
"'data.ndjson'), 'rb') as f: while True: # pmid list for batch query pmid_list",
"file because of problems parsing the medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\",",
"\"2016 11-12\" \"\"\" months = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\",",
"# if length is 1 can either be year or year-year if date_len",
"should be year month day or year month day-day elif date_len == 3:",
"season := seasons.get(s_date[1]): return datetime.strptime(s_date[0] + season, '%Y %b %d').date().isoformat() else: logger.warning(\"Need to",
"query take the next 1000 docs and collect all the pmids next_n_lines =",
"Entrez.email = email if api_key: Entrez.api_key = api_key ct_fd = {} # api",
"citations and funding. \"\"\" # probably dont need this line. Using python package,",
"this happens records = list(records) for record in records: citation = {} #",
":param pmids: A list of PubMed PMIDs :param api_key: API Key from NCBI",
"funding # add the date tranformation before yielding rec = add_date(rec) yield rec",
"# docs to yield for each batch query doc_list = [] # to",
"rec['funding'] = funding # add the date tranformation before yielding rec = add_date(rec)",
"# add in the citation and funding to each doc in doc_list and",
"= funding funding = [] return ct_fd def load_pmid_ctfd(data_folder): \"\"\" Takes 1000 documents",
"the next 1000 docs and collect all the pmids next_n_lines = list(islice(f, 1000))",
"Spring\" into date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted date depending on context: Seasons",
"1\", \"summer\": \" jun 1\", \"fall\": \" sep 1\", \"winter\": \" dec 1\"}",
"datetime.strptime(s_date[0] + season, '%Y %b %d').date().isoformat() else: logger.warning(\"Need to update isoformat transformation: %s\",",
"= list(islice(f, 1000)) if not next_n_lines: break for line in next_n_lines: doc =",
"Y/M/D-D take only the beginning day Dates with only Y/M or Y/M-M take",
"= len(s_date) # if length is 1 can either be year or year-year",
"api query to parse citations handle = Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\") records =",
"in pmids: if not eutils_info.get(pmid): logger.info('There is an issue with this pmid. PMID:",
"calls in crawler to improve runtime # TODO: figure out how to make",
":= grant.get('Agency'): fund['funder'] = {'@type': 'Organization', 'name': agency} funding.append(fund) if pmid := record['MedlineCitation'].get('PMID'):",
"second with API Key, 3/s without. if api_key: time.sleep(0.1) else: time.sleep(0.35) # add",
"if no access to config file comment out above and enter your own",
"datetime.strptime(s_date[0] + ' ' + s_date[1], '%Y %b').date().isoformat() else: logger.warning(\"Need to update isoformat",
"' ' + s_date[1], '%Y %b').date().isoformat() else: logger.warning(\"Need to update isoformat transformation %s\",",
"doc_list = [] # to make batch api query take the next 1000",
"in crawler perferrably api_key = GEO_API_KEY email = GEO_EMAIL # if no access",
"api_key: time.sleep(0.1) else: time.sleep(0.35) # get the funding using xml file because of",
"return None # if length is 3 should be year month day or",
"# email = <EMAIL> with open(os.path.join(data_folder, 'data.ndjson'), 'rb') as f: while True: #",
"medline file # https://www.nlm.nih.gov/bsd/mms/medlineelements.html#gr handle = Entrez.efetch(db=\"pubmed\", id=pmids, retmode=\"xml\") # Have to use",
"eutils_info.get(pmid): if citation := eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation) else: rec['citation'] = [citation] if",
"# set up Entrez variables. Email is required. Entrez.email = email if api_key:",
"if rec.get('funding'): rec['funding'] += funding else: rec['funding'] = funding # add the date",
"funding.append(fund) if pmid := record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding'] = funding funding = []",
"GEO_EMAIL import logging logger = logging.getLogger('nde-logger') def get_pub_date(date: str): \"\"\"helper method to solve",
"to batch call pmids to get citations and funding # Helpful links to",
"the completed documents \"\"\" # a temporary solution to make bigger batch api",
"of Biopython Package for writing this file # https://biopython.org/DIST/docs/tutorial/Tutorial.html#sec162 # https://biopython.org/docs/1.76/api/Bio.Entrez.html # https://www.nlm.nih.gov/bsd/mms/medlineelements.html",
"grant in grants: fund = {} if grant_id := grant.get('GrantID'): fund['identifier'] = grant_id",
"pmid in pmids: if not eutils_info.get(pmid): logger.info('There is an issue with this pmid.",
"are any pmids before requesting if pmid_list: # batch request eutils_info = batch_get_pmid_eutils(pmid_list,",
"api_key: time.sleep(0.1) else: time.sleep(0.35) # add in the citation and funding to each",
"an Iterable of str\", RuntimeWarning) # set up Entrez variables. Email is required.",
"<reponame>NIAID-Data-Ecosystem/nde-crawlers<gh_stars>0 # Helper file to batch call pmids to get citations and funding",
"call pmids to get citations and funding # Helpful links to documentation of",
"citation['url'] = 'https://pubmed.ncbi.nlm.nih.gov/' + pmid + '/' if journal_name := record.get('JT'): citation['journalName'] =",
"in dictionary ct_fd[pmid] = {'citation': citation} # throttle request rates, NCBI says up",
"if not next_n_lines: break for line in next_n_lines: doc = orjson.loads(line) doc_list.append(doc) if",
"if length is 2 can either be year season or year month or",
"email # email = <EMAIL> with open(os.path.join(data_folder, 'data.ndjson'), 'rb') as f: while True:",
"funding # Helpful links to documentation of Biopython Package for writing this file",
"pmid_list: # batch request eutils_info = batch_get_pmid_eutils(pmid_list, email, api_key) # throttle request rates,",
"https://dataguide.nlm.nih.gov/eutilities/utilities.html#efetch import os import orjson import yaml import time from .date import add_date",
"the pmids which hold citations and funding. \"\"\" # probably dont need this",
"{\"spring\": \" mar 1\", \"summer\": \" jun 1\", \"fall\": \" sep 1\", \"winter\":",
"docs and collect all the pmids next_n_lines = list(islice(f, 1000)) if not next_n_lines:",
"is no pmid # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE41964 if eutils_info.get(pmid): if citation := eutils_info[pmid].get('citation'): if rec.get('citation'):",
"seasons.get(s_date[1]): return datetime.strptime(s_date[0] + season, '%Y %b %d').date().isoformat() else: logger.warning(\"Need to update isoformat",
"date().isoformat dates https://www.nlm.nih.gov/bsd/mms/medlineelements.html#dp Returns: An isoformatted date depending on context: Seasons use metrological",
"and funding info in batch :param pmids: A list of PubMed PMIDs :param",
"+ s_date[1], '%Y %b').date().isoformat() else: logger.warning(\"Need to update isoformat transformation %s\", date) else:",
"own email # email = <EMAIL> with open(os.path.join(data_folder, 'data.ndjson'), 'rb') as f: while",
"1 Summer: June 1 Fall: September 1 Dates with Y/M/D-D take only the",
"[citation] if funding := eutils_info[pmid].get('funding'): if rec.get('funding'): rec['funding'] += funding else: rec['funding'] =",
"logger.warning(\"Need to update isoformat transformation %s\", date) else: logger.warning(\"Need to update isoformat transformation:",
"\"\"\"Use pmid to retrieve both citation and funding info in batch :param pmids:",
"citations handle = Entrez.efetch(db=\"pubmed\", id=pmids, rettype=\"medline\", retmode=\"text\") records = Medline.parse(handle) # TODO: this",
"batch api call in crawler perferrably api_key = GEO_API_KEY email = GEO_EMAIL #",
":= eutils_info[pmid].get('citation'): if rec.get('citation'): rec['citation'].append(citation) else: rec['citation'] = [citation] if funding := eutils_info[pmid].get('funding'):",
"date field. Returns: A generator with the completed documents \"\"\" # a temporary",
"= journal_name if date_published := record.get('DP'): if date := get_pub_date(date_published): citation['datePublished'] = date",
"f: while True: # pmid list for batch query pmid_list = [] #",
"months: return datetime.strptime(s_date[0] + ' ' + s_date[1][:3], '%Y %b').date().isoformat() elif season :=",
"discussed here: https://github.com/biopython/biopython/issues/1027 # TODO: this can get an incompleteread error need implementation",
"get_pub_date(date_published): citation['datePublished'] = date # make an empty list if there is some",
"datetime import datetime from typing import Optional, List, Iterable, Dict from itertools import",
"NCBI says up to 10 requests per second with API Key, 3/s without.",
"pmid := record.get('PMID'): citation['pmid'] = pmid citation['identifier'] = 'PMID:' + pmid citation['url'] =",
"{'@type': 'Organization', 'name': agency} funding.append(fund) if pmid := record['MedlineCitation'].get('PMID'): if funding: ct_fd[pmid]['funding'] =",
"import islice from config import GEO_API_KEY, GEO_EMAIL import logging logger = logging.getLogger('nde-logger') def",
"perferrably api_key = GEO_API_KEY email = GEO_EMAIL # if no access to config"
] |
[
"non-ascii-name checker. \"\"\" áéíóú = 4444 # [non-ascii-name] def úóíéá(): # [non-ascii-name] \"\"\"yo\"\"\"",
"for non-ascii-name checker. \"\"\" áéíóú = 4444 # [non-ascii-name] def úóíéá(): # [non-ascii-name]",
"\"\"\" Tests for non-ascii-name checker. \"\"\" áéíóú = 4444 # [non-ascii-name] def úóíéá():",
"Tests for non-ascii-name checker. \"\"\" áéíóú = 4444 # [non-ascii-name] def úóíéá(): #"
] |
[
"notifications are rendered even if user # killed the app printer_name = token[\"printerName\"]",
"if camera_url and camera_url.strip(): image = self.image(camera_url, hflip, vflip, rotate) except: self._logger.info(\"Could not",
"apns_token = token[\"apnsToken\"] printerID = token[\"printerID\"] # Ignore tokens that already received the",
"for public address if apns_token in used_tokens: continue # Keep track of tokens",
"For each registered token we will send a push notification # We do",
"not None: # We can send non-silent notifications (the new way) so notifications",
"the same OctoPrint instance is added twice # on the iOS app. Usually",
"= None for token in tokens: apns_token = token[\"apnsToken\"] printerID = token[\"printerID\"] #",
"notify. Values are strings def add_layer(self, layer): \"\"\" Add a new layer to",
"get_layers(self): \"\"\" Returns list of layers for which notifications will be sent \"\"\"",
"notification with # proper printer name used_tokens = [] last_result = None for",
"get a notification when print started printing at this layer self.__send__layer_notification(settings, current_layer) elif",
"try: hflip = settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"])",
"notifications (the new way) so notifications are rendered even if user # killed",
"of the camera image = None try: hflip = settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"])",
"name used_tokens = [] last_result = None for token in tokens: apns_token =",
"1: # Send a picture for first X layers (only send once layer",
"\"\"\" return self._layers def reset_layers(self): \"\"\" Reset list of layers for which notifications",
"token and token[\"printerName\"] is not None: # We can send non-silent notifications (the",
"= [] # Variable used for tracking layer numbers to notify. Values are",
"server_url.strip(): # No APNS server has been defined so do nothing return -1",
"self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url = settings.get([\"server_url\"]) if not server_url or not server_url.strip(): #",
"current_layer) elif first_layers > 0 and 1 < int(current_layer) <= first_layers + 1:",
"self.__send__layer_notification(settings, current_layer) elif first_layers > 0 and 1 < int(current_layer) <= first_layers +",
"is added twice # on the iOS app. Usually one for local address",
"picture for first X layers (only send once layer was printed) self.__send__layer_notification(settings, current_layer)",
"non-silent notifications (the new way) so notifications are rendered even if user #",
"be sent \"\"\" return self._layers def reset_layers(self): \"\"\" Reset list of layers for",
"BaseNotification class LayerNotifications(BaseNotification): def __init__(self, logger, ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts = ifttt_alerts self._alerts",
"= self.image(camera_url, hflip, vflip, rotate) except: self._logger.info(\"Could not load image from url\") #",
"and camera_url.strip(): image = self.image(camera_url, hflip, vflip, rotate) except: self._logger.info(\"Could not load image",
"of layers for which notifications will be sent \"\"\" self._layers.append(layer) def remove_layer(self, layer):",
"once layer was printed) self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self, settings, current_layer): # Send IFTTT",
"'printerID' is included so that # iOS app can properly render local notification",
"to get a notification when print started printing at this layer self.__send__layer_notification(settings, current_layer)",
"url\") # For each registered token we will send a push notification #",
"server_url + '/v1/push_printer' last_result = self._alerts.send_alert_code(settings, language_code, apns_token, url, printer_name, \"layer_changed\", None, image,",
"self._layers.remove(layer) def layer_changed(self, settings, current_layer): first_layers = settings.get_int(['notify_first_X_layers']) if current_layer in self._layers: #",
"since 'printerID' is included so that # iOS app can properly render local",
"def layer_changed(self, settings, current_layer): first_layers = settings.get_int(['notify_first_X_layers']) if current_layer in self._layers: # User",
"elif first_layers > 0 and 1 < int(current_layer) <= first_layers + 1: #",
"in used_tokens: continue # Keep track of tokens that received a notification used_tokens.append(apns_token)",
"logger, ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts = ifttt_alerts self._alerts = Alerts(self._logger) self.reset_layers() def get_layers(self):",
"that received a notification used_tokens.append(apns_token) if 'printerName' in token and token[\"printerName\"] is not",
"notification return -2 # Get a snapshot of the camera image = None",
"rotate = settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"]) if camera_url and camera_url.strip(): image = self.image(camera_url,",
"class LayerNotifications(BaseNotification): def __init__(self, logger, ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts = ifttt_alerts self._alerts =",
"list of layers for which notifications will be sent \"\"\" self._layers.append(layer) def remove_layer(self,",
"which notifications will be sent \"\"\" self._layers.remove(layer) def layer_changed(self, settings, current_layer): first_layers =",
"# Ignore tokens that already received the notification # This is the case",
"a push notification # We do it individually since 'printerID' is included so",
"def __send__layer_notification(self, settings, current_layer): # Send IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url =",
"not server_url.strip(): # No APNS server has been defined so do nothing return",
"hflip = settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"]) if",
"token[\"apnsToken\"] printerID = token[\"printerID\"] # Ignore tokens that already received the notification #",
"and one for public address if apns_token in used_tokens: continue # Keep track",
"# No iOS devices were registered so skip notification return -2 # Get",
"self.image(camera_url, hflip, vflip, rotate) except: self._logger.info(\"Could not load image from url\") # For",
"were registered so skip notification return -2 # Get a snapshot of the",
"iOS app. Usually one for local address and one for public address if",
"layer): \"\"\" Remove layer from list of layers for which notifications will be",
"# Send a picture for first X layers (only send once layer was",
"Remove layer from list of layers for which notifications will be sent \"\"\"",
"nothing return -1 tokens = settings.get([\"tokens\"]) if len(tokens) == 0: # No iOS",
"Reset list of layers for which notifications will be sent \"\"\" self._layers =",
"# This is the case when the same OctoPrint instance is added twice",
"= settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"]) if camera_url and camera_url.strip(): image = self.image(camera_url, hflip,",
"'printerName' in token and token[\"printerName\"] is not None: # We can send non-silent",
"# Variable used for tracking layer numbers to notify. Values are strings def",
"Send IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url = settings.get([\"server_url\"]) if not server_url or",
"printer name used_tokens = [] last_result = None for token in tokens: apns_token",
"killed the app printer_name = token[\"printerName\"] language_code = token[\"languageCode\"] url = server_url +",
"\"\"\" Returns list of layers for which notifications will be sent \"\"\" return",
"current_layer): first_layers = settings.get_int(['notify_first_X_layers']) if current_layer in self._layers: # User specified they wanted",
"printer_name = token[\"printerName\"] language_code = token[\"languageCode\"] url = server_url + '/v1/push_printer' last_result =",
"layer from list of layers for which notifications will be sent \"\"\" self._layers.remove(layer)",
"new way) so notifications are rendered even if user # killed the app",
"list of layers for which notifications will be sent \"\"\" return self._layers def",
"Keep track of tokens that received a notification used_tokens.append(apns_token) if 'printerName' in token",
"the case when the same OctoPrint instance is added twice # on the",
"= server_url + '/v1/push_printer' last_result = self._alerts.send_alert_code(settings, language_code, apns_token, url, printer_name, \"layer_changed\", None,",
"# User specified they wanted to get a notification when print started printing",
"settings, current_layer): first_layers = settings.get_int(['notify_first_X_layers']) if current_layer in self._layers: # User specified they",
"tokens that already received the notification # This is the case when the",
"sent \"\"\" self._layers = [] # Variable used for tracking layer numbers to",
"0: # No iOS devices were registered so skip notification return -2 #",
"already received the notification # This is the case when the same OctoPrint",
"rotate) except: self._logger.info(\"Could not load image from url\") # For each registered token",
"if apns_token in used_tokens: continue # Keep track of tokens that received a",
"Returns list of layers for which notifications will be sent \"\"\" return self._layers",
"ifttt_alerts self._alerts = Alerts(self._logger) self.reset_layers() def get_layers(self): \"\"\" Returns list of layers for",
"len(tokens) == 0: # No iOS devices were registered so skip notification return",
"for which notifications will be sent \"\"\" self._layers.remove(layer) def layer_changed(self, settings, current_layer): first_layers",
"included so that # iOS app can properly render local notification with #",
"LayerNotifications(BaseNotification): def __init__(self, logger, ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts = ifttt_alerts self._alerts = Alerts(self._logger)",
"has been defined so do nothing return -1 tokens = settings.get([\"tokens\"]) if len(tokens)",
"+ '/v1/push_printer' last_result = self._alerts.send_alert_code(settings, language_code, apns_token, url, printer_name, \"layer_changed\", None, image, current_layer)",
"from list of layers for which notifications will be sent \"\"\" self._layers.remove(layer) def",
"so that # iOS app can properly render local notification with # proper",
"current_layer) def __send__layer_notification(self, settings, current_layer): # Send IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url",
"used_tokens: continue # Keep track of tokens that received a notification used_tokens.append(apns_token) if",
"Get a snapshot of the camera image = None try: hflip = settings.get([\"webcam_flipH\"])",
"token[\"printerName\"] language_code = token[\"languageCode\"] url = server_url + '/v1/push_printer' last_result = self._alerts.send_alert_code(settings, language_code,",
"settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"]) if camera_url and camera_url.strip(): image = self.image(camera_url, hflip, vflip,",
"token[\"languageCode\"] url = server_url + '/v1/push_printer' last_result = self._alerts.send_alert_code(settings, language_code, apns_token, url, printer_name,",
"will be sent \"\"\" return self._layers def reset_layers(self): \"\"\" Reset list of layers",
"def __init__(self, logger, ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts = ifttt_alerts self._alerts = Alerts(self._logger) self.reset_layers()",
"first X layers (only send once layer was printed) self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self,",
"instance is added twice # on the iOS app. Usually one for local",
"if user # killed the app printer_name = token[\"printerName\"] language_code = token[\"languageCode\"] url",
"token[\"printerID\"] # Ignore tokens that already received the notification # This is the",
"apns_token in used_tokens: continue # Keep track of tokens that received a notification",
"layers for which notifications will be sent \"\"\" self._layers.append(layer) def remove_layer(self, layer): \"\"\"",
"# We can send non-silent notifications (the new way) so notifications are rendered",
"for which notifications will be sent \"\"\" self._layers.append(layer) def remove_layer(self, layer): \"\"\" Remove",
"a snapshot of the camera image = None try: hflip = settings.get([\"webcam_flipH\"]) vflip",
"vflip, rotate) except: self._logger.info(\"Could not load image from url\") # For each registered",
"started printing at this layer self.__send__layer_notification(settings, current_layer) elif first_layers > 0 and 1",
"def reset_layers(self): \"\"\" Reset list of layers for which notifications will be sent",
"None: # We can send non-silent notifications (the new way) so notifications are",
"Variable used for tracking layer numbers to notify. Values are strings def add_layer(self,",
"url = server_url + '/v1/push_printer' last_result = self._alerts.send_alert_code(settings, language_code, apns_token, url, printer_name, \"layer_changed\",",
"used_tokens = [] last_result = None for token in tokens: apns_token = token[\"apnsToken\"]",
"def remove_layer(self, layer): \"\"\" Remove layer from list of layers for which notifications",
"settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"]) if camera_url and",
"a picture for first X layers (only send once layer was printed) self.__send__layer_notification(settings,",
"will be sent \"\"\" self._layers.append(layer) def remove_layer(self, layer): \"\"\" Remove layer from list",
"= token[\"apnsToken\"] printerID = token[\"printerID\"] # Ignore tokens that already received the notification",
"properly render local notification with # proper printer name used_tokens = [] last_result",
"self._ifttt_alerts = ifttt_alerts self._alerts = Alerts(self._logger) self.reset_layers() def get_layers(self): \"\"\" Returns list of",
"<= first_layers + 1: # Send a picture for first X layers (only",
"layer_changed(self, settings, current_layer): first_layers = settings.get_int(['notify_first_X_layers']) if current_layer in self._layers: # User specified",
"self._layers: # User specified they wanted to get a notification when print started",
"# Keep track of tokens that received a notification used_tokens.append(apns_token) if 'printerName' in",
"BaseNotification.__init__(self, logger) self._ifttt_alerts = ifttt_alerts self._alerts = Alerts(self._logger) self.reset_layers() def get_layers(self): \"\"\" Returns",
"are strings def add_layer(self, layer): \"\"\" Add a new layer to the list",
"= settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"]) if camera_url",
"IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url = settings.get([\"server_url\"]) if not server_url or not",
"notifications will be sent \"\"\" return self._layers def reset_layers(self): \"\"\" Reset list of",
"__send__layer_notification(self, settings, current_layer): # Send IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url = settings.get([\"server_url\"])",
"reset_layers(self): \"\"\" Reset list of layers for which notifications will be sent \"\"\"",
"[] last_result = None for token in tokens: apns_token = token[\"apnsToken\"] printerID =",
"for local address and one for public address if apns_token in used_tokens: continue",
"same OctoPrint instance is added twice # on the iOS app. Usually one",
"at this layer self.__send__layer_notification(settings, current_layer) elif first_layers > 0 and 1 < int(current_layer)",
"\"layer-changed\", current_layer) server_url = settings.get([\"server_url\"]) if not server_url or not server_url.strip(): # No",
"each registered token we will send a push notification # We do it",
"been defined so do nothing return -1 tokens = settings.get([\"tokens\"]) if len(tokens) ==",
"'/v1/push_printer' last_result = self._alerts.send_alert_code(settings, language_code, apns_token, url, printer_name, \"layer_changed\", None, image, current_layer) return",
"even if user # killed the app printer_name = token[\"printerName\"] language_code = token[\"languageCode\"]",
"= Alerts(self._logger) self.reset_layers() def get_layers(self): \"\"\" Returns list of layers for which notifications",
"one for public address if apns_token in used_tokens: continue # Keep track of",
".base_notification import BaseNotification class LayerNotifications(BaseNotification): def __init__(self, logger, ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts =",
"= settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"]) if camera_url and camera_url.strip(): image",
"server_url or not server_url.strip(): # No APNS server has been defined so do",
"address if apns_token in used_tokens: continue # Keep track of tokens that received",
"Alerts(self._logger) self.reset_layers() def get_layers(self): \"\"\" Returns list of layers for which notifications will",
"current_layer) server_url = settings.get([\"server_url\"]) if not server_url or not server_url.strip(): # No APNS",
"are rendered even if user # killed the app printer_name = token[\"printerName\"] language_code",
"-1 tokens = settings.get([\"tokens\"]) if len(tokens) == 0: # No iOS devices were",
"twice # on the iOS app. Usually one for local address and one",
"new layer to the list of layers for which notifications will be sent",
"for token in tokens: apns_token = token[\"apnsToken\"] printerID = token[\"printerID\"] # Ignore tokens",
"render local notification with # proper printer name used_tokens = [] last_result =",
"they wanted to get a notification when print started printing at this layer",
"layers for which notifications will be sent \"\"\" self._layers.remove(layer) def layer_changed(self, settings, current_layer):",
"layer was printed) self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self, settings, current_layer): # Send IFTTT Notifications",
"last_result = None for token in tokens: apns_token = token[\"apnsToken\"] printerID = token[\"printerID\"]",
"import BaseNotification class LayerNotifications(BaseNotification): def __init__(self, logger, ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts = ifttt_alerts",
"address and one for public address if apns_token in used_tokens: continue # Keep",
"= settings.get([\"camera_snapshot_url\"]) if camera_url and camera_url.strip(): image = self.image(camera_url, hflip, vflip, rotate) except:",
"specified they wanted to get a notification when print started printing at this",
"We do it individually since 'printerID' is included so that # iOS app",
"proper printer name used_tokens = [] last_result = None for token in tokens:",
"# killed the app printer_name = token[\"printerName\"] language_code = token[\"languageCode\"] url = server_url",
"a notification used_tokens.append(apns_token) if 'printerName' in token and token[\"printerName\"] is not None: #",
"current_layer): # Send IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url = settings.get([\"server_url\"]) if not",
"if len(tokens) == 0: # No iOS devices were registered so skip notification",
"printerID = token[\"printerID\"] # Ignore tokens that already received the notification # This",
"self._logger.info(\"Could not load image from url\") # For each registered token we will",
"will be sent \"\"\" self._layers.remove(layer) def layer_changed(self, settings, current_layer): first_layers = settings.get_int(['notify_first_X_layers']) if",
"X layers (only send once layer was printed) self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self, settings,",
"layers (only send once layer was printed) self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self, settings, current_layer):",
"so skip notification return -2 # Get a snapshot of the camera image",
"settings.get([\"camera_snapshot_url\"]) if camera_url and camera_url.strip(): image = self.image(camera_url, hflip, vflip, rotate) except: self._logger.info(\"Could",
"notification when print started printing at this layer self.__send__layer_notification(settings, current_layer) elif first_layers >",
"-2 # Get a snapshot of the camera image = None try: hflip",
"a new layer to the list of layers for which notifications will be",
"if current_layer in self._layers: # User specified they wanted to get a notification",
"image = self.image(camera_url, hflip, vflip, rotate) except: self._logger.info(\"Could not load image from url\")",
"list of layers for which notifications will be sent \"\"\" self._layers = []",
"which notifications will be sent \"\"\" return self._layers def reset_layers(self): \"\"\" Reset list",
"# For each registered token we will send a push notification # We",
"notifications will be sent \"\"\" self._layers = [] # Variable used for tracking",
"token in tokens: apns_token = token[\"apnsToken\"] printerID = token[\"printerID\"] # Ignore tokens that",
"server_url = settings.get([\"server_url\"]) if not server_url or not server_url.strip(): # No APNS server",
"self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self, settings, current_layer): # Send IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer)",
"# proper printer name used_tokens = [] last_result = None for token in",
"\"\"\" Remove layer from list of layers for which notifications will be sent",
"settings, current_layer): # Send IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url = settings.get([\"server_url\"]) if",
"Alerts from .base_notification import BaseNotification class LayerNotifications(BaseNotification): def __init__(self, logger, ifttt_alerts): BaseNotification.__init__(self, logger)",
"of layers for which notifications will be sent \"\"\" self._layers.remove(layer) def layer_changed(self, settings,",
"registered so skip notification return -2 # Get a snapshot of the camera",
"do it individually since 'printerID' is included so that # iOS app can",
"notification # We do it individually since 'printerID' is included so that #",
"# Send IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url = settings.get([\"server_url\"]) if not server_url",
"__init__(self, logger, ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts = ifttt_alerts self._alerts = Alerts(self._logger) self.reset_layers() def",
"local address and one for public address if apns_token in used_tokens: continue #",
"strings def add_layer(self, layer): \"\"\" Add a new layer to the list of",
"token[\"printerName\"] is not None: # We can send non-silent notifications (the new way)",
"in tokens: apns_token = token[\"apnsToken\"] printerID = token[\"printerID\"] # Ignore tokens that already",
"# iOS app can properly render local notification with # proper printer name",
"public address if apns_token in used_tokens: continue # Keep track of tokens that",
"settings.get([\"tokens\"]) if len(tokens) == 0: # No iOS devices were registered so skip",
"added twice # on the iOS app. Usually one for local address and",
"Values are strings def add_layer(self, layer): \"\"\" Add a new layer to the",
"layer self.__send__layer_notification(settings, current_layer) elif first_layers > 0 and 1 < int(current_layer) <= first_layers",
"defined so do nothing return -1 tokens = settings.get([\"tokens\"]) if len(tokens) == 0:",
"language_code = token[\"languageCode\"] url = server_url + '/v1/push_printer' last_result = self._alerts.send_alert_code(settings, language_code, apns_token,",
".alerts import Alerts from .base_notification import BaseNotification class LayerNotifications(BaseNotification): def __init__(self, logger, ifttt_alerts):",
"continue # Keep track of tokens that received a notification used_tokens.append(apns_token) if 'printerName'",
"= settings.get_int(['notify_first_X_layers']) if current_layer in self._layers: # User specified they wanted to get",
"def add_layer(self, layer): \"\"\" Add a new layer to the list of layers",
"+ 1: # Send a picture for first X layers (only send once",
"app can properly render local notification with # proper printer name used_tokens =",
"settings.get_int(['notify_first_X_layers']) if current_layer in self._layers: # User specified they wanted to get a",
"vflip = settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"]) if camera_url and camera_url.strip():",
"and 1 < int(current_layer) <= first_layers + 1: # Send a picture for",
"app printer_name = token[\"printerName\"] language_code = token[\"languageCode\"] url = server_url + '/v1/push_printer' last_result",
"settings.get([\"server_url\"]) if not server_url or not server_url.strip(): # No APNS server has been",
"self._layers def reset_layers(self): \"\"\" Reset list of layers for which notifications will be",
"print started printing at this layer self.__send__layer_notification(settings, current_layer) elif first_layers > 0 and",
"User specified they wanted to get a notification when print started printing at",
"tokens = settings.get([\"tokens\"]) if len(tokens) == 0: # No iOS devices were registered",
"\"\"\" Add a new layer to the list of layers for which notifications",
"user # killed the app printer_name = token[\"printerName\"] language_code = token[\"languageCode\"] url =",
"logger) self._ifttt_alerts = ifttt_alerts self._alerts = Alerts(self._logger) self.reset_layers() def get_layers(self): \"\"\" Returns list",
"Usually one for local address and one for public address if apns_token in",
"notification # This is the case when the same OctoPrint instance is added",
"OctoPrint instance is added twice # on the iOS app. Usually one for",
"\"\"\" self._layers = [] # Variable used for tracking layer numbers to notify.",
"first_layers + 1: # Send a picture for first X layers (only send",
"notification used_tokens.append(apns_token) if 'printerName' in token and token[\"printerName\"] is not None: # We",
"can send non-silent notifications (the new way) so notifications are rendered even if",
"layer to the list of layers for which notifications will be sent \"\"\"",
"iOS devices were registered so skip notification return -2 # Get a snapshot",
"used_tokens.append(apns_token) if 'printerName' in token and token[\"printerName\"] is not None: # We can",
"that # iOS app can properly render local notification with # proper printer",
"the notification # This is the case when the same OctoPrint instance is",
"that already received the notification # This is the case when the same",
"= [] last_result = None for token in tokens: apns_token = token[\"apnsToken\"] printerID",
"= token[\"printerName\"] language_code = token[\"languageCode\"] url = server_url + '/v1/push_printer' last_result = self._alerts.send_alert_code(settings,",
"# on the iOS app. Usually one for local address and one for",
"of tokens that received a notification used_tokens.append(apns_token) if 'printerName' in token and token[\"printerName\"]",
"when the same OctoPrint instance is added twice # on the iOS app.",
"from .alerts import Alerts from .base_notification import BaseNotification class LayerNotifications(BaseNotification): def __init__(self, logger,",
"image from url\") # For each registered token we will send a push",
"sent \"\"\" self._layers.remove(layer) def layer_changed(self, settings, current_layer): first_layers = settings.get_int(['notify_first_X_layers']) if current_layer in",
"camera image = None try: hflip = settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"]) rotate =",
"the iOS app. Usually one for local address and one for public address",
"first_layers > 0 and 1 < int(current_layer) <= first_layers + 1: # Send",
"with # proper printer name used_tokens = [] last_result = None for token",
"was printed) self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self, settings, current_layer): # Send IFTTT Notifications self._ifttt_alerts.fire_event(settings,",
"No iOS devices were registered so skip notification return -2 # Get a",
"skip notification return -2 # Get a snapshot of the camera image =",
"(the new way) so notifications are rendered even if user # killed the",
"local notification with # proper printer name used_tokens = [] last_result = None",
"layers for which notifications will be sent \"\"\" self._layers = [] # Variable",
"track of tokens that received a notification used_tokens.append(apns_token) if 'printerName' in token and",
"to the list of layers for which notifications will be sent \"\"\" self._layers.append(layer)",
"will send a push notification # We do it individually since 'printerID' is",
"or not server_url.strip(): # No APNS server has been defined so do nothing",
"layers for which notifications will be sent \"\"\" return self._layers def reset_layers(self): \"\"\"",
"for which notifications will be sent \"\"\" self._layers = [] # Variable used",
"notifications will be sent \"\"\" self._layers.append(layer) def remove_layer(self, layer): \"\"\" Remove layer from",
"sent \"\"\" return self._layers def reset_layers(self): \"\"\" Reset list of layers for which",
"for first X layers (only send once layer was printed) self.__send__layer_notification(settings, current_layer) def",
"if 'printerName' in token and token[\"printerName\"] is not None: # We can send",
"\"\"\" Reset list of layers for which notifications will be sent \"\"\" self._layers",
"self.reset_layers() def get_layers(self): \"\"\" Returns list of layers for which notifications will be",
"is not None: # We can send non-silent notifications (the new way) so",
"settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"]) camera_url = settings.get([\"camera_snapshot_url\"]) if camera_url and camera_url.strip(): image =",
"printed) self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self, settings, current_layer): # Send IFTTT Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\",",
"used for tracking layer numbers to notify. Values are strings def add_layer(self, layer):",
"which notifications will be sent \"\"\" self._layers = [] # Variable used for",
"> 0 and 1 < int(current_layer) <= first_layers + 1: # Send a",
"received a notification used_tokens.append(apns_token) if 'printerName' in token and token[\"printerName\"] is not None:",
"return -1 tokens = settings.get([\"tokens\"]) if len(tokens) == 0: # No iOS devices",
"of layers for which notifications will be sent \"\"\" return self._layers def reset_layers(self):",
"sent \"\"\" self._layers.append(layer) def remove_layer(self, layer): \"\"\" Remove layer from list of layers",
"return self._layers def reset_layers(self): \"\"\" Reset list of layers for which notifications will",
"camera_url = settings.get([\"camera_snapshot_url\"]) if camera_url and camera_url.strip(): image = self.image(camera_url, hflip, vflip, rotate)",
"token we will send a push notification # We do it individually since",
"the list of layers for which notifications will be sent \"\"\" self._layers.append(layer) def",
"push notification # We do it individually since 'printerID' is included so that",
"do nothing return -1 tokens = settings.get([\"tokens\"]) if len(tokens) == 0: # No",
"iOS app can properly render local notification with # proper printer name used_tokens",
"\"\"\" self._layers.remove(layer) def layer_changed(self, settings, current_layer): first_layers = settings.get_int(['notify_first_X_layers']) if current_layer in self._layers:",
"the camera image = None try: hflip = settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"]) rotate",
"be sent \"\"\" self._layers.append(layer) def remove_layer(self, layer): \"\"\" Remove layer from list of",
"load image from url\") # For each registered token we will send a",
"individually since 'printerID' is included so that # iOS app can properly render",
"return -2 # Get a snapshot of the camera image = None try:",
"= None try: hflip = settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"]) camera_url",
"def get_layers(self): \"\"\" Returns list of layers for which notifications will be sent",
"self._layers.append(layer) def remove_layer(self, layer): \"\"\" Remove layer from list of layers for which",
"in token and token[\"printerName\"] is not None: # We can send non-silent notifications",
"Notifications self._ifttt_alerts.fire_event(settings, \"layer-changed\", current_layer) server_url = settings.get([\"server_url\"]) if not server_url or not server_url.strip():",
"None for token in tokens: apns_token = token[\"apnsToken\"] printerID = token[\"printerID\"] # Ignore",
"we will send a push notification # We do it individually since 'printerID'",
"Send a picture for first X layers (only send once layer was printed)",
"layer): \"\"\" Add a new layer to the list of layers for which",
"No APNS server has been defined so do nothing return -1 tokens =",
"Ignore tokens that already received the notification # This is the case when",
"and token[\"printerName\"] is not None: # We can send non-silent notifications (the new",
"layer numbers to notify. Values are strings def add_layer(self, layer): \"\"\" Add a",
"one for local address and one for public address if apns_token in used_tokens:",
"when print started printing at this layer self.__send__layer_notification(settings, current_layer) elif first_layers > 0",
"can properly render local notification with # proper printer name used_tokens = []",
"app. Usually one for local address and one for public address if apns_token",
"hflip, vflip, rotate) except: self._logger.info(\"Could not load image from url\") # For each",
"Add a new layer to the list of layers for which notifications will",
"APNS server has been defined so do nothing return -1 tokens = settings.get([\"tokens\"])",
"self._layers = [] # Variable used for tracking layer numbers to notify. Values",
"if not server_url or not server_url.strip(): # No APNS server has been defined",
"case when the same OctoPrint instance is added twice # on the iOS",
"way) so notifications are rendered even if user # killed the app printer_name",
"= ifttt_alerts self._alerts = Alerts(self._logger) self.reset_layers() def get_layers(self): \"\"\" Returns list of layers",
"wanted to get a notification when print started printing at this layer self.__send__layer_notification(settings,",
"of layers for which notifications will be sent \"\"\" self._layers = [] #",
"in self._layers: # User specified they wanted to get a notification when print",
"except: self._logger.info(\"Could not load image from url\") # For each registered token we",
"tokens: apns_token = token[\"apnsToken\"] printerID = token[\"printerID\"] # Ignore tokens that already received",
"# Get a snapshot of the camera image = None try: hflip =",
"< int(current_layer) <= first_layers + 1: # Send a picture for first X",
"[] # Variable used for tracking layer numbers to notify. Values are strings",
"None try: hflip = settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"]) camera_url =",
"# We do it individually since 'printerID' is included so that # iOS",
"# No APNS server has been defined so do nothing return -1 tokens",
"not load image from url\") # For each registered token we will send",
"be sent \"\"\" self._layers = [] # Variable used for tracking layer numbers",
"be sent \"\"\" self._layers.remove(layer) def layer_changed(self, settings, current_layer): first_layers = settings.get_int(['notify_first_X_layers']) if current_layer",
"the app printer_name = token[\"printerName\"] language_code = token[\"languageCode\"] url = server_url + '/v1/push_printer'",
"= token[\"printerID\"] # Ignore tokens that already received the notification # This is",
"printing at this layer self.__send__layer_notification(settings, current_layer) elif first_layers > 0 and 1 <",
"for tracking layer numbers to notify. Values are strings def add_layer(self, layer): \"\"\"",
"list of layers for which notifications will be sent \"\"\" self._layers.remove(layer) def layer_changed(self,",
"image = None try: hflip = settings.get([\"webcam_flipH\"]) vflip = settings.get([\"webcam_flipV\"]) rotate = settings.get([\"webcam_rotate90\"])",
"it individually since 'printerID' is included so that # iOS app can properly",
"add_layer(self, layer): \"\"\" Add a new layer to the list of layers for",
"\"\"\" self._layers.append(layer) def remove_layer(self, layer): \"\"\" Remove layer from list of layers for",
"send non-silent notifications (the new way) so notifications are rendered even if user",
"is the case when the same OctoPrint instance is added twice # on",
"camera_url and camera_url.strip(): image = self.image(camera_url, hflip, vflip, rotate) except: self._logger.info(\"Could not load",
"This is the case when the same OctoPrint instance is added twice #",
"rendered even if user # killed the app printer_name = token[\"printerName\"] language_code =",
"first_layers = settings.get_int(['notify_first_X_layers']) if current_layer in self._layers: # User specified they wanted to",
"int(current_layer) <= first_layers + 1: # Send a picture for first X layers",
"server has been defined so do nothing return -1 tokens = settings.get([\"tokens\"]) if",
"this layer self.__send__layer_notification(settings, current_layer) elif first_layers > 0 and 1 < int(current_layer) <=",
"on the iOS app. Usually one for local address and one for public",
"tokens that received a notification used_tokens.append(apns_token) if 'printerName' in token and token[\"printerName\"] is",
"0 and 1 < int(current_layer) <= first_layers + 1: # Send a picture",
"is included so that # iOS app can properly render local notification with",
"notifications will be sent \"\"\" self._layers.remove(layer) def layer_changed(self, settings, current_layer): first_layers = settings.get_int(['notify_first_X_layers'])",
"current_layer in self._layers: # User specified they wanted to get a notification when",
"a notification when print started printing at this layer self.__send__layer_notification(settings, current_layer) elif first_layers",
"ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts = ifttt_alerts self._alerts = Alerts(self._logger) self.reset_layers() def get_layers(self): \"\"\"",
"self._alerts = Alerts(self._logger) self.reset_layers() def get_layers(self): \"\"\" Returns list of layers for which",
"to notify. Values are strings def add_layer(self, layer): \"\"\" Add a new layer",
"from url\") # For each registered token we will send a push notification",
"so do nothing return -1 tokens = settings.get([\"tokens\"]) if len(tokens) == 0: #",
"from .base_notification import BaseNotification class LayerNotifications(BaseNotification): def __init__(self, logger, ifttt_alerts): BaseNotification.__init__(self, logger) self._ifttt_alerts",
"registered token we will send a push notification # We do it individually",
"(only send once layer was printed) self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self, settings, current_layer): #",
"snapshot of the camera image = None try: hflip = settings.get([\"webcam_flipH\"]) vflip =",
"tracking layer numbers to notify. Values are strings def add_layer(self, layer): \"\"\" Add",
"last_result = self._alerts.send_alert_code(settings, language_code, apns_token, url, printer_name, \"layer_changed\", None, image, current_layer) return last_result",
"send a push notification # We do it individually since 'printerID' is included",
"import Alerts from .base_notification import BaseNotification class LayerNotifications(BaseNotification): def __init__(self, logger, ifttt_alerts): BaseNotification.__init__(self,",
"= settings.get([\"tokens\"]) if len(tokens) == 0: # No iOS devices were registered so",
"<gh_stars>10-100 from .alerts import Alerts from .base_notification import BaseNotification class LayerNotifications(BaseNotification): def __init__(self,",
"camera_url.strip(): image = self.image(camera_url, hflip, vflip, rotate) except: self._logger.info(\"Could not load image from",
"== 0: # No iOS devices were registered so skip notification return -2",
"for which notifications will be sent \"\"\" return self._layers def reset_layers(self): \"\"\" Reset",
"remove_layer(self, layer): \"\"\" Remove layer from list of layers for which notifications will",
"received the notification # This is the case when the same OctoPrint instance",
"so notifications are rendered even if user # killed the app printer_name =",
"= token[\"languageCode\"] url = server_url + '/v1/push_printer' last_result = self._alerts.send_alert_code(settings, language_code, apns_token, url,",
"will be sent \"\"\" self._layers = [] # Variable used for tracking layer",
"send once layer was printed) self.__send__layer_notification(settings, current_layer) def __send__layer_notification(self, settings, current_layer): # Send",
"= settings.get([\"server_url\"]) if not server_url or not server_url.strip(): # No APNS server has",
"not server_url or not server_url.strip(): # No APNS server has been defined so",
"devices were registered so skip notification return -2 # Get a snapshot of",
"which notifications will be sent \"\"\" self._layers.append(layer) def remove_layer(self, layer): \"\"\" Remove layer",
"numbers to notify. Values are strings def add_layer(self, layer): \"\"\" Add a new",
"1 < int(current_layer) <= first_layers + 1: # Send a picture for first",
"We can send non-silent notifications (the new way) so notifications are rendered even"
] |
[
"api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token = token",
"('id', 'password', 'password2', 'access_token') extra_kwargs = { 'password': { 'write_only': True, 'min_length': 8,",
"write_only=True) class Meta: model = User fields = ('id', 'password', 'password2', 'access_token') extra_kwargs",
"validate(self, attrs): \"\"\" 校验数据 \"\"\" if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow =",
"serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn = get_redis_connection('verify_codes') mobile = attrs['mobile'] real_sms_code = redis_conn.get('sms_%s' %",
"'access_token') extra_kwargs = { 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages':",
"检查sms code \"\"\" sms_code = serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self, value): account = self.context['view'].kwargs['account']",
"= serializers.CharField(label='操作token', write_only=True) class Meta: model = User fields = ('id', 'password', 'password2',",
"serializers.CharField(label='确认密码', write_only=True) access_token = serializers.CharField(label='操作token', write_only=True) class Meta: model = User fields =",
"is None: raise serializers.ValidationError('用户不存在') self.user = user # 从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes') real_sms_code",
"attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return attrs def create(self, validated_data): \"\"\" 创建用户 \"\"\"",
"model = User fields = ('id', 'email') extra_kwargs = { 'email': { 'required':",
"import send_verify_email logger = logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\" password2 = serializers.CharField(label='确认密码',",
"raise serializers.ValidationError('无效的access token') return attrs def update(self, instance, validated_data): \"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password'])",
"raise serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn = get_redis_connection('verify_codes') mobile = attrs['mobile'] real_sms_code = redis_conn.get('sms_%s'",
"8, 'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } class",
"'password', '<PASSWORD>', 'sms_code', 'mobile', 'allow', 'token') extra_kwargs = { 'id': {'read_only': True}, #",
"!= real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return value class ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码', write_only=True) access_token",
"get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s' % user.mobile) if real_sms_code is None: return serializers.ValidationError('无效的短信验证码') if",
"= get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s' % user.mobile) if real_sms_code is None: return serializers.ValidationError('无效的短信验证码')",
"redis_conn.get('sms_%s' % user.mobile) if real_sms_code is None: return serializers.ValidationError('无效的短信验证码') if value != real_sms_code.decode():",
"required=True, allow_null=False, allow_blank=False, write_only=True) token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 def validate_mobile(self, value):",
"allow = serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False, write_only=True) token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段",
"class ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码', write_only=True) access_token = serializers.CharField(label='操作token', write_only=True) class Meta: model",
"class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\" password2 = serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True) sms_code",
"\"\"\" # 移除数据库模型中不存在的属性 del validated_data['password2'] del validated_data['sms_code'] del validated_data['allow'] user = super().create(validated_data) #",
"'username': { 'min_length': 5, 'max_length': 20, 'error_messages': { 'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', }",
"'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } def validate(self,",
"'password', 'password2', 'access_token') extra_kwargs = { 'password': { 'write_only': True, 'min_length': 8, 'max_length':",
"allow_blank=False, write_only=True) sms_code = serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False, write_only=True) allow = serializers.CharField(label='同意协议', required=True,",
"instance.email = email instance.save() # 生成验证链接 verify_url = instance.generate_verify_email_url() # 发送验证邮件 send_verify_email.delay(email, verify_url)",
"validated_data): \"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save() return instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\"",
"model = User fields = ['id', 'username', 'mobile', 'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer): class",
"is None: return serializers.ValidationError('无效的短信验证码') if value != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return value class",
"class Meta: model = User fields = ['id', 'username', 'mobile', 'email', 'email_active'] class",
"user is None: raise serializers.ValidationError('用户不存在') self.user = user # 从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes')",
"email = validated_data['email'] instance.email = email instance.save() # 生成验证链接 verify_url = instance.generate_verify_email_url() #",
"user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user)",
"{ 'min_length': 5, 'max_length': 20, 'error_messages': { 'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', } },",
"创建用户 \"\"\" # 移除数据库模型中不存在的属性 del validated_data['password2'] del validated_data['sms_code'] del validated_data['allow'] user = super().create(validated_data)",
"fields = ('id', 'email') extra_kwargs = { 'email': { 'required': True } }",
"logger = logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\" password2 = serializers.CharField(label='确认密码', required=True, allow_null=False,",
"= serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True) sms_code = serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False, write_only=True)",
"validate_sms_code(self, value): account = self.context['view'].kwargs['account'] # 获取user user = get_user_by_account(account) if user is",
"20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } def validate(self, attrs):",
"real_sms_code = redis_conn.get('sms_%s' % mobile) if real_sms_code is None: raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code']",
"# 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id', 'username', 'password', '<PASSWORD>', 'sms_code', 'mobile', 'allow', 'token') extra_kwargs",
"'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', }",
"real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return attrs def create(self, validated_data): \"\"\" 创建用户 \"\"\" # 移除数据库模型中不存在的属性",
"'min_length': 5, 'max_length': 20, 'error_messages': { 'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', } }, 'password':",
"token return user class Meta: model = User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id',",
"= redis_conn.get('sms_%s' % user.mobile) if real_sms_code is None: return serializers.ValidationError('无效的短信验证码') if value !=",
"value): \"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误') return value def validate_allow(self, value):",
"}, 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码',",
"import re from .models import User from .utils import get_user_by_account from celery_tasks.email.tasks import",
"{ 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code",
"return value def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if value != 'true': raise serializers.ValidationError('请同意用户协议') return",
"allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not allow: raise serializers.ValidationError('无效的access token') return attrs def",
"serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False, write_only=True) allow = serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False, write_only=True) token",
"extra_kwargs = { 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages': {",
"创建用户序列化器 \"\"\" password2 = serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True) sms_code = serializers.CharField(label='短信验证码', required=True,",
"serializers.ValidationError('请同意用户协议') return value def validate(self, attrs): # 判断两次密码 if attrs['password'] != attrs['password2']: raise",
"del validated_data['allow'] user = super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token jwt_payload_handler =",
"def update(self, instance, validated_data): \"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save() return instance class UserDetailSerializer(serializers.ModelSerializer):",
"write_only=True) access_token = serializers.CharField(label='操作token', write_only=True) class Meta: model = User fields = ('id',",
"mobile = attrs['mobile'] real_sms_code = redis_conn.get('sms_%s' % mobile) if real_sms_code is None: raise",
"'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email')",
"real_sms_code is None: return serializers.ValidationError('无效的短信验证码') if value != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return value",
"= jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token = token return user class Meta: model",
"logging import re from .models import User from .utils import get_user_by_account from celery_tasks.email.tasks",
"extra_kwargs = { 'email': { 'required': True } } def update(self, instance, validated_data):",
"del validated_data['sms_code'] del validated_data['allow'] user = super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token",
"max_length=6) def validate_sms_code(self, value): account = self.context['view'].kwargs['account'] # 获取user user = get_user_by_account(account) if",
"required=True, allow_null=False, allow_blank=False, write_only=True) allow = serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False, write_only=True) token =",
"raise serializers.ValidationError('请同意用户协议') return value def validate(self, attrs): # 判断两次密码 if attrs['password'] != attrs['password2']:",
"'email': { 'required': True } } def update(self, instance, validated_data): email = validated_data['email']",
"if attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return attrs def create(self, validated_data): \"\"\" 创建用户",
"token = jwt_encode_handler(payload) user.token = token return user class Meta: model = User",
"sms_code = serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False, write_only=True) allow = serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False,",
"from rest_framework_jwt.settings import api_settings import logging import re from .models import User from",
"User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not allow: raise serializers.ValidationError('无效的access token') return attrs def update(self, instance,",
"write_only=True) token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 def validate_mobile(self, value): \"\"\"验证手机号\"\"\" if not",
"get_user_by_account(account) if user is None: raise serializers.ValidationError('用户不存在') self.user = user # 从redis中取出真实的验证码 redis_conn",
"value): raise serializers.ValidationError('手机号格式错误') return value def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if value != 'true':",
"\"\"\" 用户详细信息序列化器 \"\"\" class Meta: model = User fields = ['id', 'username', 'mobile',",
"user = get_user_by_account(account) if user is None: raise serializers.ValidationError('用户不存在') self.user = user #",
"None: return serializers.ValidationError('无效的短信验证码') if value != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return value class ResetPasswordSerializer(serializers.ModelSerializer):",
"allow_null=False, allow_blank=False, write_only=True) allow = serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False, write_only=True) token = serializers.CharField(label='登录状态token',",
"value def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if value != 'true': raise serializers.ValidationError('请同意用户协议') return value",
"serializers.ValidationError('无效的短信验证码') if value != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return value class ResetPasswordSerializer(serializers.ModelSerializer): password2 =",
"8, 'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } def",
"validated_data): \"\"\" 创建用户 \"\"\" # 移除数据库模型中不存在的属性 del validated_data['password2'] del validated_data['sms_code'] del validated_data['allow'] user",
"\"\"\"检验用户是否同意协议\"\"\" if value != 'true': raise serializers.ValidationError('请同意用户协议') return value def validate(self, attrs): #",
"validated_data['password2'] del validated_data['sms_code'] del validated_data['allow'] user = super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() #",
"= { 'email': { 'required': True } } def update(self, instance, validated_data): email",
"instance.save() return instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\" class Meta: model = User",
"class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\" class Meta: model = User fields = ['id',",
"EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email') extra_kwargs = {",
"class EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email') extra_kwargs =",
"if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn = get_redis_connection('verify_codes') mobile =",
"serializers.CharField(label='操作token', write_only=True) class Meta: model = User fields = ('id', 'password', 'password2', 'access_token')",
"attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn = get_redis_connection('verify_codes') mobile = attrs['mobile']",
"instance, validated_data): email = validated_data['email'] instance.email = email instance.save() # 生成验证链接 verify_url =",
".models import User from .utils import get_user_by_account from celery_tasks.email.tasks import send_verify_email logger =",
"value): account = self.context['view'].kwargs['account'] # 获取user user = get_user_by_account(account) if user is None:",
"class Meta: model = User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id', 'username', 'password', '<PASSWORD>',",
"value != 'true': raise serializers.ValidationError('请同意用户协议') return value def validate(self, attrs): # 判断两次密码 if",
"} class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code \"\"\" sms_code = serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self,",
"= user # 从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s' % user.mobile) if",
"instance.set_password(validated_data['password']) instance.save() return instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\" class Meta: model =",
"20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } class CheckSMSCodeSerializer(serializers.Serializer): \"\"\"",
"} } } def validate(self, attrs): \"\"\" 校验数据 \"\"\" if attrs['password'] != attrs['password2']:",
"'password': { 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length':",
"\"\"\" 创建用户序列化器 \"\"\" password2 = serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True) sms_code = serializers.CharField(label='短信验证码',",
"redis_conn = get_redis_connection('verify_codes') mobile = attrs['mobile'] real_sms_code = redis_conn.get('sms_%s' % mobile) if real_sms_code",
"\"\"\" password2 = serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True) sms_code = serializers.CharField(label='短信验证码', required=True, allow_null=False,",
"= User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id', 'username', 'password', '<PASSWORD>', 'sms_code', 'mobile', 'allow',",
"Meta: model = User fields = ('id', 'password', 'password2', 'access_token') extra_kwargs = {",
"Meta: model = User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id', 'username', 'password', '<PASSWORD>', 'sms_code',",
"\"\"\" if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not",
"attrs['mobile'] real_sms_code = redis_conn.get('sms_%s' % mobile) if real_sms_code is None: raise serializers.ValidationError('无效的短信验证码') if",
"{ 'id': {'read_only': True}, # read_only为True,指明只有输出时才会用到 'username': { 'min_length': 5, 'max_length': 20, 'error_messages':",
"True } } def update(self, instance, validated_data): email = validated_data['email'] instance.email = email",
"real_sms_code = redis_conn.get('sms_%s' % user.mobile) if real_sms_code is None: return serializers.ValidationError('无效的短信验证码') if value",
"'password2', 'access_token') extra_kwargs = { 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20,",
"= redis_conn.get('sms_%s' % mobile) if real_sms_code is None: raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] !=",
"serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self, value): account = self.context['view'].kwargs['account'] # 获取user user = get_user_by_account(account)",
"serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return attrs def create(self, validated_data): \"\"\"",
"= ['id', 'username', 'mobile', 'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer): class Meta: model = User",
"real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return value class ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码', write_only=True) access_token =",
"# 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload",
"code \"\"\" sms_code = serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self, value): account = self.context['view'].kwargs['account'] #",
"= self.context['view'].kwargs['account'] # 获取user user = get_user_by_account(account) if user is None: raise serializers.ValidationError('用户不存在')",
"return serializers.ValidationError('无效的短信验证码') if value != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return value class ResetPasswordSerializer(serializers.ModelSerializer): password2",
"\"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save() return instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\" class",
"allow_null=False, allow_blank=False, write_only=True) token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 def validate_mobile(self, value): \"\"\"验证手机号\"\"\"",
"validate_mobile(self, value): \"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误') return value def validate_allow(self,",
"api_settings import logging import re from .models import User from .utils import get_user_by_account",
"'id': {'read_only': True}, # read_only为True,指明只有输出时才会用到 'username': { 'min_length': 5, 'max_length': 20, 'error_messages': {",
"= User fields = ('id', 'password', 'password2', 'access_token') extra_kwargs = { 'password': {",
"User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id', 'username', 'password', '<PASSWORD>', 'sms_code', 'mobile', 'allow', 'token')",
"serializers.ValidationError('短信验证码错误') return value class ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码', write_only=True) access_token = serializers.CharField(label='操作token', write_only=True)",
"ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码', write_only=True) access_token = serializers.CharField(label='操作token', write_only=True) class Meta: model =",
"'required': True } } def update(self, instance, validated_data): email = validated_data['email'] instance.email =",
"serializers.ValidationError('无效的access token') return attrs def update(self, instance, validated_data): \"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save()",
"校验数据 \"\"\" if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if",
"User from .utils import get_user_by_account from celery_tasks.email.tasks import send_verify_email logger = logging.getLogger('django') class",
"= serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 def validate_mobile(self, value): \"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$', value):",
"password2 = serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True) sms_code = serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False,",
"此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id', 'username', 'password', '<PASSWORD>', 'sms_code', 'mobile', 'allow', 'token') extra_kwargs =",
"write_only=True) allow = serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False, write_only=True) token = serializers.CharField(label='登录状态token', read_only=True) #",
"= super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler =",
"not allow: raise serializers.ValidationError('无效的access token') return attrs def update(self, instance, validated_data): \"\"\" 更新密码",
"validated_data['sms_code'] del validated_data['allow'] user = super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token jwt_payload_handler",
"raise serializers.ValidationError('用户不存在') self.user = user # 从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s'",
"self.user = user # 从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s' % user.mobile)",
"import api_settings import logging import re from .models import User from .utils import",
"% mobile) if real_sms_code is None: raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] != real_sms_code.decode(): raise",
"'max_length': '仅允许8-20个字符的密码', } } } class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code \"\"\" sms_code =",
"def validate_mobile(self, value): \"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误') return value def",
"\"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误') return value def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\"",
"'email_active'] class EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email') extra_kwargs",
"= get_user_by_account(account) if user is None: raise serializers.ValidationError('用户不存在') self.user = user # 从redis中取出真实的验证码",
"!= attrs['password2']: raise serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn = get_redis_connection('verify_codes') mobile = attrs['mobile'] real_sms_code",
"= serializers.CharField(label='确认密码', write_only=True) access_token = serializers.CharField(label='操作token', write_only=True) class Meta: model = User fields",
"allow: raise serializers.ValidationError('无效的access token') return attrs def update(self, instance, validated_data): \"\"\" 更新密码 \"\"\"",
"# read_only为True,指明只有输出时才会用到 'username': { 'min_length': 5, 'max_length': 20, 'error_messages': { 'min_length': '仅允许5-20个字符的用户名', 'max_length':",
"token') return attrs def update(self, instance, validated_data): \"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save() return",
"'max_length': '仅允许8-20个字符的密码', } } } def validate(self, attrs): \"\"\" 校验数据 \"\"\" if attrs['password']",
"= validated_data['email'] instance.email = email instance.save() # 生成验证链接 verify_url = instance.generate_verify_email_url() # 发送验证邮件",
"CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code \"\"\" sms_code = serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self, value): account",
"write_only=True) sms_code = serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False, write_only=True) allow = serializers.CharField(label='同意协议', required=True, allow_null=False,",
"return attrs def create(self, validated_data): \"\"\" 创建用户 \"\"\" # 移除数据库模型中不存在的属性 del validated_data['password2'] del",
"('id', 'username', 'password', '<PASSWORD>', 'sms_code', 'mobile', 'allow', 'token') extra_kwargs = { 'id': {'read_only':",
"用户详细信息序列化器 \"\"\" class Meta: model = User fields = ['id', 'username', 'mobile', 'email',",
"\"\"\" 校验数据 \"\"\" if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token'])",
"from rest_framework import serializers, status from django_redis import get_redis_connection from rest_framework_jwt.settings import api_settings",
"import User from .utils import get_user_by_account from celery_tasks.email.tasks import send_verify_email logger = logging.getLogger('django')",
"\"\"\" 创建用户 \"\"\" # 移除数据库模型中不存在的属性 del validated_data['password2'] del validated_data['sms_code'] del validated_data['allow'] user =",
"调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload =",
"= get_redis_connection('verify_codes') mobile = attrs['mobile'] real_sms_code = redis_conn.get('sms_%s' % mobile) if real_sms_code is",
"from django_redis import get_redis_connection from rest_framework_jwt.settings import api_settings import logging import re from",
"rest_framework_jwt.settings import api_settings import logging import re from .models import User from .utils",
"import logging import re from .models import User from .utils import get_user_by_account from",
"import serializers, status from django_redis import get_redis_connection from rest_framework_jwt.settings import api_settings import logging",
"email instance.save() # 生成验证链接 verify_url = instance.generate_verify_email_url() # 发送验证邮件 send_verify_email.delay(email, verify_url) return instance",
"'mobile', 'allow', 'token') extra_kwargs = { 'id': {'read_only': True}, # read_only为True,指明只有输出时才会用到 'username': {",
"('id', 'email') extra_kwargs = { 'email': { 'required': True } } def update(self,",
"attrs def create(self, validated_data): \"\"\" 创建用户 \"\"\" # 移除数据库模型中不存在的属性 del validated_data['password2'] del validated_data['sms_code']",
"= serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False, write_only=True) allow = serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False, write_only=True)",
"instance, validated_data): \"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save() return instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器",
"'username', 'password', '<PASSWORD>', 'sms_code', 'mobile', 'allow', 'token') extra_kwargs = { 'id': {'read_only': True},",
"user.mobile) if real_sms_code is None: return serializers.ValidationError('无效的短信验证码') if value != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误')",
"django_redis import get_redis_connection from rest_framework_jwt.settings import api_settings import logging import re from .models",
"'max_length': 20, 'error_messages': { 'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', } }, 'password': { 'write_only':",
"def update(self, instance, validated_data): email = validated_data['email'] instance.email = email instance.save() # 生成验证链接",
"model = User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id', 'username', 'password', '<PASSWORD>', 'sms_code', 'mobile',",
"update(self, instance, validated_data): email = validated_data['email'] instance.email = email instance.save() # 生成验证链接 verify_url",
"attrs def update(self, instance, validated_data): \"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save() return instance class",
"update(self, instance, validated_data): \"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save() return instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\"",
"'allow', 'token') extra_kwargs = { 'id': {'read_only': True}, # read_only为True,指明只有输出时才会用到 'username': { 'min_length':",
"return value class ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码', write_only=True) access_token = serializers.CharField(label='操作token', write_only=True) class",
"= logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\" password2 = serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False,",
"raise serializers.ValidationError('手机号格式错误') return value def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if value != 'true': raise",
"from celery_tasks.email.tasks import send_verify_email logger = logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\" password2",
"password2 = serializers.CharField(label='确认密码', write_only=True) access_token = serializers.CharField(label='操作token', write_only=True) class Meta: model = User",
"User fields = ('id', 'password', 'password2', 'access_token') extra_kwargs = { 'password': { 'write_only':",
"UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\" class Meta: model = User fields = ['id', 'username',",
"= ('id', 'password', 'password2', 'access_token') extra_kwargs = { 'password': { 'write_only': True, 'min_length':",
"'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms",
"'error_messages': { 'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', } }, 'password': { 'write_only': True, 'min_length':",
"= api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token =",
"'min_length': 8, 'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } }",
"'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code \"\"\"",
"# 增加token字段 def validate_mobile(self, value): \"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误') return",
"return value def validate(self, attrs): # 判断两次密码 if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致')",
"'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } def validate(self, attrs): \"\"\"",
"= jwt_encode_handler(payload) user.token = token return user class Meta: model = User #",
"validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if value != 'true': raise serializers.ValidationError('请同意用户协议') return value def validate(self,",
"} } } class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code \"\"\" sms_code = serializers.CharField(min_length=6, max_length=6)",
"{ 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码',",
"api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token = token return user class",
"'仅允许5-20个字符的用户名', } }, 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages': {",
"# 从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s' % user.mobile) if real_sms_code is",
"'<PASSWORD>', 'sms_code', 'mobile', 'allow', 'token') extra_kwargs = { 'id': {'read_only': True}, # read_only为True,指明只有输出时才会用到",
"attrs['password2']: raise serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn = get_redis_connection('verify_codes') mobile = attrs['mobile'] real_sms_code =",
"if value != 'true': raise serializers.ValidationError('请同意用户协议') return value def validate(self, attrs): # 判断两次密码",
"if user is None: raise serializers.ValidationError('用户不存在') self.user = user # 从redis中取出真实的验证码 redis_conn =",
"serializers.ValidationError('短信验证码错误') return attrs def create(self, validated_data): \"\"\" 创建用户 \"\"\" # 移除数据库模型中不存在的属性 del validated_data['password2']",
".utils import get_user_by_account from celery_tasks.email.tasks import send_verify_email logger = logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\"",
"allow_blank=False, write_only=True) allow = serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False, write_only=True) token = serializers.CharField(label='登录状态token', read_only=True)",
"payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token = token return user class Meta:",
"value def validate(self, attrs): # 判断两次密码 if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') #",
"'仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code \"\"\" sms_code",
"'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } def validate(self, attrs): \"\"\" 校验数据 \"\"\"",
"redis_conn.get('sms_%s' % mobile) if real_sms_code is None: raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] != real_sms_code.decode():",
"'仅允许8-20个字符的密码', } } } class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code \"\"\" sms_code = serializers.CharField(min_length=6,",
"def validate(self, attrs): \"\"\" 校验数据 \"\"\" if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow",
"extra_kwargs = { 'id': {'read_only': True}, # read_only为True,指明只有输出时才会用到 'username': { 'min_length': 5, 'max_length':",
"True, 'min_length': 8, 'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } }",
"import get_user_by_account from celery_tasks.email.tasks import send_verify_email logger = logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器",
"'仅允许8-20个字符的密码', } } } def validate(self, attrs): \"\"\" 校验数据 \"\"\" if attrs['password'] !=",
"'sms_code', 'mobile', 'allow', 'token') extra_kwargs = { 'id': {'read_only': True}, # read_only为True,指明只有输出时才会用到 'username':",
"raise serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not allow: raise serializers.ValidationError('无效的access token') return",
"redis_conn = get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s' % user.mobile) if real_sms_code is None: return",
"not re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误') return value def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if value",
"# 判断短信验证码 redis_conn = get_redis_connection('verify_codes') mobile = attrs['mobile'] real_sms_code = redis_conn.get('sms_%s' % mobile)",
"Meta: model = User fields = ('id', 'email') extra_kwargs = { 'email': {",
"serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True) sms_code = serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False, write_only=True) allow",
"instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\" class Meta: model = User fields =",
"从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s' % user.mobile) if real_sms_code is None:",
"serializers.ValidationError('手机号格式错误') return value def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if value != 'true': raise serializers.ValidationError('请同意用户协议')",
"allow_null=False, allow_blank=False, write_only=True) sms_code = serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False, write_only=True) allow = serializers.CharField(label='同意协议',",
"= { 'id': {'read_only': True}, # read_only为True,指明只有输出时才会用到 'username': { 'min_length': 5, 'max_length': 20,",
"class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code \"\"\" sms_code = serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self, value):",
"raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return attrs def create(self, validated_data):",
"def validate(self, attrs): # 判断两次密码 if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') # 判断短信验证码",
"model = User fields = ('id', 'password', 'password2', 'access_token') extra_kwargs = { 'password':",
"增加token字段 def validate_mobile(self, value): \"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误') return value",
"{ 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } def validate(self, attrs): \"\"\" 校验数据",
"fields = ['id', 'username', 'mobile', 'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer): class Meta: model =",
"user class Meta: model = User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id', 'username', 'password',",
"# 判断两次密码 if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn = get_redis_connection('verify_codes')",
"= User fields = ('id', 'email') extra_kwargs = { 'email': { 'required': True",
"\"\"\" class Meta: model = User fields = ['id', 'username', 'mobile', 'email', 'email_active']",
"!= real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return attrs def create(self, validated_data): \"\"\" 创建用户 \"\"\" #",
"jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token = token return",
"fields = ('id', 'username', 'password', '<PASSWORD>', 'sms_code', 'mobile', 'allow', 'token') extra_kwargs = {",
"20, 'error_messages': { 'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', } }, 'password': { 'write_only': True,",
"is None: raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return attrs def",
"{ 'required': True } } def update(self, instance, validated_data): email = validated_data['email'] instance.email",
"sms_code = serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self, value): account = self.context['view'].kwargs['account'] # 获取user user",
"account = self.context['view'].kwargs['account'] # 获取user user = get_user_by_account(account) if user is None: raise",
"read_only为True,指明只有输出时才会用到 'username': { 'min_length': 5, 'max_length': 20, 'error_messages': { 'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名',",
"= ('id', 'username', 'password', '<PASSWORD>', 'sms_code', 'mobile', 'allow', 'token') extra_kwargs = { 'id':",
"raise serializers.ValidationError('短信验证码错误') return attrs def create(self, validated_data): \"\"\" 创建用户 \"\"\" # 移除数据库模型中不存在的属性 del",
"} }, 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages': { 'min_length':",
"'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', } }, 'password': { 'write_only': True, 'min_length': 8, 'max_length':",
"# 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token =",
"!= 'true': raise serializers.ValidationError('请同意用户协议') return value def validate(self, attrs): # 判断两次密码 if attrs['password']",
"attrs['access_token']) if not allow: raise serializers.ValidationError('无效的access token') return attrs def update(self, instance, validated_data):",
"= ('id', 'email') extra_kwargs = { 'email': { 'required': True } } def",
"send_verify_email logger = logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\" password2 = serializers.CharField(label='确认密码', required=True,",
"status from django_redis import get_redis_connection from rest_framework_jwt.settings import api_settings import logging import re",
"= serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False, write_only=True) token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 def",
"'true': raise serializers.ValidationError('请同意用户协议') return value def validate(self, attrs): # 判断两次密码 if attrs['password'] !=",
"logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\" password2 = serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True)",
"= token return user class Meta: model = User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields =",
"attrs): # 判断两次密码 if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn =",
"} } class CheckSMSCodeSerializer(serializers.Serializer): \"\"\" 检查sms code \"\"\" sms_code = serializers.CharField(min_length=6, max_length=6) def",
"if not allow: raise serializers.ValidationError('无效的access token') return attrs def update(self, instance, validated_data): \"\"\"",
"if real_sms_code is None: raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return",
"获取user user = get_user_by_account(account) if user is None: raise serializers.ValidationError('用户不存在') self.user = user",
"CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\" password2 = serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True) sms_code =",
"if not re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误') return value def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if",
"} } def validate(self, attrs): \"\"\" 校验数据 \"\"\" if attrs['password'] != attrs['password2']: raise",
"rest_framework import serializers, status from django_redis import get_redis_connection from rest_framework_jwt.settings import api_settings import",
"None: raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return attrs def create(self,",
"serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not allow: raise serializers.ValidationError('无效的access token') return attrs",
"return user class Meta: model = User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields = ('id', 'username',",
"get_redis_connection from rest_framework_jwt.settings import api_settings import logging import re from .models import User",
"serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 def validate_mobile(self, value): \"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$', value): raise",
"validated_data['email'] instance.email = email instance.save() # 生成验证链接 verify_url = instance.generate_verify_email_url() # 发送验证邮件 send_verify_email.delay(email,",
"jwt_encode_handler(payload) user.token = token return user class Meta: model = User # 此序列化器用于传入和输出,所以得包含所有要用到的字段",
"return instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\" class Meta: model = User fields",
"\"\"\" 检查sms code \"\"\" sms_code = serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self, value): account =",
"= User fields = ['id', 'username', 'mobile', 'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer): class Meta:",
"= { 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages': { 'min_length':",
"real_sms_code is None: raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return attrs",
"validated_data): email = validated_data['email'] instance.email = email instance.save() # 生成验证链接 verify_url = instance.generate_verify_email_url()",
"value != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return value class ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码', write_only=True)",
"# 移除数据库模型中不存在的属性 del validated_data['password2'] del validated_data['sms_code'] del validated_data['allow'] user = super().create(validated_data) # 调用django的认证系统加密密码",
"if real_sms_code is None: return serializers.ValidationError('无效的短信验证码') if value != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return",
"get_user_by_account from celery_tasks.email.tasks import send_verify_email logger = logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\"",
"celery_tasks.email.tasks import send_verify_email logger = logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer): \"\"\" 创建用户序列化器 \"\"\" password2 =",
"raise serializers.ValidationError('短信验证码错误') return value class ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码', write_only=True) access_token = serializers.CharField(label='操作token',",
"'仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', } }, 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20,",
"if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not allow:",
"access_token = serializers.CharField(label='操作token', write_only=True) class Meta: model = User fields = ('id', 'password',",
"['id', 'username', 'mobile', 'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields",
"= api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token = token return user",
"{ 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码',",
"{ 'email': { 'required': True } } def update(self, instance, validated_data): email =",
"mobile) if real_sms_code is None: raise serializers.ValidationError('无效的短信验证码') if attrs['sms_code'] != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误')",
"判断短信验证码 redis_conn = get_redis_connection('verify_codes') mobile = attrs['mobile'] real_sms_code = redis_conn.get('sms_%s' % mobile) if",
"if value != real_sms_code.decode(): raise serializers.ValidationError('短信验证码错误') return value class ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码',",
"= User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not allow: raise serializers.ValidationError('无效的access token') return attrs def update(self,",
"class Meta: model = User fields = ('id', 'email') extra_kwargs = { 'email':",
"validate(self, attrs): # 判断两次密码 if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn",
"'max_length': 20, 'error_messages': { 'min_length': '仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } class CheckSMSCodeSerializer(serializers.Serializer):",
"super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER",
"判断两次密码 if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') # 判断短信验证码 redis_conn = get_redis_connection('verify_codes') mobile",
"'email') extra_kwargs = { 'email': { 'required': True } } def update(self, instance,",
"class Meta: model = User fields = ('id', 'password', 'password2', 'access_token') extra_kwargs =",
"user.save() # 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token",
"allow_blank=False, write_only=True) token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 def validate_mobile(self, value): \"\"\"验证手机号\"\"\" if",
"user = super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler",
"% user.mobile) if real_sms_code is None: return serializers.ValidationError('无效的短信验证码') if value != real_sms_code.decode(): raise",
"'max_length': '仅允许5-20个字符的用户名', } }, 'password': { 'write_only': True, 'min_length': 8, 'max_length': 20, 'error_messages':",
"validated_data['allow'] user = super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER",
"user # 从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s' % user.mobile) if real_sms_code",
"User fields = ('id', 'email') extra_kwargs = { 'email': { 'required': True }",
"def create(self, validated_data): \"\"\" 创建用户 \"\"\" # 移除数据库模型中不存在的属性 del validated_data['password2'] del validated_data['sms_code'] del",
"attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not allow: raise serializers.ValidationError('无效的access token')",
"= attrs['mobile'] real_sms_code = redis_conn.get('sms_%s' % mobile) if real_sms_code is None: raise serializers.ValidationError('无效的短信验证码')",
"serializers, status from django_redis import get_redis_connection from rest_framework_jwt.settings import api_settings import logging import",
"attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not allow: raise",
"from .models import User from .utils import get_user_by_account from celery_tasks.email.tasks import send_verify_email logger",
"jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token = token return user class Meta: model =",
"移除数据库模型中不存在的属性 del validated_data['password2'] del validated_data['sms_code'] del validated_data['allow'] user = super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password'])",
"fields = ('id', 'password', 'password2', 'access_token') extra_kwargs = { 'password': { 'write_only': True,",
"} def update(self, instance, validated_data): email = validated_data['email'] instance.email = email instance.save() #",
"True}, # read_only为True,指明只有输出时才会用到 'username': { 'min_length': 5, 'max_length': 20, 'error_messages': { 'min_length': '仅允许5-20个字符的用户名',",
"re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误') return value def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if value !=",
"{'read_only': True}, # read_only为True,指明只有输出时才会用到 'username': { 'min_length': 5, 'max_length': 20, 'error_messages': { 'min_length':",
"jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token",
"None: raise serializers.ValidationError('用户不存在') self.user = user # 从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes') real_sms_code =",
"value): \"\"\"检验用户是否同意协议\"\"\" if value != 'true': raise serializers.ValidationError('请同意用户协议') return value def validate(self, attrs):",
"read_only=True) # 增加token字段 def validate_mobile(self, value): \"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$', value): raise serializers.ValidationError('手机号格式错误')",
"def validate_sms_code(self, value): account = self.context['view'].kwargs['account'] # 获取user user = get_user_by_account(account) if user",
"serializers.CharField(label='同意协议', required=True, allow_null=False, allow_blank=False, write_only=True) token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 def validate_mobile(self,",
"= serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self, value): account = self.context['view'].kwargs['account'] # 获取user user =",
"'仅允许8-20个字符的密码', 'max_length': '仅允许8-20个字符的密码', } } } def validate(self, attrs): \"\"\" 校验数据 \"\"\" if",
"} def validate(self, attrs): \"\"\" 校验数据 \"\"\" if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致')",
"return attrs def update(self, instance, validated_data): \"\"\" 更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save() return instance",
"补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload)",
"User fields = ['id', 'username', 'mobile', 'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer): class Meta: model",
"import get_redis_connection from rest_framework_jwt.settings import api_settings import logging import re from .models import",
"Meta: model = User fields = ['id', 'username', 'mobile', 'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer):",
"\"\"\" sms_code = serializers.CharField(min_length=6, max_length=6) def validate_sms_code(self, value): account = self.context['view'].kwargs['account'] # 获取user",
"'mobile', 'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id',",
"from .utils import get_user_by_account from celery_tasks.email.tasks import send_verify_email logger = logging.getLogger('django') class CreateUserSerializer(serializers.ModelSerializer):",
"# 获取user user = get_user_by_account(account) if user is None: raise serializers.ValidationError('用户不存在') self.user =",
"value class ResetPasswordSerializer(serializers.ModelSerializer): password2 = serializers.CharField(label='确认密码', write_only=True) access_token = serializers.CharField(label='操作token', write_only=True) class Meta:",
"} } def update(self, instance, validated_data): email = validated_data['email'] instance.email = email instance.save()",
"attrs): \"\"\" 校验数据 \"\"\" if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'],",
"create(self, validated_data): \"\"\" 创建用户 \"\"\" # 移除数据库模型中不存在的属性 del validated_data['password2'] del validated_data['sms_code'] del validated_data['allow']",
"re from .models import User from .utils import get_user_by_account from celery_tasks.email.tasks import send_verify_email",
"self.context['view'].kwargs['account'] # 获取user user = get_user_by_account(account) if user is None: raise serializers.ValidationError('用户不存在') self.user",
"user.token = token return user class Meta: model = User # 此序列化器用于传入和输出,所以得包含所有要用到的字段 fields",
"\"\"\" instance.set_password(validated_data['password']) instance.save() return instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\" class Meta: model",
"def validate_allow(self, value): \"\"\"检验用户是否同意协议\"\"\" if value != 'true': raise serializers.ValidationError('请同意用户协议') return value def",
"'username', 'mobile', 'email', 'email_active'] class EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields =",
"{ 'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', } }, 'password': { 'write_only': True, 'min_length': 8,",
"get_redis_connection('verify_codes') mobile = attrs['mobile'] real_sms_code = redis_conn.get('sms_%s' % mobile) if real_sms_code is None:",
"= email instance.save() # 生成验证链接 verify_url = instance.generate_verify_email_url() # 发送验证邮件 send_verify_email.delay(email, verify_url) return",
"更新密码 \"\"\" instance.set_password(validated_data['password']) instance.save() return instance class UserDetailSerializer(serializers.ModelSerializer): \"\"\" 用户详细信息序列化器 \"\"\" class Meta:",
"required=True, allow_null=False, allow_blank=False, write_only=True) sms_code = serializers.CharField(label='短信验证码', required=True, allow_null=False, allow_blank=False, write_only=True) allow =",
"del validated_data['password2'] del validated_data['sms_code'] del validated_data['allow'] user = super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save()",
"serializers.ValidationError('用户不存在') self.user = user # 从redis中取出真实的验证码 redis_conn = get_redis_connection('verify_codes') real_sms_code = redis_conn.get('sms_%s' %",
"!= attrs['password2']: raise serializers.ValidationError('两次密码不一致') allow = User.check_set_password_token(self.context['view'].kwargs['pk'], attrs['access_token']) if not allow: raise serializers.ValidationError('无效的access",
"'token') extra_kwargs = { 'id': {'read_only': True}, # read_only为True,指明只有输出时才会用到 'username': { 'min_length': 5,",
"token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 def validate_mobile(self, value): \"\"\"验证手机号\"\"\" if not re.match(r'^1[3-9]\\d{9}$',",
"5, 'max_length': 20, 'error_messages': { 'min_length': '仅允许5-20个字符的用户名', 'max_length': '仅允许5-20个字符的用户名', } }, 'password': {"
] |
[
"app = Flask(__name__) app.config['SECRET_KEY'] = 'random string' app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\")",
"return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ == '__main__': app.run(host = '0.0.0.0', port =",
"import os from flask import Flask from MrLing import ling_blueprint from MrBasicWff import",
"app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if",
"wff_blueprint app = Flask(__name__) app.config['SECRET_KEY'] = 'random string' app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint)",
"import wff_blueprint app = Flask(__name__) app.config['SECRET_KEY'] = 'random string' app.debug = True app.register_blueprint(ling_blueprint)",
"from flask import Flask from MrLing import ling_blueprint from MrBasicWff import wff_blueprint app",
"home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ == '__main__': app.run(host = '0.0.0.0', port",
"app.config['SECRET_KEY'] = 'random string' app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def home(): return",
"MrLing import ling_blueprint from MrBasicWff import wff_blueprint app = Flask(__name__) app.config['SECRET_KEY'] = 'random",
"= 'random string' app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def home(): return '<p><a",
"import ling_blueprint from MrBasicWff import wff_blueprint app = Flask(__name__) app.config['SECRET_KEY'] = 'random string'",
"'<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ == '__main__': app.run(host = '0.0.0.0', port = int(os.getenv('PORT',",
"'random string' app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a",
"MrBasicWff import wff_blueprint app = Flask(__name__) app.config['SECRET_KEY'] = 'random string' app.debug = True",
"import Flask from MrLing import ling_blueprint from MrBasicWff import wff_blueprint app = Flask(__name__)",
"from MrLing import ling_blueprint from MrBasicWff import wff_blueprint app = Flask(__name__) app.config['SECRET_KEY'] =",
"= True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__",
"ling_blueprint from MrBasicWff import wff_blueprint app = Flask(__name__) app.config['SECRET_KEY'] = 'random string' app.debug",
"os from flask import Flask from MrLing import ling_blueprint from MrBasicWff import wff_blueprint",
"flask import Flask from MrLing import ling_blueprint from MrBasicWff import wff_blueprint app =",
"True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ ==",
"from MrBasicWff import wff_blueprint app = Flask(__name__) app.config['SECRET_KEY'] = 'random string' app.debug =",
"href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ == '__main__': app.run(host = '0.0.0.0', port = int(os.getenv('PORT', 5000)))",
"app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ == '__main__':",
"string' app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>'",
"app.register_blueprint(wff_blueprint) @app.route(\"/\") def home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ == '__main__': app.run(host",
"def home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ == '__main__': app.run(host = '0.0.0.0',",
"Flask from MrLing import ling_blueprint from MrBasicWff import wff_blueprint app = Flask(__name__) app.config['SECRET_KEY']",
"Flask(__name__) app.config['SECRET_KEY'] = 'random string' app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def home():",
"= Flask(__name__) app.config['SECRET_KEY'] = 'random string' app.debug = True app.register_blueprint(ling_blueprint) app.register_blueprint(wff_blueprint) @app.route(\"/\") def",
"@app.route(\"/\") def home(): return '<p><a href=\"/MrLing\">Ling</a></p><p><a href=\"/MrWff\">Wff</a></p>' if __name__ == '__main__': app.run(host ="
] |
[
"y = np.array([3, 4]) result = foo(x, y) assert((result[0] == x).all() and (result[1]",
"at http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx import numpy as np @Phylanx def foo(x,",
"(c) 2018 <NAME> # # Distributed under the Boost Software License, Version 1.0.",
"# Copyright (c) 2018 <NAME> # # Distributed under the Boost Software License,",
"Phylanx import numpy as np @Phylanx def foo(x, y): return [x, y] x",
"Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) from phylanx",
"LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx import numpy as np",
"@Phylanx def foo(x, y): return [x, y] x = np.array([1, 2]) y =",
"[x, y] x = np.array([1, 2]) y = np.array([3, 4]) result = foo(x,",
"2018 <NAME> # # Distributed under the Boost Software License, Version 1.0. (See",
"http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx import numpy as np @Phylanx def foo(x, y):",
"phylanx import Phylanx import numpy as np @Phylanx def foo(x, y): return [x,",
"def foo(x, y): return [x, y] x = np.array([1, 2]) y = np.array([3,",
"2]) y = np.array([3, 4]) result = foo(x, y) assert((result[0] == x).all() and",
"y] x = np.array([1, 2]) y = np.array([3, 4]) result = foo(x, y)",
"import numpy as np @Phylanx def foo(x, y): return [x, y] x =",
"numpy as np @Phylanx def foo(x, y): return [x, y] x = np.array([1,",
"the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy",
"y): return [x, y] x = np.array([1, 2]) y = np.array([3, 4]) result",
"copy at http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx import numpy as np @Phylanx def",
"np @Phylanx def foo(x, y): return [x, y] x = np.array([1, 2]) y",
"# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx import numpy",
"file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx import numpy as",
"(See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx",
"or copy at http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx import numpy as np @Phylanx",
"1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) from phylanx import",
"Copyright (c) 2018 <NAME> # # Distributed under the Boost Software License, Version",
"= np.array([1, 2]) y = np.array([3, 4]) result = foo(x, y) assert((result[0] ==",
"np.array([1, 2]) y = np.array([3, 4]) result = foo(x, y) assert((result[0] == x).all()",
"accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) from phylanx import Phylanx import",
"return [x, y] x = np.array([1, 2]) y = np.array([3, 4]) result =",
"Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt",
"Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at",
"from phylanx import Phylanx import numpy as np @Phylanx def foo(x, y): return",
"under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or",
"# Distributed under the Boost Software License, Version 1.0. (See accompanying # file",
"as np @Phylanx def foo(x, y): return [x, y] x = np.array([1, 2])",
"<NAME> # # Distributed under the Boost Software License, Version 1.0. (See accompanying",
"np.array([3, 4]) result = foo(x, y) assert((result[0] == x).all() and (result[1] == y).all())",
"License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) from",
"Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)",
"= np.array([3, 4]) result = foo(x, y) assert((result[0] == x).all() and (result[1] ==",
"# # Distributed under the Boost Software License, Version 1.0. (See accompanying #",
"x = np.array([1, 2]) y = np.array([3, 4]) result = foo(x, y) assert((result[0]",
"import Phylanx import numpy as np @Phylanx def foo(x, y): return [x, y]",
"foo(x, y): return [x, y] x = np.array([1, 2]) y = np.array([3, 4])"
] |
[
"raise metadata = { 'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender'] }",
"if not bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic(): return {'msg':'hello",
"validate_token(request) file = request.files['audio'] if request.method == 'POST' and token_data is not None",
"except Exception as e: return e def validate_json_payload(meta_keys, metadata): for key in meta_keys:",
"return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic(): return {'msg':'hello i am flask'}, 200 @app.route('/meta',",
"validate_token(request): try: bearer_token = request.headers['Authorization'] token_string = get_token(bearer_token) token_bytes = token_string.encode() payload =",
"signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' ) except Exception as e: return e def validate_json_payload(meta_keys, metadata):",
"'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender'] } file_path = os.path.join(directory, secure_filename(session_id + '.json'))",
"token_data is not None and file is not None: filename = request.form['filename'] foldername",
"} try: return jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' ) except Exception as e: return",
"jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy import jwt import datetime",
"Exception as e: return e def validate_json_payload(meta_keys, metadata): for key in meta_keys: if",
"directory = os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID'] if not os.path.exists(directory): try: os.makedirs(directory) except OSError",
"metadata['sessionID'] if not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno !=",
"with open(file_path, 'w') as fp: json.dump(metadata, fp) def get_token(bearer_token): PREFIX = 'Bearer '",
"as e: return e def validate_json_payload(meta_keys, metadata): for key in meta_keys: if key",
"and file is not None: filename = request.form['filename'] foldername = request.form['foldername'] directory =",
"meta(): metadata = request.json if request.method == 'PUT' and validate_json_payload(metadata, meta_keys): save_meta(metadata) token",
"request.method == 'PUT' and validate_json_payload(metadata, meta_keys): save_meta(metadata) token = encode_auth_token(metadata).decode() return {'token':token}, 200",
"datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try: return jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' ) except Exception as",
"import SQLAlchemy import jwt import datetime from flask_cors import CORS,cross_origin import os import",
"= encode_auth_token(metadata).decode() return {'token':token}, 200 else: return {'msg': 'Missing keys or wrong request",
"not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise",
"= os.path.join(directory, secure_filename(session_id + '.json')) with open(file_path, 'w') as fp: json.dump(metadata, fp) def",
"'request': metadata['nativeLanguage'], 'gender': metadata['gender'] } file_path = os.path.join(directory, secure_filename(session_id + '.json')) with open(file_path,",
"@app.route('/audio', methods=['POST']) def soundfile(): token_data = validate_token(request) file = request.files['audio'] if request.method ==",
"from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy import jwt import datetime from",
"request.json if request.method == 'PUT' and validate_json_payload(metadata, meta_keys): save_meta(metadata) token = encode_auth_token(metadata).decode() return",
"= request.headers['Authorization'] token_string = get_token(bearer_token) token_bytes = token_string.encode() payload = jwt.decode(token_bytes, app.config['SECRET_KEY']) return",
"meta_keys = ['gender', 'age', 'nativeLanguage', 'dateTime', 'sessionID'] def encode_auth_token(payload): signed_token = { 'exp':",
"try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise metadata =",
"wrong') return None @app.route('/audio', methods=['POST']) def soundfile(): token_data = validate_token(request) file = request.files['audio']",
"from flask_cors import CORS,cross_origin import os import json from werkzeug.utils import secure_filename from",
"app = Flask(__name__) if app.config['ENV'] == 'production': app.config['DEBUG'] = False app.config['SECRET_KEY'] = '<KEY>'",
"return e def validate_json_payload(meta_keys, metadata): for key in meta_keys: if key not in",
"app.config.get('SECRET_KEY'), algorithm='HS256' ) except Exception as e: return e def validate_json_payload(meta_keys, metadata): for",
"payload = jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload except: print('token validation went wrong') return None",
"OSError as e: if e.errno != errno.EEXIST: raise metadata = { 'uuid': metadata['sessionID'],",
"import Flask, request, redirect, url_for, Response, jsonify from flask_cors import CORS from flask_sqlalchemy",
"datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try: return jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256'",
"metadata: return False return True def save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID']",
"def save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID'] if not os.path.exists(directory): try: os.makedirs(directory)",
"request method'}, 403 def save_wav(directory, filename, file): if not os.path.exists(directory): try: os.makedirs(directory) except",
"request, redirect, url_for, Response, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy",
"'production': app.config['DEBUG'] = False app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database'",
"True def save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID'] if not os.path.exists(directory): try:",
"= get_token(bearer_token) token_bytes = token_string.encode() payload = jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload except: print('token",
"app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database' else: app.config['DEBUG'] = True",
"get_token(bearer_token): PREFIX = 'Bearer ' if not bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):] @app.route('/xyz',",
"+ '.wav')) file.save(file_path) def validate_token(request): try: bearer_token = request.headers['Authorization'] token_string = get_token(bearer_token) token_bytes",
"'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender'] } file_path = os.path.join(directory, secure_filename(session_id",
"os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise metadata",
"encode_auth_token(metadata).decode() return {'token':token}, 200 else: return {'msg': 'Missing keys or wrong request method'},",
"validate_json_payload(meta_keys, metadata): for key in meta_keys: if key not in metadata: return False",
"'/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database' else: app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD'] =",
"CORS(app, supports_credentials=True) meta_keys = ['gender', 'age', 'nativeLanguage', 'dateTime', 'sessionID'] def encode_auth_token(payload): signed_token =",
"os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise file_path = os.path.join(directory,",
"errno.EEXIST: raise file_path = os.path.join(directory, secure_filename(filename + '.wav')) file.save(file_path) def validate_token(request): try: bearer_token",
"token_bytes = token_string.encode() payload = jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload except: print('token validation went",
"meta_keys: if key not in metadata: return False return True def save_meta(metadata): directory",
"= '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys",
"i am flask'}, 200 @app.route('/meta', methods=['PUT']) def meta(): metadata = request.json if request.method",
"= ['gender', 'age', 'nativeLanguage', 'dateTime', 'sessionID'] def encode_auth_token(payload): signed_token = { 'exp': datetime.datetime.utcnow()",
"'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try: return jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' ) except Exception",
"if key not in metadata: return False return True def save_meta(metadata): directory =",
"in meta_keys: if key not in metadata: return False return True def save_meta(metadata):",
"403 def save_wav(directory, filename, file): if not os.path.exists(directory): try: os.makedirs(directory) except OSError as",
"import jwt import datetime from flask_cors import CORS,cross_origin import os import json from",
"return None @app.route('/audio', methods=['POST']) def soundfile(): token_data = validate_token(request) file = request.files['audio'] if",
"metadata['nativeLanguage'], 'gender': metadata['gender'] } file_path = os.path.join(directory, secure_filename(session_id + '.json')) with open(file_path, 'w')",
"def encode_auth_token(payload): signed_token = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] }",
"app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys = ['gender',",
"= request.form['filename'] foldername = request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file) resp =",
"import json from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage app = Flask(__name__)",
"200 @app.route('/meta', methods=['PUT']) def meta(): metadata = request.json if request.method == 'PUT' and",
"validate_json_payload(metadata, meta_keys): save_meta(metadata) token = encode_auth_token(metadata).decode() return {'token':token}, 200 else: return {'msg': 'Missing",
"token_string.encode() payload = jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload except: print('token validation went wrong') return",
"from flask import Flask, request, redirect, url_for, Response, jsonify from flask_cors import CORS",
"except: print('token validation went wrong') return None @app.route('/audio', methods=['POST']) def soundfile(): token_data =",
"save_wav(directory, filename, file) resp = Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin'] = '*' return resp",
"file = request.files['audio'] if request.method == 'POST' and token_data is not None and",
"submit worked') resp.headers['Access-Control-Allow-Origin'] = '*' return resp else: return {'msg':'Wrong request method or",
"validation went wrong') return None @app.route('/audio', methods=['POST']) def soundfile(): token_data = validate_token(request) file",
"<reponame>BlkPingu/SurveyBackend from flask import Flask, request, redirect, url_for, Response, jsonify from flask_cors import",
"if request.method == 'PUT' and validate_json_payload(metadata, meta_keys): save_meta(metadata) token = encode_auth_token(metadata).decode() return {'token':token},",
"get_token(bearer_token) token_bytes = token_string.encode() payload = jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload except: print('token validation",
"return payload except: print('token validation went wrong') return None @app.route('/audio', methods=['POST']) def soundfile():",
"os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise metadata = {",
"CORS from flask_sqlalchemy import SQLAlchemy import jwt import datetime from flask_cors import CORS,cross_origin",
"= False app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database' else: app.config['DEBUG']",
"@app.route('/xyz', methods=['GET']) def generic(): return {'msg':'hello i am flask'}, 200 @app.route('/meta', methods=['PUT']) def",
"import FileStorage app = Flask(__name__) if app.config['ENV'] == 'production': app.config['DEBUG'] = False app.config['SECRET_KEY']",
"!= errno.EEXIST: raise file_path = os.path.join(directory, secure_filename(filename + '.wav')) file.save(file_path) def validate_token(request): try:",
"'Bearer ' if not bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic():",
"app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV",
"redirect, url_for, Response, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy import",
"except OSError as e: if e.errno != errno.EEXIST: raise file_path = os.path.join(directory, secure_filename(filename",
"algorithm='HS256' ) except Exception as e: return e def validate_json_payload(meta_keys, metadata): for key",
"True app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set",
"file_path = os.path.join(directory, secure_filename(filename + '.wav')) file.save(file_path) def validate_token(request): try: bearer_token = request.headers['Authorization']",
"= os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID'] if not os.path.exists(directory): try: os.makedirs(directory) except OSError as",
"filename = request.form['filename'] foldername = request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file) resp",
"except OSError as e: if e.errno != errno.EEXIST: raise metadata = { 'uuid':",
"if e.errno != errno.EEXIST: raise file_path = os.path.join(directory, secure_filename(filename + '.wav')) file.save(file_path) def",
"from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage app = Flask(__name__) if app.config['ENV']",
"try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise file_path =",
"to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys = ['gender', 'age', 'nativeLanguage', 'dateTime', 'sessionID'] def encode_auth_token(payload):",
"= { 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try: return jwt.encode(",
"import CORS from flask_sqlalchemy import SQLAlchemy import jwt import datetime from flask_cors import",
"werkzeug.datastructures import FileStorage app = Flask(__name__) if app.config['ENV'] == 'production': app.config['DEBUG'] = False",
"e.errno != errno.EEXIST: raise metadata = { 'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'],",
"json from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage app = Flask(__name__) if",
"e.errno != errno.EEXIST: raise file_path = os.path.join(directory, secure_filename(filename + '.wav')) file.save(file_path) def validate_token(request):",
"generic(): return {'msg':'hello i am flask'}, 200 @app.route('/meta', methods=['PUT']) def meta(): metadata =",
"['gender', 'age', 'nativeLanguage', 'dateTime', 'sessionID'] def encode_auth_token(payload): signed_token = { 'exp': datetime.datetime.utcnow() +",
"wrong request method'}, 403 def save_wav(directory, filename, file): if not os.path.exists(directory): try: os.makedirs(directory)",
"Flask, request, redirect, url_for, Response, jsonify from flask_cors import CORS from flask_sqlalchemy import",
"e: return e def validate_json_payload(meta_keys, metadata): for key in meta_keys: if key not",
"'POST' and token_data is not None and file is not None: filename =",
"= 'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set to: {app.config[\"ENV\"]}')",
"e: if e.errno != errno.EEXIST: raise metadata = { 'uuid': metadata['sessionID'], 'age_range': metadata['age'],",
"and validate_json_payload(metadata, meta_keys): save_meta(metadata) token = encode_auth_token(metadata).decode() return {'token':token}, 200 else: return {'msg':",
"= request.json if request.method == 'PUT' and validate_json_payload(metadata, meta_keys): save_meta(metadata) token = encode_auth_token(metadata).decode()",
"flask'}, 200 @app.route('/meta', methods=['PUT']) def meta(): metadata = request.json if request.method == 'PUT'",
"for key in meta_keys: if key not in metadata: return False return True",
"file.save(file_path) def validate_token(request): try: bearer_token = request.headers['Authorization'] token_string = get_token(bearer_token) token_bytes = token_string.encode()",
"else: app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database'",
"not in metadata: return False return True def save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD']) session_id",
"bearer_token = request.headers['Authorization'] token_string = get_token(bearer_token) token_bytes = token_string.encode() payload = jwt.decode(token_bytes, app.config['SECRET_KEY'])",
"not None and file is not None: filename = request.form['filename'] foldername = request.form['foldername']",
"request.headers['Authorization'] token_string = get_token(bearer_token) token_bytes = token_string.encode() payload = jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload",
"app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set to:",
"soundfile(): token_data = validate_token(request) file = request.files['audio'] if request.method == 'POST' and token_data",
"file_path = os.path.join(directory, secure_filename(session_id + '.json')) with open(file_path, 'w') as fp: json.dump(metadata, fp)",
"app.config['METADATA_UPLOAD'] = '/srv/data/database' else: app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles'",
"PREFIX = 'Bearer ' if not bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET'])",
"print('token validation went wrong') return None @app.route('/audio', methods=['POST']) def soundfile(): token_data = validate_token(request)",
"'PUT' and validate_json_payload(metadata, meta_keys): save_meta(metadata) token = encode_auth_token(metadata).decode() return {'token':token}, 200 else: return",
"jwt import datetime from flask_cors import CORS,cross_origin import os import json from werkzeug.utils",
"keys or wrong request method'}, 403 def save_wav(directory, filename, file): if not os.path.exists(directory):",
"file): if not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno !=",
"{ 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try: return jwt.encode( signed_token,",
"'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try: return jwt.encode( signed_token, app.config.get('SECRET_KEY'),",
"return {'token':token}, 200 else: return {'msg': 'Missing keys or wrong request method'}, 403",
"metadata): for key in meta_keys: if key not in metadata: return False return",
"= metadata['sessionID'] if not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno",
"== 'POST' and token_data is not None and file is not None: filename",
"{'msg': 'Missing keys or wrong request method'}, 403 def save_wav(directory, filename, file): if",
"print(f'ENV is set to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys = ['gender', 'age', 'nativeLanguage', 'dateTime',",
"os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise file_path",
"datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try: return jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' ) except",
"in metadata: return False return True def save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD']) session_id =",
"{app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys = ['gender', 'age', 'nativeLanguage', 'dateTime', 'sessionID'] def encode_auth_token(payload): signed_token",
"from flask_sqlalchemy import SQLAlchemy import jwt import datetime from flask_cors import CORS,cross_origin import",
"is set to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys = ['gender', 'age', 'nativeLanguage', 'dateTime', 'sessionID']",
"session_id = metadata['sessionID'] if not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if",
"if app.config['ENV'] == 'production': app.config['DEBUG'] = False app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles'",
"foldername = request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file) resp = Response('Soundfile submit",
"import secure_filename from werkzeug.datastructures import FileStorage app = Flask(__name__) if app.config['ENV'] == 'production':",
"'dateTime', 'sessionID'] def encode_auth_token(payload): signed_token = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(),",
"secure_filename(filename + '.wav')) file.save(file_path) def validate_token(request): try: bearer_token = request.headers['Authorization'] token_string = get_token(bearer_token)",
") except Exception as e: return e def validate_json_payload(meta_keys, metadata): for key in",
"'Missing keys or wrong request method'}, 403 def save_wav(directory, filename, file): if not",
"import os import json from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage app",
"'.json')) with open(file_path, 'w') as fp: json.dump(metadata, fp) def get_token(bearer_token): PREFIX = 'Bearer",
"@app.route('/meta', methods=['PUT']) def meta(): metadata = request.json if request.method == 'PUT' and validate_json_payload(metadata,",
"not bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic(): return {'msg':'hello i",
"metadata['gender'] } file_path = os.path.join(directory, secure_filename(session_id + '.json')) with open(file_path, 'w') as fp:",
"import datetime from flask_cors import CORS,cross_origin import os import json from werkzeug.utils import",
"200 else: return {'msg': 'Missing keys or wrong request method'}, 403 def save_wav(directory,",
"'w') as fp: json.dump(metadata, fp) def get_token(bearer_token): PREFIX = 'Bearer ' if not",
"request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file) resp = Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin']",
"try: return jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' ) except Exception as e: return e",
"'.wav')) file.save(file_path) def validate_token(request): try: bearer_token = request.headers['Authorization'] token_string = get_token(bearer_token) token_bytes =",
"went wrong') return None @app.route('/audio', methods=['POST']) def soundfile(): token_data = validate_token(request) file =",
"fp) def get_token(bearer_token): PREFIX = 'Bearer ' if not bearer_token.startswith(PREFIX): return None return",
"errno.EEXIST: raise metadata = { 'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender']",
"= Flask(__name__) if app.config['ENV'] == 'production': app.config['DEBUG'] = False app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD']",
"else: return {'msg': 'Missing keys or wrong request method'}, 403 def save_wav(directory, filename,",
"set to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys = ['gender', 'age', 'nativeLanguage', 'dateTime', 'sessionID'] def",
"flask_cors import CORS,cross_origin import os import json from werkzeug.utils import secure_filename from werkzeug.datastructures",
"Response, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy import jwt import",
"= '/srv/data/database' else: app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD']",
"as e: if e.errno != errno.EEXIST: raise file_path = os.path.join(directory, secure_filename(filename + '.wav'))",
"if not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST:",
"= { 'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender'] } file_path =",
"= '*' return resp else: return {'msg':'Wrong request method or bad token'}, 403",
"or wrong request method'}, 403 def save_wav(directory, filename, file): if not os.path.exists(directory): try:",
"{'msg':'hello i am flask'}, 200 @app.route('/meta', methods=['PUT']) def meta(): metadata = request.json if",
"= jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload except: print('token validation went wrong') return None @app.route('/audio',",
"token = encode_auth_token(metadata).decode() return {'token':token}, 200 else: return {'msg': 'Missing keys or wrong",
"file) resp = Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin'] = '*' return resp else: return",
"if e.errno != errno.EEXIST: raise metadata = { 'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request':",
"import CORS,cross_origin import os import json from werkzeug.utils import secure_filename from werkzeug.datastructures import",
"= request.files['audio'] if request.method == 'POST' and token_data is not None and file",
"as e: if e.errno != errno.EEXIST: raise metadata = { 'uuid': metadata['sessionID'], 'age_range':",
"save_wav(directory, filename, file): if not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if",
"am flask'}, 200 @app.route('/meta', methods=['PUT']) def meta(): metadata = request.json if request.method ==",
"filename, file) resp = Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin'] = '*' return resp else:",
"FileStorage app = Flask(__name__) if app.config['ENV'] == 'production': app.config['DEBUG'] = False app.config['SECRET_KEY'] =",
"== 'production': app.config['DEBUG'] = False app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] =",
"jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload except: print('token validation went wrong') return None @app.route('/audio', methods=['POST'])",
"return False return True def save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID'] if",
"worked') resp.headers['Access-Control-Allow-Origin'] = '*' return resp else: return {'msg':'Wrong request method or bad",
"methods=['GET']) def generic(): return {'msg':'hello i am flask'}, 200 @app.route('/meta', methods=['PUT']) def meta():",
"{'token':token}, 200 else: return {'msg': 'Missing keys or wrong request method'}, 403 def",
"!= errno.EEXIST: raise metadata = { 'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender':",
"payload except: print('token validation went wrong') return None @app.route('/audio', methods=['POST']) def soundfile(): token_data",
"} file_path = os.path.join(directory, secure_filename(session_id + '.json')) with open(file_path, 'w') as fp: json.dump(metadata,",
"os import json from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage app =",
"'<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database' else: app.config['DEBUG'] = True app.config['SECRET_KEY'] =",
"token_data = validate_token(request) file = request.files['audio'] if request.method == 'POST' and token_data is",
"'gender': metadata['gender'] } file_path = os.path.join(directory, secure_filename(session_id + '.json')) with open(file_path, 'w') as",
"OSError as e: if e.errno != errno.EEXIST: raise file_path = os.path.join(directory, secure_filename(filename +",
"'sessionID'] def encode_auth_token(payload): signed_token = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID']",
"not None: filename = request.form['filename'] foldername = request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename,",
"metadata = request.json if request.method == 'PUT' and validate_json_payload(metadata, meta_keys): save_meta(metadata) token =",
"methods=['POST']) def soundfile(): token_data = validate_token(request) file = request.files['audio'] if request.method == 'POST'",
"app.config['DEBUG'] = False app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database' else:",
"bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic(): return {'msg':'hello i am",
"= True app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is",
"+ datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try: return jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' )",
"json.dump(metadata, fp) def get_token(bearer_token): PREFIX = 'Bearer ' if not bearer_token.startswith(PREFIX): return None",
"metadata = { 'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender'] } file_path",
"fp: json.dump(metadata, fp) def get_token(bearer_token): PREFIX = 'Bearer ' if not bearer_token.startswith(PREFIX): return",
"os.path.join(directory, secure_filename(session_id + '.json')) with open(file_path, 'w') as fp: json.dump(metadata, fp) def get_token(bearer_token):",
"os.path.join(directory, secure_filename(filename + '.wav')) file.save(file_path) def validate_token(request): try: bearer_token = request.headers['Authorization'] token_string =",
"= token_string.encode() payload = jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload except: print('token validation went wrong')",
"CORS,cross_origin import os import json from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage",
"metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender'] } file_path = os.path.join(directory, secure_filename(session_id +",
"= request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file) resp = Response('Soundfile submit worked')",
"return True def save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID'] if not os.path.exists(directory):",
"' if not bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic(): return",
"jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' ) except Exception as e: return e def validate_json_payload(meta_keys,",
"def validate_token(request): try: bearer_token = request.headers['Authorization'] token_string = get_token(bearer_token) token_bytes = token_string.encode() payload",
"and token_data is not None and file is not None: filename = request.form['filename']",
"= os.path.join(directory, secure_filename(filename + '.wav')) file.save(file_path) def validate_token(request): try: bearer_token = request.headers['Authorization'] token_string",
"None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic(): return {'msg':'hello i am flask'}, 200",
"Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin'] = '*' return resp else: return {'msg':'Wrong request method",
"'/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys = ['gender', 'age', 'nativeLanguage',",
"= validate_token(request) file = request.files['audio'] if request.method == 'POST' and token_data is not",
"None: filename = request.form['filename'] foldername = request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file)",
"resp = Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin'] = '*' return resp else: return {'msg':'Wrong",
"SQLAlchemy import jwt import datetime from flask_cors import CORS,cross_origin import os import json",
"request.form['filename'] foldername = request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file) resp = Response('Soundfile",
"def get_token(bearer_token): PREFIX = 'Bearer ' if not bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):]",
"method'}, 403 def save_wav(directory, filename, file): if not os.path.exists(directory): try: os.makedirs(directory) except OSError",
"os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID'] if not os.path.exists(directory): try: os.makedirs(directory) except OSError as e:",
"flask_sqlalchemy import SQLAlchemy import jwt import datetime from flask_cors import CORS,cross_origin import os",
"save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID'] if not os.path.exists(directory): try: os.makedirs(directory) except",
"meta_keys): save_meta(metadata) token = encode_auth_token(metadata).decode() return {'token':token}, 200 else: return {'msg': 'Missing keys",
"def save_wav(directory, filename, file): if not os.path.exists(directory): try: os.makedirs(directory) except OSError as e:",
"'/srv/data/database' else: app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] =",
"e def validate_json_payload(meta_keys, metadata): for key in meta_keys: if key not in metadata:",
"secure_filename(session_id + '.json')) with open(file_path, 'w') as fp: json.dump(metadata, fp) def get_token(bearer_token): PREFIX",
"'sessionID':payload['sessionID'] } try: return jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' ) except Exception as e:",
"key not in metadata: return False return True def save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD'])",
"encode_auth_token(payload): signed_token = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try:",
"flask import Flask, request, redirect, url_for, Response, jsonify from flask_cors import CORS from",
"= '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys = ['gender', 'age',",
"save_meta(metadata) token = encode_auth_token(metadata).decode() return {'token':token}, 200 else: return {'msg': 'Missing keys or",
"None @app.route('/audio', methods=['POST']) def soundfile(): token_data = validate_token(request) file = request.files['audio'] if request.method",
"= 'Bearer ' if not bearer_token.startswith(PREFIX): return None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def",
"token_string = get_token(bearer_token) token_bytes = token_string.encode() payload = jwt.decode(token_bytes, app.config['SECRET_KEY']) return payload except:",
"from werkzeug.datastructures import FileStorage app = Flask(__name__) if app.config['ENV'] == 'production': app.config['DEBUG'] =",
"app.config['SECRET_KEY']) return payload except: print('token validation went wrong') return None @app.route('/audio', methods=['POST']) def",
"resp.headers['Access-Control-Allow-Origin'] = '*' return resp else: return {'msg':'Wrong request method or bad token'},",
"os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file) resp = Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin'] = '*' return",
"open(file_path, 'w') as fp: json.dump(metadata, fp) def get_token(bearer_token): PREFIX = 'Bearer ' if",
"werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage app = Flask(__name__) if app.config['ENV'] ==",
"signed_token = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat': datetime.datetime.utcnow(), 'sessionID':payload['sessionID'] } try: return",
"app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True)",
"e: if e.errno != errno.EEXIST: raise file_path = os.path.join(directory, secure_filename(filename + '.wav')) file.save(file_path)",
"methods=['PUT']) def meta(): metadata = request.json if request.method == 'PUT' and validate_json_payload(metadata, meta_keys):",
"url_for, Response, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy import jwt",
"return None return bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic(): return {'msg':'hello i am flask'},",
"== 'PUT' and validate_json_payload(metadata, meta_keys): save_meta(metadata) token = encode_auth_token(metadata).decode() return {'token':token}, 200 else:",
"def soundfile(): token_data = validate_token(request) file = request.files['audio'] if request.method == 'POST' and",
"def validate_json_payload(meta_keys, metadata): for key in meta_keys: if key not in metadata: return",
"app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database' else: app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'secret'",
"False app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database' else: app.config['DEBUG'] =",
"= '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database' else: app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'secret' app.config['SOUNDFILE_UPLOAD']",
"supports_credentials=True) meta_keys = ['gender', 'age', 'nativeLanguage', 'dateTime', 'sessionID'] def encode_auth_token(payload): signed_token = {",
"'age', 'nativeLanguage', 'dateTime', 'sessionID'] def encode_auth_token(payload): signed_token = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3),",
"secure_filename from werkzeug.datastructures import FileStorage app = Flask(__name__) if app.config['ENV'] == 'production': app.config['DEBUG']",
"try: bearer_token = request.headers['Authorization'] token_string = get_token(bearer_token) token_bytes = token_string.encode() payload = jwt.decode(token_bytes,",
"raise file_path = os.path.join(directory, secure_filename(filename + '.wav')) file.save(file_path) def validate_token(request): try: bearer_token =",
"is not None: filename = request.form['filename'] foldername = request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory,",
"return jwt.encode( signed_token, app.config.get('SECRET_KEY'), algorithm='HS256' ) except Exception as e: return e def",
"+ '.json')) with open(file_path, 'w') as fp: json.dump(metadata, fp) def get_token(bearer_token): PREFIX =",
"file is not None: filename = request.form['filename'] foldername = request.form['foldername'] directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername)",
"filename, file): if not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno",
"= Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin'] = '*' return resp else: return {'msg':'Wrong request",
"def generic(): return {'msg':'hello i am flask'}, 200 @app.route('/meta', methods=['PUT']) def meta(): metadata",
"= os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file) resp = Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin'] = '*'",
"Flask(__name__) if app.config['ENV'] == 'production': app.config['DEBUG'] = False app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD'] =",
"if request.method == 'POST' and token_data is not None and file is not",
"request.method == 'POST' and token_data is not None and file is not None:",
"datetime from flask_cors import CORS,cross_origin import os import json from werkzeug.utils import secure_filename",
"flask_cors import CORS from flask_sqlalchemy import SQLAlchemy import jwt import datetime from flask_cors",
"metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender'] } file_path = os.path.join(directory, secure_filename(session_id + '.json')) with",
"request.files['audio'] if request.method == 'POST' and token_data is not None and file is",
"return {'msg': 'Missing keys or wrong request method'}, 403 def save_wav(directory, filename, file):",
"is not None and file is not None: filename = request.form['filename'] foldername =",
"'secret' app.config['SOUNDFILE_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set to: {app.config[\"ENV\"]}') CORS(app,",
"return {'msg':'hello i am flask'}, 200 @app.route('/meta', methods=['PUT']) def meta(): metadata = request.json",
"directory = os.path.join(app.config.get('SOUNDFILE_UPLOAD'),foldername) save_wav(directory, filename, file) resp = Response('Soundfile submit worked') resp.headers['Access-Control-Allow-Origin'] =",
"app.config['ENV'] == 'production': app.config['DEBUG'] = False app.config['SECRET_KEY'] = '<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD']",
"'/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/soundfiles' app.config['METADATA_UPLOAD'] = '/Users/Tobias/Desktop/Bachelorarbeit/Code/SurveyPage/data/database' print(f'ENV is set to: {app.config[\"ENV\"]}') CORS(app, supports_credentials=True) meta_keys =",
"def meta(): metadata = request.json if request.method == 'PUT' and validate_json_payload(metadata, meta_keys): save_meta(metadata)",
"None and file is not None: filename = request.form['filename'] foldername = request.form['foldername'] directory",
"{ 'uuid': metadata['sessionID'], 'age_range': metadata['age'], 'request': metadata['nativeLanguage'], 'gender': metadata['gender'] } file_path = os.path.join(directory,",
"as fp: json.dump(metadata, fp) def get_token(bearer_token): PREFIX = 'Bearer ' if not bearer_token.startswith(PREFIX):",
"key in meta_keys: if key not in metadata: return False return True def",
"bearer_token[len(PREFIX):] @app.route('/xyz', methods=['GET']) def generic(): return {'msg':'hello i am flask'}, 200 @app.route('/meta', methods=['PUT'])",
"'nativeLanguage', 'dateTime', 'sessionID'] def encode_auth_token(payload): signed_token = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=3), 'iat':",
"False return True def save_meta(metadata): directory = os.path.join(app.config['METADATA_UPLOAD']) session_id = metadata['sessionID'] if not",
"= '<KEY>' app.config['SOUNDFILE_UPLOAD'] = '/srv/data/soundfiles' app.config['METADATA_UPLOAD'] = '/srv/data/database' else: app.config['DEBUG'] = True app.config['SECRET_KEY']"
] |
[
"of command with '-i' argument to keep processing jobs even if a job",
"from django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at = timezone.now() - timedelta(days=1)",
"processing jobs even if a job fails. Ensure the non-failing jobs are marked",
"ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\" Test invocation of command with '-i' argument to keep",
") def test_cmd_delete_completed(self): \"\"\" Test invocation of command with '-d' argument to delete",
"schedule_job(self.schedule_at, 'math.pow', args=(5, 2)) ] def test_cmd_noargs(self): \"\"\" Test invocation of command with",
"setUp(self): self.schedule_at = timezone.now() - timedelta(days=1) self.jobs = [ schedule_job(self.schedule_at, 'math.pow', args=(2, 3)),",
"as completed and the error job is marked as failed. \"\"\" schedule_at =",
"import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at = timezone.now() - timedelta(days=1) self.jobs =",
"schedule_job(self.schedule_at, 'math.pow', args=(2, 3)), schedule_job(self.schedule_at, 'math.pow', args=(5, 2)) ] def test_cmd_noargs(self): \"\"\" Test",
"django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at = timezone.now() - timedelta(days=1) self.jobs",
"delete completed jobs. Ensure the scheduled jobs are removed after. \"\"\" self.assertEqual( 2,",
"argument to keep processing jobs even if a job fails. Ensure the non-failing",
"\"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def",
"self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\" Test invocation of command with '-i' argument to",
"[ schedule_job(self.schedule_at, 'math.pow', args=(2, 3)), schedule_job(self.schedule_at, 'math.pow', args=(5, 2)) ] def test_cmd_noargs(self): \"\"\"",
"timezone from django_future.jobs import schedule_job from django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self):",
"self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-i') error_job.refresh_from_db() self.assertEqual(error_job.status, ScheduledJob.STATUS_FAILED) self.assertEqual( 2, ScheduledJob.objects.filter(",
"from django_future.jobs import schedule_job from django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at",
"= schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-i') error_job.refresh_from_db() self.assertEqual(error_job.status, ScheduledJob.STATUS_FAILED)",
"import TestCase from django.utils import timezone from django_future.jobs import schedule_job from django_future.models import",
"test_cmd_delete_completed(self): \"\"\" Test invocation of command with '-d' argument to delete completed jobs.",
"\"\"\" Test invocation of command with no arguments. Ensure the scheduled jobs are",
"'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-i') error_job.refresh_from_db() self.assertEqual(error_job.status, ScheduledJob.STATUS_FAILED) self.assertEqual( 2,",
"schedule_job from django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at = timezone.now() -",
"def test_cmd_delete_completed(self): \"\"\" Test invocation of command with '-d' argument to delete completed",
"test_cmd_ignore_errors(self): \"\"\" Test invocation of command with '-i' argument to keep processing jobs",
"\"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\"",
"2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self): \"\"\" Test invocation of command with '-d'",
"def test_cmd_ignore_errors(self): \"\"\" Test invocation of command with '-i' argument to keep processing",
"3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-i') error_job.refresh_from_db() self.assertEqual(error_job.status, ScheduledJob.STATUS_FAILED) self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count()",
"\"\"\" Test invocation of command with '-i' argument to keep processing jobs even",
"are marked as completed and the error job is marked as failed. \"\"\"",
"from django.utils import timezone from django_future.jobs import schedule_job from django_future.models import ScheduledJob class",
"jobs even if a job fails. Ensure the non-failing jobs are marked as",
"of command with no arguments. Ensure the scheduled jobs are marked as completed.",
"the scheduled jobs are marked as completed. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() )",
"2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\" Test invocation",
"as completed. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count()",
"args=(2, 3)), schedule_job(self.schedule_at, 'math.pow', args=(5, 2)) ] def test_cmd_noargs(self): \"\"\" Test invocation of",
"def setUp(self): self.schedule_at = timezone.now() - timedelta(days=1) self.jobs = [ schedule_job(self.schedule_at, 'math.pow', args=(2,",
"job is marked as failed. \"\"\" schedule_at = self.schedule_at - timedelta(days=1) error_job =",
"Test invocation of command with '-i' argument to keep processing jobs even if",
"self.jobs = [ schedule_job(self.schedule_at, 'math.pow', args=(2, 3)), schedule_job(self.schedule_at, 'math.pow', args=(5, 2)) ] def",
"status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\" Test invocation of command",
"- timedelta(days=1) error_job = schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-i')",
"= timezone.now() - timedelta(days=1) self.jobs = [ schedule_job(self.schedule_at, 'math.pow', args=(2, 3)), schedule_job(self.schedule_at, 'math.pow',",
"marked as completed and the error job is marked as failed. \"\"\" schedule_at",
"django.core.management import call_command from django.test import TestCase from django.utils import timezone from django_future.jobs",
"TestCase from django.utils import timezone from django_future.jobs import schedule_job from django_future.models import ScheduledJob",
"from datetime import timedelta from django.core.management import call_command from django.test import TestCase from",
"'math.pow', args=(2, 3)), schedule_job(self.schedule_at, 'math.pow', args=(5, 2)) ] def test_cmd_noargs(self): \"\"\" Test invocation",
"invocation of command with no arguments. Ensure the scheduled jobs are marked as",
"scheduled jobs are removed after. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d')",
"self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self): \"\"\" Test invocation of command with",
"jobs are marked as completed. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual(",
"of command with '-d' argument to delete completed jobs. Ensure the scheduled jobs",
"jobs are removed after. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d') self.assertEqual(0,",
"call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\" Test invocation of command with '-i'",
"timezone.now() - timedelta(days=1) self.jobs = [ schedule_job(self.schedule_at, 'math.pow', args=(2, 3)), schedule_job(self.schedule_at, 'math.pow', args=(5,",
"'-i' argument to keep processing jobs even if a job fails. Ensure the",
"status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self): \"\"\" Test invocation",
"keep processing jobs even if a job fails. Ensure the non-failing jobs are",
"\"\"\" Test invocation of command with '-d' argument to delete completed jobs. Ensure",
"timedelta(days=1) self.jobs = [ schedule_job(self.schedule_at, 'math.pow', args=(2, 3)), schedule_job(self.schedule_at, 'math.pow', args=(5, 2)) ]",
"def test_cmd_noargs(self): \"\"\" Test invocation of command with no arguments. Ensure the scheduled",
"completed jobs. Ensure the scheduled jobs are removed after. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter(",
"command with '-i' argument to keep processing jobs even if a job fails.",
"Ensure the scheduled jobs are marked as completed. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count()",
"no arguments. Ensure the scheduled jobs are marked as completed. \"\"\" self.assertEqual( 2,",
"ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self): \"\"\" Test",
"the non-failing jobs are marked as completed and the error job is marked",
"datetime import timedelta from django.core.management import call_command from django.test import TestCase from django.utils",
"self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\" Test",
"import timedelta from django.core.management import call_command from django.test import TestCase from django.utils import",
"Ensure the scheduled jobs are removed after. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() )",
"self.schedule_at - timedelta(days=1) error_job = schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs',",
"Ensure the non-failing jobs are marked as completed and the error job is",
"command with no arguments. Ensure the scheduled jobs are marked as completed. \"\"\"",
"self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self):",
"ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self): \"\"\" Test invocation of command with '-d' argument",
"class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at = timezone.now() - timedelta(days=1) self.jobs = [ schedule_job(self.schedule_at,",
"scheduled jobs are marked as completed. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs')",
"after. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self):",
"test_cmd_noargs(self): \"\"\" Test invocation of command with no arguments. Ensure the scheduled jobs",
"command with '-d' argument to delete completed jobs. Ensure the scheduled jobs are",
"invocation of command with '-d' argument to delete completed jobs. Ensure the scheduled",
"error job is marked as failed. \"\"\" schedule_at = self.schedule_at - timedelta(days=1) error_job",
"marked as failed. \"\"\" schedule_at = self.schedule_at - timedelta(days=1) error_job = schedule_job(schedule_at, 'math.funky_error')",
") call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self): \"\"\" Test invocation of",
"to keep processing jobs even if a job fails. Ensure the non-failing jobs",
"call_command from django.test import TestCase from django.utils import timezone from django_future.jobs import schedule_job",
"status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self): \"\"\" Test invocation of command with '-d' argument to",
"argument to delete completed jobs. Ensure the scheduled jobs are removed after. \"\"\"",
") call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\" Test invocation of command with",
"jobs. Ensure the scheduled jobs are removed after. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count()",
"to delete completed jobs. Ensure the scheduled jobs are removed after. \"\"\" self.assertEqual(",
"'-d') self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\" Test invocation of command with '-i' argument",
"jobs are marked as completed and the error job is marked as failed.",
"error_job = schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-i') error_job.refresh_from_db() self.assertEqual(error_job.status,",
"- timedelta(days=1) self.jobs = [ schedule_job(self.schedule_at, 'math.pow', args=(2, 3)), schedule_job(self.schedule_at, 'math.pow', args=(5, 2))",
"marked as completed. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter(",
"'math.pow', args=(5, 2)) ] def test_cmd_noargs(self): \"\"\" Test invocation of command with no",
"are removed after. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count())",
"with '-i' argument to keep processing jobs even if a job fails. Ensure",
"a job fails. Ensure the non-failing jobs are marked as completed and the",
"and the error job is marked as failed. \"\"\" schedule_at = self.schedule_at -",
"django.test import TestCase from django.utils import timezone from django_future.jobs import schedule_job from django_future.models",
"are marked as completed. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual( 2,",
"with '-d' argument to delete completed jobs. Ensure the scheduled jobs are removed",
"failed. \"\"\" schedule_at = self.schedule_at - timedelta(days=1) error_job = schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3,",
"ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-i') error_job.refresh_from_db() self.assertEqual(error_job.status, ScheduledJob.STATUS_FAILED) self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() )",
"django_future.jobs import schedule_job from django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at =",
"Test invocation of command with '-d' argument to delete completed jobs. Ensure the",
"is marked as failed. \"\"\" schedule_at = self.schedule_at - timedelta(days=1) error_job = schedule_job(schedule_at,",
"schedule_at = self.schedule_at - timedelta(days=1) error_job = schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count()",
"django.utils import timezone from django_future.jobs import schedule_job from django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase):",
"import call_command from django.test import TestCase from django.utils import timezone from django_future.jobs import",
"job fails. Ensure the non-failing jobs are marked as completed and the error",
"timedelta(days=1) error_job = schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-i') error_job.refresh_from_db()",
"] def test_cmd_noargs(self): \"\"\" Test invocation of command with no arguments. Ensure the",
"completed and the error job is marked as failed. \"\"\" schedule_at = self.schedule_at",
"RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at = timezone.now() - timedelta(days=1) self.jobs = [ schedule_job(self.schedule_at, 'math.pow',",
"2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self): \"\"\"",
"completed. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() )",
"removed after. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count()) def",
"non-failing jobs are marked as completed and the error job is marked as",
"import timezone from django_future.jobs import schedule_job from django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def",
"import schedule_job from django_future.models import ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at = timezone.now()",
"schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-i') error_job.refresh_from_db() self.assertEqual(error_job.status, ScheduledJob.STATUS_FAILED) self.assertEqual(",
"self.schedule_at = timezone.now() - timedelta(days=1) self.jobs = [ schedule_job(self.schedule_at, 'math.pow', args=(2, 3)), schedule_job(self.schedule_at,",
"as failed. \"\"\" schedule_at = self.schedule_at - timedelta(days=1) error_job = schedule_job(schedule_at, 'math.funky_error') self.assertEqual(",
"if a job fails. Ensure the non-failing jobs are marked as completed and",
"from django.test import TestCase from django.utils import timezone from django_future.jobs import schedule_job from",
"ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs', '-d') self.assertEqual(0, ScheduledJob.objects.count()) def test_cmd_ignore_errors(self): \"\"\" Test invocation of",
"3)), schedule_job(self.schedule_at, 'math.pow', args=(5, 2)) ] def test_cmd_noargs(self): \"\"\" Test invocation of command",
"call_command('runscheduledjobs') self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_COMPLETE).count() ) def test_cmd_delete_completed(self): \"\"\" Test invocation of command",
"invocation of command with '-i' argument to keep processing jobs even if a",
"'-d' argument to delete completed jobs. Ensure the scheduled jobs are removed after.",
"Test invocation of command with no arguments. Ensure the scheduled jobs are marked",
"= self.schedule_at - timedelta(days=1) error_job = schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() )",
"2)) ] def test_cmd_noargs(self): \"\"\" Test invocation of command with no arguments. Ensure",
"with no arguments. Ensure the scheduled jobs are marked as completed. \"\"\" self.assertEqual(",
"the scheduled jobs are removed after. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter( status=ScheduledJob.STATUS_SCHEDULED).count() ) call_command('runscheduledjobs',",
"= [ schedule_job(self.schedule_at, 'math.pow', args=(2, 3)), schedule_job(self.schedule_at, 'math.pow', args=(5, 2)) ] def test_cmd_noargs(self):",
"fails. Ensure the non-failing jobs are marked as completed and the error job",
"even if a job fails. Ensure the non-failing jobs are marked as completed",
"ScheduledJob class RunScheduledJobsCommandTest(TestCase): def setUp(self): self.schedule_at = timezone.now() - timedelta(days=1) self.jobs = [",
"the error job is marked as failed. \"\"\" schedule_at = self.schedule_at - timedelta(days=1)",
"\"\"\" schedule_at = self.schedule_at - timedelta(days=1) error_job = schedule_job(schedule_at, 'math.funky_error') self.assertEqual( 3, ScheduledJob.objects.filter(",
"arguments. Ensure the scheduled jobs are marked as completed. \"\"\" self.assertEqual( 2, ScheduledJob.objects.filter(",
"from django.core.management import call_command from django.test import TestCase from django.utils import timezone from",
"timedelta from django.core.management import call_command from django.test import TestCase from django.utils import timezone",
"args=(5, 2)) ] def test_cmd_noargs(self): \"\"\" Test invocation of command with no arguments."
] |
[
"to # of validation examples /batch size (i.e. figure out num validation examples)",
"KIND, either express or implied. # See the License for the specific language",
"tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299, 299]) image = tf.cast(image, tf.uint8) image = tf.reshape(image,",
"Unless required by applicable law or agreed to in writing, software # distributed",
"299]) image = tf.cast(image, tf.uint8) image = tf.reshape(image, [299, 299, 3]) #weird workaround",
"import os import sys from firecam.lib import settings from firecam.lib import collect_args from",
"if args.resumeModel: inception = tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) > 0 initial_epoch = int(args.startEpoch) else:",
"they are apprently rectangular much fo the time if example['image/height'] != 299 or",
"0 initial_epoch = int(args.startEpoch) else: inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2) initial_epoch =",
"epochs over which validation loss hasnt decreased to stop training at val_steps =",
"def main(): reqArgs = [ [\"i\", \"inputDir\", \"directory containing TFRecord files\"], [\"o\", \"outputDir\",",
"\"(optional) number of validation steps per epoch\", int], ] args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs,",
"and # limitations under the License. # ============================================================================== \"\"\" Training code using Keras",
"os import sys from firecam.lib import settings from firecam.lib import collect_args from firecam.lib",
"'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d training files, and %d validation files',",
"proto using the dictionary above. example = tf.io.parse_single_example(example_proto, feature_description) image = tf.image.decode_jpeg(example['image/encoded'], channels=3,",
"from given saved model\"], [\"s\", \"startEpoch\", \"epoch to resume from (epoch from resumeModel)\"],",
"because they are apprently rectangular much fo the time if example['image/height'] != 299",
"= tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299, 299]) image = tf.cast(image, tf.uint8) image =",
"\"nadam\": optimizer = tf.keras.optimizers.Nadam() elif args.algorithm == \"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported",
"tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([],",
"this to # of validation examples /batch size (i.e. figure out num validation",
"should be fixed in next version #TODO: either set this to # of",
"goog_helper from firecam.lib import tf_helper import glob import tensorflow as tf from tensorflow",
"= logs or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def main(): reqArgs = [",
"tf.one_hot(example['image/class/label'], depth=2) image = (tf.cast(image, tf.float32) - 128) / 128.0 return [image, label]",
"this file except in compliance with the License. # You may obtain a",
"tensorflow import keras import logging import datetime def _parse_function(example_proto): \"\"\" Function for converting",
"for now because of a bug in tf2.0, which should be fixed in",
"using Keras for TF2 \"\"\" from __future__ import absolute_import from __future__ import division",
"callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val,",
"len(val_filenames)) if (len(train_filenames) == 0) or (len(val_filenames) == 0): logging.error('Could not find data",
"= tf.reshape(image, [299, 299, 3]) #weird workaround because decode image doesnt get shape",
"import datetime def _parse_function(example_proto): \"\"\" Function for converting TFRecordDataset to uncompressed image pixels",
"apprently rectangular much fo the time if example['image/height'] != 299 or example['image/width'] !=",
"[example['image/height'], example['image/width'], 3]), [299, 299]) image = tf.cast(image, tf.uint8) image = tf.reshape(image, [299,",
"else 1000 steps_per_epoch = args.stepsPerEpoch if args.stepsPerEpoch else 2000 overshoot_epochs = 30 #number",
"tf.float32) - 128) / 128.0 return [image, label] class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir,",
"Function for converting TFRecordDataset to uncompressed image pixels + labels :return: \"\"\" feature_description",
"its ready and automatically go thorugh the whole set train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord'))",
"ANY KIND, either express or implied. # See the License for the specific",
"keras import logging import datetime def _parse_function(example_proto): \"\"\" Function for converting TFRecordDataset to",
"image = tf.reshape(image, [299, 299, 3]) #weird workaround because decode image doesnt get",
"which should be fixed in next version #TODO: either set this to #",
"image = tf.cast(image, tf.uint8) image = tf.reshape(image, [299, 299, 3]) #weird workaround because",
"(len(val_filenames) == 0): logging.error('Could not find data in %s', args.inputDir) exit(1) raw_dataset_train =",
"max_epochs = args.maxEpochs if args.maxEpochs else 1000 steps_per_epoch = args.stepsPerEpoch if args.stepsPerEpoch else",
"next version #TODO: either set this to # of validation examples /batch size",
"2020 Open Climate Tech Contributors # # Licensed under the Apache License, Version",
"optimizer = tf.keras.optimizers.Nadam() elif args.algorithm == \"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo",
"hasnt decreased to stop training at val_steps = args.valStepsPerEpoch if args.valStepsPerEpoch else 200",
"= 64 max_epochs = args.maxEpochs if args.maxEpochs else 1000 steps_per_epoch = args.stepsPerEpoch if",
"keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=val_steps,",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"3]), [299, 299]) image = tf.cast(image, tf.uint8) image = tf.reshape(image, [299, 299, 3])",
"for TF2 \"\"\" from __future__ import absolute_import from __future__ import division from __future__",
"\"maxEpochs\", \"(optional) max number of epochs (default 1000)\", int], [\"r\", \"resumeModel\", \"resume training",
"exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size *",
"absolute_import from __future__ import division from __future__ import print_function import os import sys",
"optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size = 64 max_epochs = args.maxEpochs if args.maxEpochs else 1000 steps_per_epoch",
"} # Parse the input `tf.Example` proto using the dictionary above. example =",
"'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width':",
"logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)]",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"Contributors # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"you need super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self, epoch, logs=None): logs = logs or {}",
"1000 steps_per_epoch = args.stepsPerEpoch if args.stepsPerEpoch else 2000 overshoot_epochs = 30 #number of",
"Copyright 2020 Open Climate Tech Contributors # # Licensed under the Apache License,",
"OF ANY KIND, either express or implied. # See the License for the",
"datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train,",
"of a bug in tf2.0, which should be fixed in next version #TODO:",
"as tf from tensorflow import keras import logging import datetime def _parse_function(example_proto): \"\"\"",
"(i.e. figure out num validation examples) #or upgrade to TF2.1 when its ready",
"args.stepsPerEpoch else 2000 overshoot_epochs = 30 #number of epochs over which validation loss",
"if args.valStepsPerEpoch else 200 #val_steps only needed for now because of a bug",
"\"startEpoch\", \"epoch to resume from (epoch from resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional) number of",
"# limitations under the License. # ============================================================================== \"\"\" Training code using Keras for",
"if args.stepsPerEpoch else 2000 overshoot_epochs = 30 #number of epochs over which validation",
"bug in tf2.0, which should be fixed in next version #TODO: either set",
"input `tf.Example` proto using the dictionary above. example = tf.io.parse_single_example(example_proto, feature_description) image =",
"#number of epochs over which validation loss hasnt decreased to stop training at",
"__future__ import absolute_import from __future__ import division from __future__ import print_function import os",
"[ [\"m\", \"maxEpochs\", \"(optional) max number of epochs (default 1000)\", int], [\"r\", \"resumeModel\",",
"assert int(args.startEpoch) > 0 initial_epoch = int(args.startEpoch) else: inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None,",
"classes=2) initial_epoch = 0 if args.algorithm == \"adam\": # optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9,",
"default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0),",
"int], [\"v\", \"valStepsPerEpoch\", \"(optional) number of validation steps per epoch\", int], ] args",
"set because they are apprently rectangular much fo the time if example['image/height'] !=",
"dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception = tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) > 0 initial_epoch",
"firecam.lib import tf_helper import glob import tensorflow as tf from tensorflow import keras",
"much fo the time if example['image/height'] != 299 or example['image/width'] != 299: image",
"tf.reshape(image, [299, 299, 3]) #weird workaround because decode image doesnt get shape label",
"Tech Contributors # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"loss hasnt decreased to stop training at val_steps = args.valStepsPerEpoch if args.valStepsPerEpoch else",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), } # Parse the input `tf.Example` proto using the",
"elif args.algorithm == \"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo %s', args.algorithm) exit(1)",
"============================================================================== \"\"\" Training code using Keras for TF2 \"\"\" from __future__ import absolute_import",
"or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def main(): reqArgs = [ [\"i\", \"inputDir\",",
"depth=2) image = (tf.cast(image, tf.float32) - 128) / 128.0 return [image, label] class",
"optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm == \"nadam\": optimizer = tf.keras.optimizers.Nadam() elif args.algorithm",
"64 max_epochs = args.maxEpochs if args.maxEpochs else 1000 steps_per_epoch = args.stepsPerEpoch if args.stepsPerEpoch",
"[ [\"i\", \"inputDir\", \"directory containing TFRecord files\"], [\"o\", \"outputDir\", \"directory to write out",
"= keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2) initial_epoch = 0 if args.algorithm == \"adam\": #",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"converting TFRecordDataset to uncompressed image pixels + labels :return: \"\"\" feature_description = {",
"upgrade to TF2.1 when its ready and automatically go thorugh the whole set",
"tf from tensorflow import keras import logging import datetime def _parse_function(example_proto): \"\"\" Function",
"keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2) initial_epoch = 0 if args.algorithm == \"adam\": # optimizer",
"\"valStepsPerEpoch\", \"(optional) number of validation steps per epoch\", int], ] args = collect_args.collectArgs(reqArgs,",
"need super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self, epoch, logs=None): logs = logs or {} logs.update({'lr':",
"beta_2=0.999, amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm == \"nadam\": optimizer = tf.keras.optimizers.Nadam()",
"set train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d training files,",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"tf.cast(image, tf.uint8) image = tf.reshape(image, [299, 299, 3]) #weird workaround because decode image",
"dictionary above. example = tf.io.parse_single_example(example_proto, feature_description) image = tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing images",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"= 30 #number of epochs over which validation loss hasnt decreased to stop",
"number of steps per epoch\", int], [\"v\", \"valStepsPerEpoch\", \"(optional) number of validation steps",
"] args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size = 64 max_epochs = args.maxEpochs if",
"the License. # ============================================================================== \"\"\" Training code using Keras for TF2 \"\"\" from",
"arguments to __init__ if you need super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self, epoch, logs=None): logs",
"stop training at val_steps = args.valStepsPerEpoch if args.valStepsPerEpoch else 200 #val_steps only needed",
"from firecam.lib import settings from firecam.lib import collect_args from firecam.lib import goog_helper from",
"required by applicable law or agreed to in writing, software # distributed under",
"* steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception = tf_helper.loadModel(args.resumeModel) assert",
"] optArgs = [ [\"m\", \"maxEpochs\", \"(optional) max number of epochs (default 1000)\",",
"raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size)",
"are apprently rectangular much fo the time if example['image/height'] != 299 or example['image/width']",
"applicable law or agreed to in writing, software # distributed under the License",
"[299, 299]) image = tf.cast(image, tf.uint8) image = tf.reshape(image, [299, 299, 3]) #weird",
"the dictionary above. example = tf.io.parse_single_example(example_proto, feature_description) image = tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing",
"def _parse_function(example_proto): \"\"\" Function for converting TFRecordDataset to uncompressed image pixels + labels",
"Training code using Keras for TF2 \"\"\" from __future__ import absolute_import from __future__",
"for converting TFRecordDataset to uncompressed image pixels + labels :return: \"\"\" feature_description =",
"example = tf.io.parse_single_example(example_proto, feature_description) image = tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing images in training",
"when its ready and automatically go thorugh the whole set train_filenames = glob.glob(os.path.join(args.inputDir,",
"and %d validation files', len(train_filenames), len(val_filenames)) if (len(train_filenames) == 0) or (len(val_filenames) ==",
"or agreed to in writing, software # distributed under the License is distributed",
"5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception = tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) > 0",
"= glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d training files, and %d validation files', len(train_filenames), len(val_filenames))",
"\"adam\": # optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif",
"training at val_steps = args.valStepsPerEpoch if args.valStepsPerEpoch else 200 #val_steps only needed for",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"# ============================================================================== \"\"\" Training code using Keras for TF2 \"\"\" from __future__ import",
"logs = logs or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def main(): reqArgs =",
"[\"s\", \"startEpoch\", \"epoch to resume from (epoch from resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional) number",
"under the License. # ============================================================================== \"\"\" Training code using Keras for TF2 \"\"\"",
"default_value=0), } # Parse the input `tf.Example` proto using the dictionary above. example",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"[image, label] class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir, **kwargs): # add other arguments to",
"the whole set train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"thorugh the whole set train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"tf.keras.optimizers.Nadam() elif args.algorithm == \"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo %s', args.algorithm)",
"%d validation files', len(train_filenames), len(val_filenames)) if (len(train_filenames) == 0) or (len(val_filenames) == 0):",
"args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs),",
"License. # You may obtain a copy of the License at # #",
"# Parse the input `tf.Example` proto using the dictionary above. example = tf.io.parse_single_example(example_proto,",
"feature_description = { 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([],",
"[keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch,",
"image = tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing images in training set because they are",
"2000 overshoot_epochs = 30 #number of epochs over which validation loss hasnt decreased",
"files\"], [\"o\", \"outputDir\", \"directory to write out checkpoints and tensorboard logs\"], [\"a\", \"algorithm\",",
"firecam.lib import collect_args from firecam.lib import goog_helper from firecam.lib import tf_helper import glob",
"compliance with the License. # You may obtain a copy of the License",
"\"resume training from given saved model\"], [\"s\", \"startEpoch\", \"epoch to resume from (epoch",
"monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=val_steps, callbacks=callbacks) logging.warning('Done",
"epoch, logs=None): logs = logs or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def main():",
"in %s', args.inputDir) exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs",
"in training set because they are apprently rectangular much fo the time if",
"of epochs (default 1000)\", int], [\"r\", \"resumeModel\", \"resume training from given saved model\"],",
"= 0 if args.algorithm == \"adam\": # optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)",
"optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm ==",
"checkpoints and tensorboard logs\"], [\"a\", \"algorithm\", \"adam, nadam, or rmsprop\"], ] optArgs =",
"%s', args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss',",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"labels :return: \"\"\" feature_description = { 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string,",
"save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=val_steps, callbacks=callbacks) logging.warning('Done training')",
"validation loss hasnt decreased to stop training at val_steps = args.valStepsPerEpoch if args.valStepsPerEpoch",
"#Resizing images in training set because they are apprently rectangular much fo the",
"image pixels + labels :return: \"\"\" feature_description = { 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0),",
"training from given saved model\"], [\"s\", \"startEpoch\", \"epoch to resume from (epoch from",
"= tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) > 0 initial_epoch = int(args.startEpoch) else: inception = keras.applications.inception_v3.InceptionV3(weights=None,",
"import tensorflow as tf from tensorflow import keras import logging import datetime def",
"val_steps = args.valStepsPerEpoch if args.valStepsPerEpoch else 200 #val_steps only needed for now because",
"\"outputDir\", \"directory to write out checkpoints and tensorboard logs\"], [\"a\", \"algorithm\", \"adam, nadam,",
"TF2 \"\"\" from __future__ import absolute_import from __future__ import division from __future__ import",
"= collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size = 64 max_epochs = args.maxEpochs if args.maxEpochs else",
"30 #number of epochs over which validation loss hasnt decreased to stop training",
"not use this file except in compliance with the License. # You may",
"tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), } # Parse the input `tf.Example`",
"from firecam.lib import tf_helper import glob import tensorflow as tf from tensorflow import",
"glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d training files, and %d validation",
"import print_function import os import sys from firecam.lib import settings from firecam.lib import",
"model\"], [\"s\", \"startEpoch\", \"epoch to resume from (epoch from resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional)",
"raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception = tf_helper.loadModel(args.resumeModel)",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir, **kwargs): # add other arguments to __init__ if you",
"reqArgs = [ [\"i\", \"inputDir\", \"directory containing TFRecord files\"], [\"o\", \"outputDir\", \"directory to",
"or rmsprop\"], ] optArgs = [ [\"m\", \"maxEpochs\", \"(optional) max number of epochs",
"examples /batch size (i.e. figure out num validation examples) #or upgrade to TF2.1",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"\"inputDir\", \"directory containing TFRecord files\"], [\"o\", \"outputDir\", \"directory to write out checkpoints and",
"\"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo %s', args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy'])",
"== \"nadam\": optimizer = tf.keras.optimizers.Nadam() elif args.algorithm == \"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else:",
"to write out checkpoints and tensorboard logs\"], [\"a\", \"algorithm\", \"adam, nadam, or rmsprop\"],",
"[\"r\", \"resumeModel\", \"resume training from given saved model\"], [\"s\", \"startEpoch\", \"epoch to resume",
"time if example['image/height'] != 299 or example['image/width'] != 299: image = tf.image.resize(tf.reshape(image, [example['image/height'],",
"3]) #weird workaround because decode image doesnt get shape label = tf.one_hot(example['image/class/label'], depth=2)",
"doesnt get shape label = tf.one_hot(example['image/class/label'], depth=2) image = (tf.cast(image, tf.float32) - 128)",
"decode image doesnt get shape label = tf.one_hot(example['image/class/label'], depth=2) image = (tf.cast(image, tf.float32)",
"tf.int64, default_value=0), } # Parse the input `tf.Example` proto using the dictionary above.",
"if example['image/height'] != 299 or example['image/width'] != 299: image = tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'],",
"amsgrad=True) elif args.algorithm == \"nadam\": optimizer = tf.keras.optimizers.Nadam() elif args.algorithm == \"rmsprop\": optimizer",
"above. example = tf.io.parse_single_example(example_proto, feature_description) image = tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing images in",
"# you may not use this file except in compliance with the License.",
"\"(optional) number of steps per epoch\", int], [\"v\", \"valStepsPerEpoch\", \"(optional) number of validation",
"= tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm == \"nadam\": optimizer = tf.keras.optimizers.Nadam() elif args.algorithm ==",
"agreed to in writing, software # distributed under the License is distributed on",
"logging.error('Could not find data in %s', args.inputDir) exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val =",
"args.stepsPerEpoch if args.stepsPerEpoch else 2000 overshoot_epochs = 30 #number of epochs over which",
"os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training')",
"a bug in tf2.0, which should be fixed in next version #TODO: either",
"(the \"License\"); # you may not use this file except in compliance with",
"logs or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def main(): reqArgs = [ [\"i\",",
"tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel:",
"'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height':",
"nadam, or rmsprop\"], ] optArgs = [ [\"m\", \"maxEpochs\", \"(optional) max number of",
"args.valStepsPerEpoch if args.valStepsPerEpoch else 200 #val_steps only needed for now because of a",
"if args.algorithm == \"adam\": # optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer =",
"= tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo %s', args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir =",
"# Unless required by applicable law or agreed to in writing, software #",
"#TODO: either set this to # of validation examples /batch size (i.e. figure",
"else 200 #val_steps only needed for now because of a bug in tf2.0,",
"by applicable law or agreed to in writing, software # distributed under the",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"`tf.Example` proto using the dictionary above. example = tf.io.parse_single_example(example_proto, feature_description) image = tf.image.decode_jpeg(example['image/encoded'],",
"metrics=['accuracy']) logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True),",
"'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=val_steps, callbacks=callbacks)",
"LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=val_steps, callbacks=callbacks) logging.warning('Done training') if",
"{ 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''),",
"workaround because decode image doesnt get shape label = tf.one_hot(example['image/class/label'], depth=2) image =",
"__future__ import print_function import os import sys from firecam.lib import settings from firecam.lib",
"args.maxEpochs if args.maxEpochs else 1000 steps_per_epoch = args.stepsPerEpoch if args.stepsPerEpoch else 2000 overshoot_epochs",
"example['image/width'] != 299: image = tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299, 299]) image =",
"example['image/width'], 3]), [299, 299]) image = tf.cast(image, tf.uint8) image = tf.reshape(image, [299, 299,",
"file except in compliance with the License. # You may obtain a copy",
"= tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing images in training set because they are apprently",
"\"algorithm\", \"adam, nadam, or rmsprop\"], ] optArgs = [ [\"m\", \"maxEpochs\", \"(optional) max",
"# of validation examples /batch size (i.e. figure out num validation examples) #or",
"args.algorithm == \"adam\": # optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06,",
"division from __future__ import print_function import os import sys from firecam.lib import settings",
"resume from (epoch from resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional) number of steps per epoch\",",
"= tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if",
"License for the specific language governing permissions and # limitations under the License.",
"299 or example['image/width'] != 299: image = tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299, 299])",
"language governing permissions and # limitations under the License. # ============================================================================== \"\"\" Training",
"pixels + labels :return: \"\"\" feature_description = { 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded':",
"def __init__(self, log_dir, **kwargs): # add other arguments to __init__ if you need",
"fixed in next version #TODO: either set this to # of validation examples",
"to in writing, software # distributed under the License is distributed on an",
"main(): reqArgs = [ [\"i\", \"inputDir\", \"directory containing TFRecord files\"], [\"o\", \"outputDir\", \"directory",
"implied. # See the License for the specific language governing permissions and #",
"return [image, label] class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir, **kwargs): # add other arguments",
"[\"a\", \"algorithm\", \"adam, nadam, or rmsprop\"], ] optArgs = [ [\"m\", \"maxEpochs\", \"(optional)",
"exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir,",
"\"License\"); # you may not use this file except in compliance with the",
"image = tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299, 299]) image = tf.cast(image, tf.uint8) image",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"from __future__ import division from __future__ import print_function import os import sys from",
"tf.uint8) image = tf.reshape(image, [299, 299, 3]) #weird workaround because decode image doesnt",
"set this to # of validation examples /batch size (i.e. figure out num",
"collect_args from firecam.lib import goog_helper from firecam.lib import tf_helper import glob import tensorflow",
"0 if args.algorithm == \"adam\": # optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer",
"= raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception = tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) > 0 initial_epoch =",
"code using Keras for TF2 \"\"\" from __future__ import absolute_import from __future__ import",
"= os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start",
"epoch\", int], ] args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size = 64 max_epochs =",
"# optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm",
"super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self, epoch, logs=None): logs = logs or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)})",
"num validation examples) #or upgrade to TF2.1 when its ready and automatically go",
"ready and automatically go thorugh the whole set train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames",
"label = tf.one_hot(example['image/class/label'], depth=2) image = (tf.cast(image, tf.float32) - 128) / 128.0 return",
"datetime def _parse_function(example_proto): \"\"\" Function for converting TFRecordDataset to uncompressed image pixels +",
"files', len(train_filenames), len(val_filenames)) if (len(train_filenames) == 0) or (len(val_filenames) == 0): logging.error('Could not",
"Keras for TF2 \"\"\" from __future__ import absolute_import from __future__ import division from",
"= int(args.startEpoch) else: inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2) initial_epoch = 0 if",
"len(train_filenames), len(val_filenames)) if (len(train_filenames) == 0) or (len(val_filenames) == 0): logging.error('Could not find",
"or implied. # See the License for the specific language governing permissions and",
"__init__ if you need super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self, epoch, logs=None): logs = logs",
"batch_size = 64 max_epochs = args.maxEpochs if args.maxEpochs else 1000 steps_per_epoch = args.stepsPerEpoch",
"settings from firecam.lib import collect_args from firecam.lib import goog_helper from firecam.lib import tf_helper",
"epochs (default 1000)\", int], [\"r\", \"resumeModel\", \"resume training from given saved model\"], [\"s\",",
"import glob import tensorflow as tf from tensorflow import keras import logging import",
"(epoch from resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional) number of steps per epoch\", int], [\"v\",",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"\"resumeModel\", \"resume training from given saved model\"], [\"s\", \"startEpoch\", \"epoch to resume from",
"logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def main(): reqArgs = [ [\"i\", \"inputDir\", \"directory containing",
"find data in %s', args.inputDir) exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception",
"== \"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo %s', args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(),",
"firecam.lib import settings from firecam.lib import collect_args from firecam.lib import goog_helper from firecam.lib",
"include_top=True, input_tensor=None, classes=2) initial_epoch = 0 if args.algorithm == \"adam\": # optimizer =",
"args.algorithm == \"nadam\": optimizer = tf.keras.optimizers.Nadam() elif args.algorithm == \"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06)",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"example['image/height'] != 299 or example['image/width'] != 299: image = tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]),",
"in writing, software # distributed under the License is distributed on an \"AS",
"args.algorithm == \"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo %s', args.algorithm) exit(1) inception.compile(optimizer=optimizer,",
"default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), } # Parse the",
"%s', args.inputDir) exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs *",
"glob import tensorflow as tf from tensorflow import keras import logging import datetime",
"permissions and # limitations under the License. # ============================================================================== \"\"\" Training code using",
"tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm == \"nadam\": optimizer = tf.keras.optimizers.Nadam() elif args.algorithm == \"rmsprop\":",
"validation steps per epoch\", int], ] args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size =",
":return: \"\"\" feature_description = { 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''),",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"feature_description) image = tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing images in training set because they",
"= args.maxEpochs if args.maxEpochs else 1000 steps_per_epoch = args.stepsPerEpoch if args.stepsPerEpoch else 2000",
"/batch size (i.e. figure out num validation examples) #or upgrade to TF2.1 when",
"= [ [\"i\", \"inputDir\", \"directory containing TFRecord files\"], [\"o\", \"outputDir\", \"directory to write",
"# add other arguments to __init__ if you need super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self,",
"algo %s', args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks =",
"examples) #or upgrade to TF2.1 when its ready and automatically go thorugh the",
"logs\"], [\"a\", \"algorithm\", \"adam, nadam, or rmsprop\"], ] optArgs = [ [\"m\", \"maxEpochs\",",
"because of a bug in tf2.0, which should be fixed in next version",
"\"(optional) max number of epochs (default 1000)\", int], [\"r\", \"resumeModel\", \"resume training from",
"__future__ import division from __future__ import print_function import os import sys from firecam.lib",
"in next version #TODO: either set this to # of validation examples /batch",
"training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=val_steps, callbacks=callbacks) logging.warning('Done training') if __name__ ==",
"only needed for now because of a bug in tf2.0, which should be",
"logging import datetime def _parse_function(example_proto): \"\"\" Function for converting TFRecordDataset to uncompressed image",
"[\"m\", \"maxEpochs\", \"(optional) max number of epochs (default 1000)\", int], [\"r\", \"resumeModel\", \"resume",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([],",
"if you need super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self, epoch, logs=None): logs = logs or",
"inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2) initial_epoch = 0 if args.algorithm == \"adam\":",
"patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch,",
"tf.io.parse_single_example(example_proto, feature_description) image = tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing images in training set because",
"validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=val_steps, callbacks=callbacks) logging.warning('Done training') if __name__ == \"__main__\": main()",
"Parse the input `tf.Example` proto using the dictionary above. example = tf.io.parse_single_example(example_proto, feature_description)",
"add other arguments to __init__ if you need super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self, epoch,",
"int(args.startEpoch) else: inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2) initial_epoch = 0 if args.algorithm",
"from (epoch from resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional) number of steps per epoch\", int],",
"= [ [\"m\", \"maxEpochs\", \"(optional) max number of epochs (default 1000)\", int], [\"r\",",
"200 #val_steps only needed for now because of a bug in tf2.0, which",
"sys from firecam.lib import settings from firecam.lib import collect_args from firecam.lib import goog_helper",
"1000)\", int], [\"r\", \"resumeModel\", \"resume training from given saved model\"], [\"s\", \"startEpoch\", \"epoch",
"{} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def main(): reqArgs = [ [\"i\", \"inputDir\", \"directory",
"data in %s', args.inputDir) exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train =",
"firecam.lib import goog_helper from firecam.lib import tf_helper import glob import tensorflow as tf",
"#weird workaround because decode image doesnt get shape label = tf.one_hot(example['image/class/label'], depth=2) image",
"glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d training files, and %d validation files', len(train_filenames), len(val_filenames)) if",
"use this file except in compliance with the License. # You may obtain",
"\"adam, nadam, or rmsprop\"], ] optArgs = [ [\"m\", \"maxEpochs\", \"(optional) max number",
"'firecam_validation_*.tfrecord')) logging.warning('Found %d training files, and %d validation files', len(train_filenames), len(val_filenames)) if (len(train_filenames)",
"else: logging.error('Unsupported algo %s', args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))",
"image = (tf.cast(image, tf.float32) - 128) / 128.0 return [image, label] class LRTensorBoard(keras.callbacks.TensorBoard):",
"steps per epoch\", int], [\"v\", \"valStepsPerEpoch\", \"(optional) number of validation steps per epoch\",",
"tf.io.FixedLenFeature([], tf.int64, default_value=0), } # Parse the input `tf.Example` proto using the dictionary",
"[299, 299, 3]) #weird workaround because decode image doesnt get shape label =",
"else 2000 overshoot_epochs = 30 #number of epochs over which validation loss hasnt",
"logs) def main(): reqArgs = [ [\"i\", \"inputDir\", \"directory containing TFRecord files\"], [\"o\",",
"def on_epoch_end(self, epoch, logs=None): logs = logs or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs)",
"import collect_args from firecam.lib import goog_helper from firecam.lib import tf_helper import glob import",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"max number of epochs (default 1000)\", int], [\"r\", \"resumeModel\", \"resume training from given",
"epoch\", int], [\"v\", \"valStepsPerEpoch\", \"(optional) number of validation steps per epoch\", int], ]",
"from tensorflow import keras import logging import datetime def _parse_function(example_proto): \"\"\" Function for",
"validation examples) #or upgrade to TF2.1 when its ready and automatically go thorugh",
"\"\"\" Training code using Keras for TF2 \"\"\" from __future__ import absolute_import from",
"steps_per_epoch = args.stepsPerEpoch if args.stepsPerEpoch else 2000 overshoot_epochs = 30 #number of epochs",
"tf_helper import glob import tensorflow as tf from tensorflow import keras import logging",
"size (i.e. figure out num validation examples) #or upgrade to TF2.1 when its",
"specific language governing permissions and # limitations under the License. # ============================================================================== \"\"\"",
"[\"v\", \"valStepsPerEpoch\", \"(optional) number of validation steps per epoch\", int], ] args =",
"= (tf.cast(image, tf.float32) - 128) / 128.0 return [image, label] class LRTensorBoard(keras.callbacks.TensorBoard): def",
"val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d training files, and %d validation files', len(train_filenames),",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"print_function import os import sys from firecam.lib import settings from firecam.lib import collect_args",
"raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception = tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) > 0 initial_epoch = int(args.startEpoch)",
"else: inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2) initial_epoch = 0 if args.algorithm ==",
"= tf.keras.optimizers.Nadam() elif args.algorithm == \"rmsprop\": optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo %s',",
"for the specific language governing permissions and # limitations under the License. #",
"import logging import datetime def _parse_function(example_proto): \"\"\" Function for converting TFRecordDataset to uncompressed",
"Climate Tech Contributors # # Licensed under the Apache License, Version 2.0 (the",
"fo the time if example['image/height'] != 299 or example['image/width'] != 299: image =",
"saved model\"], [\"s\", \"startEpoch\", \"epoch to resume from (epoch from resumeModel)\"], [\"t\", \"stepsPerEpoch\",",
"be fixed in next version #TODO: either set this to # of validation",
"default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0),",
"299: image = tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299, 299]) image = tf.cast(image, tf.uint8)",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional) number of steps per epoch\", int], [\"v\", \"valStepsPerEpoch\", \"(optional)",
"= args.stepsPerEpoch if args.stepsPerEpoch else 2000 overshoot_epochs = 30 #number of epochs over",
"rectangular much fo the time if example['image/height'] != 299 or example['image/width'] != 299:",
"shape label = tf.one_hot(example['image/class/label'], depth=2) image = (tf.cast(image, tf.float32) - 128) / 128.0",
"= tf.one_hot(example['image/class/label'], depth=2) image = (tf.cast(image, tf.float32) - 128) / 128.0 return [image,",
"tensorboard logs\"], [\"a\", \"algorithm\", \"adam, nadam, or rmsprop\"], ] optArgs = [ [\"m\",",
"number of epochs (default 1000)\", int], [\"r\", \"resumeModel\", \"resume training from given saved",
"args.resumeModel: inception = tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) > 0 initial_epoch = int(args.startEpoch) else: inception",
"training files, and %d validation files', len(train_filenames), len(val_filenames)) if (len(train_filenames) == 0) or",
"input_tensor=None, classes=2) initial_epoch = 0 if args.algorithm == \"adam\": # optimizer = tf.keras.optimizers.Adam(learning_rate=0.001,",
"# # Unless required by applicable law or agreed to in writing, software",
"containing TFRecord files\"], [\"o\", \"outputDir\", \"directory to write out checkpoints and tensorboard logs\"],",
"args.valStepsPerEpoch else 200 #val_steps only needed for now because of a bug in",
"express or implied. # See the License for the specific language governing permissions",
"channels=3, dct_method='INTEGER_ACCURATE') #Resizing images in training set because they are apprently rectangular much",
"of steps per epoch\", int], [\"v\", \"valStepsPerEpoch\", \"(optional) number of validation steps per",
"tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), } #",
"using the dictionary above. example = tf.io.parse_single_example(example_proto, feature_description) image = tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE')",
"either express or implied. # See the License for the specific language governing",
"(tf.cast(image, tf.float32) - 128) / 128.0 return [image, label] class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self,",
"images in training set because they are apprently rectangular much fo the time",
"0): logging.error('Could not find data in %s', args.inputDir) exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val",
"%d training files, and %d validation files', len(train_filenames), len(val_filenames)) if (len(train_filenames) == 0)",
"image doesnt get shape label = tf.one_hot(example['image/class/label'], depth=2) image = (tf.cast(image, tf.float32) -",
"tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), } # Parse the input `tf.Example` proto",
"or example['image/width'] != 299: image = tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299, 299]) image",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"= { 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string,",
"label] class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir, **kwargs): # add other arguments to __init__",
"of validation steps per epoch\", int], ] args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size",
"== 0): logging.error('Could not find data in %s', args.inputDir) exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames)",
"the License. # You may obtain a copy of the License at #",
"= tf.cast(image, tf.uint8) image = tf.reshape(image, [299, 299, 3]) #weird workaround because decode",
"in tf2.0, which should be fixed in next version #TODO: either set this",
"over which validation loss hasnt decreased to stop training at val_steps = args.valStepsPerEpoch",
"import settings from firecam.lib import collect_args from firecam.lib import goog_helper from firecam.lib import",
"128.0 return [image, label] class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir, **kwargs): # add other",
"\"epoch to resume from (epoch from resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional) number of steps",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"log_dir, **kwargs): # add other arguments to __init__ if you need super().__init__(log_dir=log_dir, **kwargs)",
"tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), } # Parse",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"decreased to stop training at val_steps = args.valStepsPerEpoch if args.valStepsPerEpoch else 200 #val_steps",
"default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), } # Parse the input `tf.Example` proto using",
"\"\"\" feature_description = { 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format':",
"out num validation examples) #or upgrade to TF2.1 when its ready and automatically",
"training set because they are apprently rectangular much fo the time if example['image/height']",
"needed for now because of a bug in tf2.0, which should be fixed",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function import",
"299, 3]) #weird workaround because decode image doesnt get shape label = tf.one_hot(example['image/class/label'],",
"128) / 128.0 return [image, label] class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir, **kwargs): #",
"# Copyright 2020 Open Climate Tech Contributors # # Licensed under the Apache",
"= glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d training files, and %d",
"super().on_epoch_end(epoch, logs) def main(): reqArgs = [ [\"i\", \"inputDir\", \"directory containing TFRecord files\"],",
"(len(train_filenames) == 0) or (len(val_filenames) == 0): logging.error('Could not find data in %s',",
"= args.valStepsPerEpoch if args.valStepsPerEpoch else 200 #val_steps only needed for now because of",
"per epoch\", int], [\"v\", \"valStepsPerEpoch\", \"(optional) number of validation steps per epoch\", int],",
"\"directory containing TFRecord files\"], [\"o\", \"outputDir\", \"directory to write out checkpoints and tensorboard",
"with the License. # You may obtain a copy of the License at",
"out checkpoints and tensorboard logs\"], [\"a\", \"algorithm\", \"adam, nadam, or rmsprop\"], ] optArgs",
"collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size = 64 max_epochs = args.maxEpochs if args.maxEpochs else 1000",
"!= 299: image = tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299, 299]) image = tf.cast(image,",
"import tf_helper import glob import tensorflow as tf from tensorflow import keras import",
"figure out num validation examples) #or upgrade to TF2.1 when its ready and",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"parentParsers=[goog_helper.getParentParser()]) batch_size = 64 max_epochs = args.maxEpochs if args.maxEpochs else 1000 steps_per_epoch =",
"optArgs = [ [\"m\", \"maxEpochs\", \"(optional) max number of epochs (default 1000)\", int],",
"initial_epoch = int(args.startEpoch) else: inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2) initial_epoch = 0",
"steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception = tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch)",
"'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), } # Parse the input",
"and automatically go thorugh the whole set train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames =",
"== 0) or (len(val_filenames) == 0): logging.error('Could not find data in %s', args.inputDir)",
"and tensorboard logs\"], [\"a\", \"algorithm\", \"adam, nadam, or rmsprop\"], ] optArgs = [",
"at val_steps = args.valStepsPerEpoch if args.valStepsPerEpoch else 200 #val_steps only needed for now",
"go thorugh the whole set train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord'))",
"= [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss', save_best_only=True), LRTensorBoard(log_dir=logdir)] logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs,",
"\"\"\" Function for converting TFRecordDataset to uncompressed image pixels + labels :return: \"\"\"",
"logging.warning('Found %d training files, and %d validation files', len(train_filenames), len(val_filenames)) if (len(train_filenames) ==",
"write out checkpoints and tensorboard logs\"], [\"a\", \"algorithm\", \"adam, nadam, or rmsprop\"], ]",
"int(args.startEpoch) > 0 initial_epoch = int(args.startEpoch) else: inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2)",
"logs=None): logs = logs or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def main(): reqArgs",
"[\"i\", \"inputDir\", \"directory containing TFRecord files\"], [\"o\", \"outputDir\", \"directory to write out checkpoints",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir, **kwargs): # add other arguments to __init__ if",
"tf2.0, which should be fixed in next version #TODO: either set this to",
"either set this to # of validation examples /batch size (i.e. figure out",
"to uncompressed image pixels + labels :return: \"\"\" feature_description = { 'image/class/label': tf.io.FixedLenFeature([],",
"if (len(train_filenames) == 0) or (len(val_filenames) == 0): logging.error('Could not find data in",
"other arguments to __init__ if you need super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self, epoch, logs=None):",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"version #TODO: either set this to # of validation examples /batch size (i.e.",
"TFRecordDataset to uncompressed image pixels + labels :return: \"\"\" feature_description = { 'image/class/label':",
"tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val =",
"logging.error('Unsupported algo %s', args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks",
"dct_method='INTEGER_ACCURATE') #Resizing images in training set because they are apprently rectangular much fo",
"args.maxEpochs else 1000 steps_per_epoch = args.stepsPerEpoch if args.stepsPerEpoch else 2000 overshoot_epochs = 30",
"TFRecord files\"], [\"o\", \"outputDir\", \"directory to write out checkpoints and tensorboard logs\"], [\"a\",",
"loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'), monitor='val_loss',",
"beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm == \"nadam\": optimizer =",
"optimizer = tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo %s', args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir",
"inception = tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) > 0 initial_epoch = int(args.startEpoch) else: inception =",
"!= 299 or example['image/width'] != 299: image = tf.image.resize(tf.reshape(image, [example['image/height'], example['image/width'], 3]), [299,",
"args.inputDir) exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size",
"in compliance with the License. # You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"import division from __future__ import print_function import os import sys from firecam.lib import",
"#or upgrade to TF2.1 when its ready and automatically go thorugh the whole",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"[\"o\", \"outputDir\", \"directory to write out checkpoints and tensorboard logs\"], [\"a\", \"algorithm\", \"adam,",
"tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm == \"nadam\": optimizer",
"inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=val_steps, callbacks=callbacks) logging.warning('Done training') if __name__ == \"__main__\":",
"governing permissions and # limitations under the License. # ============================================================================== \"\"\" Training code",
"* 5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception = tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) >",
"tensorflow as tf from tensorflow import keras import logging import datetime def _parse_function(example_proto):",
"See the License for the specific language governing permissions and # limitations under",
"automatically go thorugh the whole set train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir,",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"given saved model\"], [\"s\", \"startEpoch\", \"epoch to resume from (epoch from resumeModel)\"], [\"t\",",
"int], ] args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size = 64 max_epochs = args.maxEpochs",
"0) or (len(val_filenames) == 0): logging.error('Could not find data in %s', args.inputDir) exit(1)",
"files, and %d validation files', len(train_filenames), len(val_filenames)) if (len(train_filenames) == 0) or (len(val_filenames)",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"Open Climate Tech Contributors # # Licensed under the Apache License, Version 2.0",
"_parse_function(example_proto): \"\"\" Function for converting TFRecordDataset to uncompressed image pixels + labels :return:",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"now because of a bug in tf2.0, which should be fixed in next",
"validation files', len(train_filenames), len(val_filenames)) if (len(train_filenames) == 0) or (len(val_filenames) == 0): logging.error('Could",
"__init__(self, log_dir, **kwargs): # add other arguments to __init__ if you need super().__init__(log_dir=log_dir,",
"of validation examples /batch size (i.e. figure out num validation examples) #or upgrade",
"License. # ============================================================================== \"\"\" Training code using Keras for TF2 \"\"\" from __future__",
"import sys from firecam.lib import settings from firecam.lib import collect_args from firecam.lib import",
"steps per epoch\", int], ] args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size = 64",
"\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function",
"= tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val",
"\"stepsPerEpoch\", \"(optional) number of steps per epoch\", int], [\"v\", \"valStepsPerEpoch\", \"(optional) number of",
"which validation loss hasnt decreased to stop training at val_steps = args.valStepsPerEpoch if",
"not find data in %s', args.inputDir) exit(1) raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames)",
"[\"t\", \"stepsPerEpoch\", \"(optional) number of steps per epoch\", int], [\"v\", \"valStepsPerEpoch\", \"(optional) number",
"\"directory to write out checkpoints and tensorboard logs\"], [\"a\", \"algorithm\", \"adam, nadam, or",
"overshoot_epochs = 30 #number of epochs over which validation loss hasnt decreased to",
"to resume from (epoch from resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional) number of steps per",
"= tf.io.parse_single_example(example_proto, feature_description) image = tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing images in training set",
"from resumeModel)\"], [\"t\", \"stepsPerEpoch\", \"(optional) number of steps per epoch\", int], [\"v\", \"valStepsPerEpoch\",",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"/ 128.0 return [image, label] class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir, **kwargs): # add",
"to TF2.1 when its ready and automatically go thorugh the whole set train_filenames",
"except in compliance with the License. # You may obtain a copy of",
"the specific language governing permissions and # limitations under the License. # ==============================================================================",
"get shape label = tf.one_hot(example['image/class/label'], depth=2) image = (tf.cast(image, tf.float32) - 128) /",
"tf.keras.optimizers.RMSprop(decay=1e-06) else: logging.error('Unsupported algo %s', args.algorithm) exit(1) inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir = os.path.join(args.outputDir,",
"number of validation steps per epoch\", int], ] args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()])",
"> 0 initial_epoch = int(args.startEpoch) else: inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True, input_tensor=None, classes=2) initial_epoch",
"#val_steps only needed for now because of a bug in tf2.0, which should",
"validation examples /batch size (i.e. figure out num validation examples) #or upgrade to",
"tf_helper.loadModel(args.resumeModel) assert int(args.startEpoch) > 0 initial_epoch = int(args.startEpoch) else: inception = keras.applications.inception_v3.InceptionV3(weights=None, include_top=True,",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64,",
"= tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm == \"nadam\":",
"the input `tf.Example` proto using the dictionary above. example = tf.io.parse_single_example(example_proto, feature_description) image",
"= raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size * 5).batch(batch_size) dataset_val = raw_dataset_val.map(_parse_function).repeat().batch(batch_size) if args.resumeModel: inception =",
"'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), }",
"keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def main(): reqArgs = [ [\"i\", \"inputDir\", \"directory containing TFRecord",
"+ labels :return: \"\"\" feature_description = { 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([],",
"== \"adam\": # optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True)",
"import absolute_import from __future__ import division from __future__ import print_function import os import",
"rmsprop\"], ] optArgs = [ [\"m\", \"maxEpochs\", \"(optional) max number of epochs (default",
"tf.image.decode_jpeg(example['image/encoded'], channels=3, dct_method='INTEGER_ACCURATE') #Resizing images in training set because they are apprently rectangular",
"to stop training at val_steps = args.valStepsPerEpoch if args.valStepsPerEpoch else 200 #val_steps only",
"**kwargs) def on_epoch_end(self, epoch, logs=None): logs = logs or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch,",
"raw_dataset_train = tf.data.TFRecordDataset(train_filenames) raw_dataset_val = tf.data.TFRecordDataset(val_filenames) dataset_train = raw_dataset_train.map(_parse_function).repeat(max_epochs * steps_per_epoch).shuffle(batch_size * 5).batch(batch_size)",
"int], [\"r\", \"resumeModel\", \"resume training from given saved model\"], [\"s\", \"startEpoch\", \"epoch to",
"elif args.algorithm == \"nadam\": optimizer = tf.keras.optimizers.Nadam() elif args.algorithm == \"rmsprop\": optimizer =",
"tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/height': tf.io.FixedLenFeature([], tf.int64,",
"from __future__ import print_function import os import sys from firecam.lib import settings from",
"import keras import logging import datetime def _parse_function(example_proto): \"\"\" Function for converting TFRecordDataset",
"- 128) / 128.0 return [image, label] class LRTensorBoard(keras.callbacks.TensorBoard): def __init__(self, log_dir, **kwargs):",
"args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size = 64 max_epochs = args.maxEpochs if args.maxEpochs",
"amsgrad=False) optimizer = tf.keras.optimizers.Adam(decay=1e-06, amsgrad=True) elif args.algorithm == \"nadam\": optimizer = tf.keras.optimizers.Nadam() elif",
"or (len(val_filenames) == 0): logging.error('Could not find data in %s', args.inputDir) exit(1) raw_dataset_train",
"per epoch\", int], ] args = collect_args.collectArgs(reqArgs, optionalArgs=optArgs, parentParsers=[goog_helper.getParentParser()]) batch_size = 64 max_epochs",
"to __init__ if you need super().__init__(log_dir=log_dir, **kwargs) def on_epoch_end(self, epoch, logs=None): logs =",
"**kwargs): # add other arguments to __init__ if you need super().__init__(log_dir=log_dir, **kwargs) def",
"the time if example['image/height'] != 299 or example['image/width'] != 299: image = tf.image.resize(tf.reshape(image,",
"logging.warning('Start training') inception.fit(dataset_train, validation_data=dataset_val, epochs=max_epochs, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=val_steps, callbacks=callbacks) logging.warning('Done training') if __name__",
"inception.compile(optimizer=optimizer, loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy']) logdir = os.path.join(args.outputDir, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")) callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', patience=overshoot_epochs), keras.callbacks.ModelCheckpoint(filepath=os.path.join(args.outputDir, 'model_{epoch}'),",
"because decode image doesnt get shape label = tf.one_hot(example['image/class/label'], depth=2) image = (tf.cast(image,",
"import goog_helper from firecam.lib import tf_helper import glob import tensorflow as tf from",
"on_epoch_end(self, epoch, logs=None): logs = logs or {} logs.update({'lr': keras.backend.eval(self.model.optimizer.lr)}) super().on_epoch_end(epoch, logs) def",
"if args.maxEpochs else 1000 steps_per_epoch = args.stepsPerEpoch if args.stepsPerEpoch else 2000 overshoot_epochs =",
"whole set train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d training",
"from firecam.lib import goog_helper from firecam.lib import tf_helper import glob import tensorflow as",
"initial_epoch = 0 if args.algorithm == \"adam\": # optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999,",
"from firecam.lib import collect_args from firecam.lib import goog_helper from firecam.lib import tf_helper import",
"limitations under the License. # ============================================================================== \"\"\" Training code using Keras for TF2",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"uncompressed image pixels + labels :return: \"\"\" feature_description = { 'image/class/label': tf.io.FixedLenFeature([], tf.int64,",
"train_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_train_*.tfrecord')) val_filenames = glob.glob(os.path.join(args.inputDir, 'firecam_validation_*.tfrecord')) logging.warning('Found %d training files, and",
"TF2.1 when its ready and automatically go thorugh the whole set train_filenames =",
"(default 1000)\", int], [\"r\", \"resumeModel\", \"resume training from given saved model\"], [\"s\", \"startEpoch\",",
"of epochs over which validation loss hasnt decreased to stop training at val_steps"
] |
[
"Documentation', author, 'dotapatch', 'Parses Dota 2 text patches to html format.', 'Miscellaneous'), ]",
"sys import path import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions = [",
"sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon']",
"path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path",
"created by # sphinx-quickstart on Thu Jan 4 11:19:55 2018. from os.path import",
"from os.path import abspath from sys import path import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx",
"'<NAME>', 'manual'), ] man_pages = [ (master_doc, 'dotapatch', 'dotapatch Documentation', [author], 1) ]",
"'sphinx.ext.napoleon'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'dotapatch'",
"html_static_path = ['_static'] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme_options = { 'logo_only': True, 'display_version': False",
"by # sphinx-quickstart on Thu Jan 4 11:19:55 2018. from os.path import abspath",
"'dotapatch.tex', 'dotapatch Documentation', '<NAME>', 'manual'), ] man_pages = [ (master_doc, 'dotapatch', 'dotapatch Documentation',",
"from sys import path import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions =",
"format.', 'Miscellaneous'), ] html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme_options",
"= [ (master_doc, 'dotapatch.tex', 'dotapatch Documentation', '<NAME>', 'manual'), ] man_pages = [ (master_doc,",
"author, 'dotapatch', 'Parses Dota 2 text patches to html format.', 'Miscellaneous'), ] html_theme",
"import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx',",
"11:19:55 2018. from os.path import abspath from sys import path import sphinx_rtd_theme path.insert(0,",
"'.rst' master_doc = 'index' project = 'dotapatch' copyright = '2016, <NAME>' author =",
"python3 # coding: utf-8 # dotapatch documentation build configuration file, created by #",
"<NAME>' author = '<NAME>' version = '2.4' release = '2.4.4' pygments_style = 'sphinx'",
"] man_pages = [ (master_doc, 'dotapatch', 'dotapatch Documentation', [author], 1) ] exclude_patterns =",
"] html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme_options = {",
"= 'sphinx_rtd_theme' html_static_path = ['_static'] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme_options = { 'logo_only': True,",
"Documentation', [author], 1) ] exclude_patterns = [] language = None gettext_compact = False",
"= [ (master_doc, 'dotapatch', 'dotapatch Documentation', author, 'dotapatch', 'Parses Dota 2 text patches",
"sphinx-quickstart on Thu Jan 4 11:19:55 2018. from os.path import abspath from sys",
"Thu Jan 4 11:19:55 2018. from os.path import abspath from sys import path",
"configuration file, created by # sphinx-quickstart on Thu Jan 4 11:19:55 2018. from",
"'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index'",
"= ['_static'] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme_options = { 'logo_only': True, 'display_version': False }",
"language = None gettext_compact = False texinfo_documents = [ (master_doc, 'dotapatch', 'dotapatch Documentation',",
"'2.4' release = '2.4.4' pygments_style = 'sphinx' intersphinx_mapping = {'https://docs.python.org/3': None} htmlhelp_basename =",
"[ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path = ['_templates'] source_suffix = '.rst' master_doc =",
"4 11:19:55 2018. from os.path import abspath from sys import path import sphinx_rtd_theme",
"extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path = ['_templates'] source_suffix = '.rst'",
"Jan 4 11:19:55 2018. from os.path import abspath from sys import path import",
"= None gettext_compact = False texinfo_documents = [ (master_doc, 'dotapatch', 'dotapatch Documentation', author,",
"'Parses Dota 2 text patches to html format.', 'Miscellaneous'), ] html_theme = 'sphinx_rtd_theme'",
"= ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'dotapatch' copyright =",
"pygments_style = 'sphinx' intersphinx_mapping = {'https://docs.python.org/3': None} htmlhelp_basename = 'dotapatchdoc' latex_documents = [",
"# sphinx-quickstart on Thu Jan 4 11:19:55 2018. from os.path import abspath from",
"None} htmlhelp_basename = 'dotapatchdoc' latex_documents = [ (master_doc, 'dotapatch.tex', 'dotapatch Documentation', '<NAME>', 'manual'),",
"man_pages = [ (master_doc, 'dotapatch', 'dotapatch Documentation', [author], 1) ] exclude_patterns = []",
"htmlhelp_basename = 'dotapatchdoc' latex_documents = [ (master_doc, 'dotapatch.tex', 'dotapatch Documentation', '<NAME>', 'manual'), ]",
"(master_doc, 'dotapatch', 'dotapatch Documentation', author, 'dotapatch', 'Parses Dota 2 text patches to html",
"'dotapatch Documentation', [author], 1) ] exclude_patterns = [] language = None gettext_compact =",
"Documentation', '<NAME>', 'manual'), ] man_pages = [ (master_doc, 'dotapatch', 'dotapatch Documentation', [author], 1)",
"[ (master_doc, 'dotapatch.tex', 'dotapatch Documentation', '<NAME>', 'manual'), ] man_pages = [ (master_doc, 'dotapatch',",
"'manual'), ] man_pages = [ (master_doc, 'dotapatch', 'dotapatch Documentation', [author], 1) ] exclude_patterns",
"text patches to html format.', 'Miscellaneous'), ] html_theme = 'sphinx_rtd_theme' html_static_path = ['_static']",
"'<NAME>' version = '2.4' release = '2.4.4' pygments_style = 'sphinx' intersphinx_mapping = {'https://docs.python.org/3':",
"author = '<NAME>' version = '2.4' release = '2.4.4' pygments_style = 'sphinx' intersphinx_mapping",
"= '1.6.5' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path = ['_templates'] source_suffix",
"'dotapatch Documentation', author, 'dotapatch', 'Parses Dota 2 text patches to html format.', 'Miscellaneous'),",
"file, created by # sphinx-quickstart on Thu Jan 4 11:19:55 2018. from os.path",
"# coding: utf-8 # dotapatch documentation build configuration file, created by # sphinx-quickstart",
"= '.rst' master_doc = 'index' project = 'dotapatch' copyright = '2016, <NAME>' author",
"{'https://docs.python.org/3': None} htmlhelp_basename = 'dotapatchdoc' latex_documents = [ (master_doc, 'dotapatch.tex', 'dotapatch Documentation', '<NAME>',",
"abspath('..')) needs_sphinx = '1.6.5' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path =",
"[ (master_doc, 'dotapatch', 'dotapatch Documentation', author, 'dotapatch', 'Parses Dota 2 text patches to",
"coding: utf-8 # dotapatch documentation build configuration file, created by # sphinx-quickstart on",
"gettext_compact = False texinfo_documents = [ (master_doc, 'dotapatch', 'dotapatch Documentation', author, 'dotapatch', 'Parses",
"'1.6.5' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path = ['_templates'] source_suffix =",
"abspath from sys import path import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions",
"master_doc = 'index' project = 'dotapatch' copyright = '2016, <NAME>' author = '<NAME>'",
"[ (master_doc, 'dotapatch', 'dotapatch Documentation', [author], 1) ] exclude_patterns = [] language =",
"1) ] exclude_patterns = [] language = None gettext_compact = False texinfo_documents =",
"utf-8 # dotapatch documentation build configuration file, created by # sphinx-quickstart on Thu",
"'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project =",
"'dotapatch Documentation', '<NAME>', 'manual'), ] man_pages = [ (master_doc, 'dotapatch', 'dotapatch Documentation', [author],",
"patches to html format.', 'Miscellaneous'), ] html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] html_theme_path",
"source_suffix = '.rst' master_doc = 'index' project = 'dotapatch' copyright = '2016, <NAME>'",
"= '2.4' release = '2.4.4' pygments_style = 'sphinx' intersphinx_mapping = {'https://docs.python.org/3': None} htmlhelp_basename",
"2018. from os.path import abspath from sys import path import sphinx_rtd_theme path.insert(0, abspath('..'))",
"version = '2.4' release = '2.4.4' pygments_style = 'sphinx' intersphinx_mapping = {'https://docs.python.org/3': None}",
"latex_documents = [ (master_doc, 'dotapatch.tex', 'dotapatch Documentation', '<NAME>', 'manual'), ] man_pages = [",
"os.path import abspath from sys import path import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx =",
"= {'https://docs.python.org/3': None} htmlhelp_basename = 'dotapatchdoc' latex_documents = [ (master_doc, 'dotapatch.tex', 'dotapatch Documentation',",
"to html format.', 'Miscellaneous'), ] html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] html_theme_path =",
"templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'dotapatch' copyright",
"False texinfo_documents = [ (master_doc, 'dotapatch', 'dotapatch Documentation', author, 'dotapatch', 'Parses Dota 2",
"= [ (master_doc, 'dotapatch', 'dotapatch Documentation', [author], 1) ] exclude_patterns = [] language",
"'Miscellaneous'), ] html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme_options =",
"copyright = '2016, <NAME>' author = '<NAME>' version = '2.4' release = '2.4.4'",
"= [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path = ['_templates'] source_suffix = '.rst' master_doc",
"<filename>docs/conf.py #!/usr/bin/env python3 # coding: utf-8 # dotapatch documentation build configuration file, created",
"= '2.4.4' pygments_style = 'sphinx' intersphinx_mapping = {'https://docs.python.org/3': None} htmlhelp_basename = 'dotapatchdoc' latex_documents",
"build configuration file, created by # sphinx-quickstart on Thu Jan 4 11:19:55 2018.",
"= 'index' project = 'dotapatch' copyright = '2016, <NAME>' author = '<NAME>' version",
"intersphinx_mapping = {'https://docs.python.org/3': None} htmlhelp_basename = 'dotapatchdoc' latex_documents = [ (master_doc, 'dotapatch.tex', 'dotapatch",
"dotapatch documentation build configuration file, created by # sphinx-quickstart on Thu Jan 4",
"(master_doc, 'dotapatch', 'dotapatch Documentation', [author], 1) ] exclude_patterns = [] language = None",
"'dotapatch' copyright = '2016, <NAME>' author = '<NAME>' version = '2.4' release =",
"needs_sphinx = '1.6.5' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path = ['_templates']",
"'sphinx' intersphinx_mapping = {'https://docs.python.org/3': None} htmlhelp_basename = 'dotapatchdoc' latex_documents = [ (master_doc, 'dotapatch.tex',",
"[author], 1) ] exclude_patterns = [] language = None gettext_compact = False texinfo_documents",
"= 'dotapatchdoc' latex_documents = [ (master_doc, 'dotapatch.tex', 'dotapatch Documentation', '<NAME>', 'manual'), ] man_pages",
"import abspath from sys import path import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5'",
"] exclude_patterns = [] language = None gettext_compact = False texinfo_documents = [",
"= 'dotapatch' copyright = '2016, <NAME>' author = '<NAME>' version = '2.4' release",
"None gettext_compact = False texinfo_documents = [ (master_doc, 'dotapatch', 'dotapatch Documentation', author, 'dotapatch',",
"[] language = None gettext_compact = False texinfo_documents = [ (master_doc, 'dotapatch', 'dotapatch",
"'2.4.4' pygments_style = 'sphinx' intersphinx_mapping = {'https://docs.python.org/3': None} htmlhelp_basename = 'dotapatchdoc' latex_documents =",
"'2016, <NAME>' author = '<NAME>' version = '2.4' release = '2.4.4' pygments_style =",
"'dotapatch', 'dotapatch Documentation', [author], 1) ] exclude_patterns = [] language = None gettext_compact",
"'dotapatchdoc' latex_documents = [ (master_doc, 'dotapatch.tex', 'dotapatch Documentation', '<NAME>', 'manual'), ] man_pages =",
"# dotapatch documentation build configuration file, created by # sphinx-quickstart on Thu Jan",
"= '<NAME>' version = '2.4' release = '2.4.4' pygments_style = 'sphinx' intersphinx_mapping =",
"= '2016, <NAME>' author = '<NAME>' version = '2.4' release = '2.4.4' pygments_style",
"on Thu Jan 4 11:19:55 2018. from os.path import abspath from sys import",
"release = '2.4.4' pygments_style = 'sphinx' intersphinx_mapping = {'https://docs.python.org/3': None} htmlhelp_basename = 'dotapatchdoc'",
"(master_doc, 'dotapatch.tex', 'dotapatch Documentation', '<NAME>', 'manual'), ] man_pages = [ (master_doc, 'dotapatch', 'dotapatch",
"= [] language = None gettext_compact = False texinfo_documents = [ (master_doc, 'dotapatch',",
"import path import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions = [ 'sphinx.ext.autodoc',",
"['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'dotapatch' copyright = '2016,",
"'dotapatch', 'Parses Dota 2 text patches to html format.', 'Miscellaneous'), ] html_theme =",
"2 text patches to html format.', 'Miscellaneous'), ] html_theme = 'sphinx_rtd_theme' html_static_path =",
"= False texinfo_documents = [ (master_doc, 'dotapatch', 'dotapatch Documentation', author, 'dotapatch', 'Parses Dota",
"documentation build configuration file, created by # sphinx-quickstart on Thu Jan 4 11:19:55",
"'index' project = 'dotapatch' copyright = '2016, <NAME>' author = '<NAME>' version =",
"path import sphinx_rtd_theme path.insert(0, abspath('..')) needs_sphinx = '1.6.5' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode',",
"'sphinx_rtd_theme' html_static_path = ['_static'] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme_options = { 'logo_only': True, 'display_version':",
"html format.', 'Miscellaneous'), ] html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]",
"#!/usr/bin/env python3 # coding: utf-8 # dotapatch documentation build configuration file, created by",
"project = 'dotapatch' copyright = '2016, <NAME>' author = '<NAME>' version = '2.4'",
"'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project",
"= 'sphinx' intersphinx_mapping = {'https://docs.python.org/3': None} htmlhelp_basename = 'dotapatchdoc' latex_documents = [ (master_doc,",
"Dota 2 text patches to html format.', 'Miscellaneous'), ] html_theme = 'sphinx_rtd_theme' html_static_path",
"exclude_patterns = [] language = None gettext_compact = False texinfo_documents = [ (master_doc,",
"html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme_options = { 'logo_only':",
"texinfo_documents = [ (master_doc, 'dotapatch', 'dotapatch Documentation', author, 'dotapatch', 'Parses Dota 2 text",
"'dotapatch', 'dotapatch Documentation', author, 'dotapatch', 'Parses Dota 2 text patches to html format.',"
] |
[
"# Generated by Django 3.0.9 on 2020-08-23 12:27 from django.db import migrations class",
"3.0.9 on 2020-08-23 12:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20200823_1340'), ] operations = [ migrations.DeleteModel( name='addPost', ),",
"12:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20200823_1340'), ]",
"migrations class Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20200823_1340'), ] operations = [ migrations.DeleteModel(",
"Generated by Django 3.0.9 on 2020-08-23 12:27 from django.db import migrations class Migration(migrations.Migration):",
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20200823_1340'), ] operations =",
"class Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20200823_1340'), ] operations = [ migrations.DeleteModel( name='addPost',",
"on 2020-08-23 12:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home',",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20200823_1340'), ] operations",
"dependencies = [ ('home', '0007_auto_20200823_1340'), ] operations = [ migrations.DeleteModel( name='addPost', ), ]",
"import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20200823_1340'), ] operations = [",
"2020-08-23 12:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20200823_1340'),",
"by Django 3.0.9 on 2020-08-23 12:27 from django.db import migrations class Migration(migrations.Migration): dependencies",
"Django 3.0.9 on 2020-08-23 12:27 from django.db import migrations class Migration(migrations.Migration): dependencies ="
] |
[
"energy.\") print(f\"Current energy: {energy}.\") elif order == \"order\": if energy >= 30: energy",
"coins > 0: print(f\"You bought {order}.\") else: print(f\"Closed! Cannot afford {order}.\") break if",
"> 0: print(f\"You bought {order}.\") else: print(f\"Closed! Cannot afford {order}.\") break if coins",
"100 coins = 100 for el in range(len(events)): string = events[el] order, value",
"else: if coins > 0: coins -= value if coins > 0: print(f\"You",
"+= value if energy > 100: energy = 100 difference = 100 -",
"\"order\": if energy >= 30: energy -= 30 coins += value print(f\"You earned",
"100: energy = 100 difference = 100 - energy print(f\"You gained {difference} energy.\")",
"= input().split(\"|\") energy = 100 coins = 100 for el in range(len(events)): string",
"{difference} energy.\") print(f\"Current energy: {energy}.\") else: print(f\"You gained {value} energy.\") print(f\"Current energy: {energy}.\")",
"- energy print(f\"You gained {difference} energy.\") print(f\"Current energy: {energy}.\") else: print(f\"You gained {value}",
"if energy >= 30: energy -= 30 coins += value print(f\"You earned {value}",
"coins > 0: coins -= value if coins > 0: print(f\"You bought {order}.\")",
"value print(f\"You earned {value} coins.\") else: energy += 50 print(f\"You had to rest!\")",
"earned {value} coins.\") else: energy += 50 print(f\"You had to rest!\") else: if",
"print(f\"You gained {difference} energy.\") print(f\"Current energy: {energy}.\") else: print(f\"You gained {value} energy.\") print(f\"Current",
"value = int(value) if order == \"rest\": energy += value if energy >",
"= int(value) if order == \"rest\": energy += value if energy > 100:",
"string = events[el] order, value = string.split(\"-\") value = int(value) if order ==",
"energy: {energy}.\") elif order == \"order\": if energy >= 30: energy -= 30",
"print(f\"You had to rest!\") else: if coins > 0: coins -= value if",
"= 100 difference = 100 - energy print(f\"You gained {difference} energy.\") print(f\"Current energy:",
"int(value) if order == \"rest\": energy += value if energy > 100: energy",
"0: coins -= value if coins > 0: print(f\"You bought {order}.\") else: print(f\"Closed!",
"{order}.\") else: print(f\"Closed! Cannot afford {order}.\") break if coins > 0: print(f\"\"\"Day completed!",
"had to rest!\") else: if coins > 0: coins -= value if coins",
"order, value = string.split(\"-\") value = int(value) if order == \"rest\": energy +=",
"30: energy -= 30 coins += value print(f\"You earned {value} coins.\") else: energy",
"coins += value print(f\"You earned {value} coins.\") else: energy += 50 print(f\"You had",
"{value} coins.\") else: energy += 50 print(f\"You had to rest!\") else: if coins",
"events[el] order, value = string.split(\"-\") value = int(value) if order == \"rest\": energy",
"value = string.split(\"-\") value = int(value) if order == \"rest\": energy += value",
"afford {order}.\") break if coins > 0: print(f\"\"\"Day completed! Coins: {coins} Energy: {energy}\"\"\")",
"= events[el] order, value = string.split(\"-\") value = int(value) if order == \"rest\":",
"coins.\") else: energy += 50 print(f\"You had to rest!\") else: if coins >",
"100 - energy print(f\"You gained {difference} energy.\") print(f\"Current energy: {energy}.\") else: print(f\"You gained",
"> 0: coins -= value if coins > 0: print(f\"You bought {order}.\") else:",
"events = input().split(\"|\") energy = 100 coins = 100 for el in range(len(events)):",
"difference = 100 - energy print(f\"You gained {difference} energy.\") print(f\"Current energy: {energy}.\") else:",
"rest!\") else: if coins > 0: coins -= value if coins > 0:",
"coins = 100 for el in range(len(events)): string = events[el] order, value =",
"for el in range(len(events)): string = events[el] order, value = string.split(\"-\") value =",
"to rest!\") else: if coins > 0: coins -= value if coins >",
"value if coins > 0: print(f\"You bought {order}.\") else: print(f\"Closed! Cannot afford {order}.\")",
"if energy > 100: energy = 100 difference = 100 - energy print(f\"You",
"energy >= 30: energy -= 30 coins += value print(f\"You earned {value} coins.\")",
"range(len(events)): string = events[el] order, value = string.split(\"-\") value = int(value) if order",
"if coins > 0: print(f\"You bought {order}.\") else: print(f\"Closed! Cannot afford {order}.\") break",
"print(f\"You earned {value} coins.\") else: energy += 50 print(f\"You had to rest!\") else:",
"100 difference = 100 - energy print(f\"You gained {difference} energy.\") print(f\"Current energy: {energy}.\")",
">= 30: energy -= 30 coins += value print(f\"You earned {value} coins.\") else:",
"= 100 for el in range(len(events)): string = events[el] order, value = string.split(\"-\")",
"Cannot afford {order}.\") break if coins > 0: print(f\"\"\"Day completed! Coins: {coins} Energy:",
"{order}.\") break if coins > 0: print(f\"\"\"Day completed! Coins: {coins} Energy: {energy}\"\"\") #",
"= string.split(\"-\") value = int(value) if order == \"rest\": energy += value if",
"else: print(f\"You gained {value} energy.\") print(f\"Current energy: {energy}.\") elif order == \"order\": if",
"energy: {energy}.\") else: print(f\"You gained {value} energy.\") print(f\"Current energy: {energy}.\") elif order ==",
"else: print(f\"Closed! Cannot afford {order}.\") break if coins > 0: print(f\"\"\"Day completed! Coins:",
"coins -= value if coins > 0: print(f\"You bought {order}.\") else: print(f\"Closed! Cannot",
"order == \"order\": if energy >= 30: energy -= 30 coins += value",
"order == \"rest\": energy += value if energy > 100: energy = 100",
"bought {order}.\") else: print(f\"Closed! Cannot afford {order}.\") break if coins > 0: print(f\"\"\"Day",
"energy -= 30 coins += value print(f\"You earned {value} coins.\") else: energy +=",
"print(f\"You gained {value} energy.\") print(f\"Current energy: {energy}.\") elif order == \"order\": if energy",
"value if energy > 100: energy = 100 difference = 100 - energy",
"== \"rest\": energy += value if energy > 100: energy = 100 difference",
"print(f\"Current energy: {energy}.\") else: print(f\"You gained {value} energy.\") print(f\"Current energy: {energy}.\") elif order",
"if coins > 0: coins -= value if coins > 0: print(f\"You bought",
"el in range(len(events)): string = events[el] order, value = string.split(\"-\") value = int(value)",
"gained {value} energy.\") print(f\"Current energy: {energy}.\") elif order == \"order\": if energy >=",
"energy = 100 coins = 100 for el in range(len(events)): string = events[el]",
"energy += 50 print(f\"You had to rest!\") else: if coins > 0: coins",
"else: energy += 50 print(f\"You had to rest!\") else: if coins > 0:",
"0: print(f\"You bought {order}.\") else: print(f\"Closed! Cannot afford {order}.\") break if coins >",
"gained {difference} energy.\") print(f\"Current energy: {energy}.\") else: print(f\"You gained {value} energy.\") print(f\"Current energy:",
"energy = 100 difference = 100 - energy print(f\"You gained {difference} energy.\") print(f\"Current",
"30 coins += value print(f\"You earned {value} coins.\") else: energy += 50 print(f\"You",
"if order == \"rest\": energy += value if energy > 100: energy =",
"in range(len(events)): string = events[el] order, value = string.split(\"-\") value = int(value) if",
"energy print(f\"You gained {difference} energy.\") print(f\"Current energy: {energy}.\") else: print(f\"You gained {value} energy.\")",
"print(f\"You bought {order}.\") else: print(f\"Closed! Cannot afford {order}.\") break if coins > 0:",
"+= value print(f\"You earned {value} coins.\") else: energy += 50 print(f\"You had to",
"energy.\") print(f\"Current energy: {energy}.\") else: print(f\"You gained {value} energy.\") print(f\"Current energy: {energy}.\") elif",
"input().split(\"|\") energy = 100 coins = 100 for el in range(len(events)): string =",
"print(f\"Current energy: {energy}.\") elif order == \"order\": if energy >= 30: energy -=",
"50 print(f\"You had to rest!\") else: if coins > 0: coins -= value",
"-= value if coins > 0: print(f\"You bought {order}.\") else: print(f\"Closed! Cannot afford",
"{energy}.\") elif order == \"order\": if energy >= 30: energy -= 30 coins",
"-= 30 coins += value print(f\"You earned {value} coins.\") else: energy += 50",
"{value} energy.\") print(f\"Current energy: {energy}.\") elif order == \"order\": if energy >= 30:",
"{energy}.\") else: print(f\"You gained {value} energy.\") print(f\"Current energy: {energy}.\") elif order == \"order\":",
"energy += value if energy > 100: energy = 100 difference = 100",
"= 100 coins = 100 for el in range(len(events)): string = events[el] order,",
"> 100: energy = 100 difference = 100 - energy print(f\"You gained {difference}",
"= 100 - energy print(f\"You gained {difference} energy.\") print(f\"Current energy: {energy}.\") else: print(f\"You",
"break if coins > 0: print(f\"\"\"Day completed! Coins: {coins} Energy: {energy}\"\"\") # rest-2|order-10|eggs-100|rest-10",
"string.split(\"-\") value = int(value) if order == \"rest\": energy += value if energy",
"print(f\"Closed! Cannot afford {order}.\") break if coins > 0: print(f\"\"\"Day completed! Coins: {coins}",
"energy > 100: energy = 100 difference = 100 - energy print(f\"You gained",
"100 for el in range(len(events)): string = events[el] order, value = string.split(\"-\") value",
"== \"order\": if energy >= 30: energy -= 30 coins += value print(f\"You",
"+= 50 print(f\"You had to rest!\") else: if coins > 0: coins -=",
"elif order == \"order\": if energy >= 30: energy -= 30 coins +=",
"\"rest\": energy += value if energy > 100: energy = 100 difference ="
] |
[
"string.ascii_lowercase + string.digits)for i in range(N)) return gen_password def create_credential(user_name,site_name,account_name,password): ''' function that",
"print('Enter the name of site to be deleted') delete_account = input() if find_by_site_name(delete_account):",
"Welcome to Password-locker.') while True: print(' ') print(\"-\"*30) print( 'Use the guide codes",
"a credential by name ''' return Credentials.find_by_site_name(site_name) def main(): print(' ') print('Hi! Welcome",
"create_user(fname, lname, password): ''' Function to create a new user account ''' new_user",
"Function to copy a credentials details to the clipboard ''' return Credentials.copy_credentials(site_name) def",
"name- ').strip() password = str(input('Enter your password - ')) user_exists = verify_user(user_name, password)",
"save_user(create_user(first_name, last_name, password)) print(\" \") print( f'New Account Created for: {first_name} {last_name} with",
"print(\" \") print(f'Goodbye {user_name}') break elif short_code == 'cc': print(' ') print('Enter your",
"{last_name} with password: {password}') elif short_code == 'li': print(\"-\"*30) print(' ') print('To login,enter",
"range(N)) return gen_password def create_credential(user_name,site_name,account_name,password): ''' function that creates new credential ''' new_credential",
"break elif psw_choice == 'gp': password = generate_password() break elif psw_choice == 'ex':",
"choose: \\n ca-Create an Account \\n li-Log In \\n ex-Exit') short_code = input('Enter",
"''' new_user = User(fname, lname, password) return new_user def save_user(user): ''' function to",
"password \\n gp-generate a password \\n ex-exit') psw_choice = input('Enter an option: ').lower().strip()",
"''' Credentials.save_credentials(credential) def display_credential(user_name): ''' Function to display credentials saved by a user",
"new account:') first_name = input('Enter your first name- \\n').strip() last_name = input('Enter your",
"print(' ') print('Enter your credential details:') site_name = input('Enter the site\\'s name-').strip() account_name",
"name-').strip() while True: print(' ') print(\"-\"*30) print('Please choose an option for entering a",
"name- \\n').strip() password = input('Enter your password \\n').strip() save_user(create_user(first_name, last_name, password)) print(\" \")",
"list of all your credentials') print(' ') for credential in display_credential(user_name): print(f'Site Name:",
"') print( f'Credential created: Site Name:{site_name} - Account Name: {account_name} - Password:{password}') print('",
"login,enter your account details: ') user_name = input('Enter your first name- ').strip() password",
"Credentials(user_name,site_name,account_name,password) return new_credential def save_credential(credential): ''' function to save a credential ''' Credentials.save_credentials(credential)",
"credential password to copy: ') copy_credentials(chosen_site) print('') elif short_code == 'dl': print('Enter the",
"ex-Exit') short_code = input('Enter a choice: ').lower().strip() if short_code == 'ex': break elif",
"account:') first_name = input('Enter your first name- \\n').strip() last_name = input('Enter your last",
"option to continue.') print(' ') while True: print(\"-\"*30) print('Navigation codes: \\n cc-Create a",
"find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry account not matched') else: print('Wrong option entered. Retry') else:",
"new_credential def save_credential(credential): ''' function to save a credential ''' Credentials.save_credentials(credential) def display_credential(user_name):",
"your password: ').strip() break elif psw_choice == 'gp': password = generate_password() break elif",
"break elif psw_choice == 'ex': break else: print('Wrong option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print('",
"Name: {credential.site_name} - Account Name: {credential.account_name} - Password{<PASSWORD>}') print(' ') elif short_code ==",
"''' checking_user = Credentials.check_user(first_name, password) return checking_user def generate_password(): ''' function that generates",
"elif psw_choice == 'ex': break else: print('Wrong option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ')",
"{first_name} {last_name} with password: {password}') elif short_code == 'li': print(\"-\"*30) print(' ') print('To",
"details to the clipboard ''' return Credentials.copy_credentials(site_name) def delete_credential(credential): ''' function that deletes",
"return new_credential def save_credential(credential): ''' function to save a credential ''' Credentials.save_credentials(credential) def",
"password = input('Enter your password \\n').strip() save_user(create_user(first_name, last_name, password)) print(\" \") print( f'New",
"new_user = User(fname, lname, password) return new_user def save_user(user): ''' function to save",
"break elif short_code == 'cc': print(' ') print('Enter your credential details:') site_name =",
"elif short_code == 'li': print(\"-\"*30) print(' ') print('To login,enter your account details: ')",
"password) return new_user def save_user(user): ''' function to save user ''' User.save_user(user) def",
"a Credential \\n dc-Display Credentials \\n dl-Delete \\n copy-Copy Password \\n ex-Exit') short_code",
"by name ''' return Credentials.find_by_site_name(site_name) def main(): print(' ') print('Hi! Welcome to Password-locker.')",
"account\\'s name-').strip() while True: print(' ') print(\"-\"*30) print('Please choose an option for entering",
"saved by a user ''' return Credentials.display_credentials(user_name) def copy_credentials(site_name): ''' Function to copy",
"be deleted') delete_account = input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry account not matched')",
"choose an option for entering a password: \\n ep-enter existing password \\n gp-generate",
"= ''.join(secrets.choice( string.ascii_lowercase + string.digits)for i in range(N)) return gen_password def create_credential(user_name,site_name,account_name,password): '''",
"verify_user(user_name, password) if user_exists == user_name: print( f'Welcome {user_name}.Please choose an option to",
"''' function to save a credential ''' Credentials.save_credentials(credential) def display_credential(user_name): ''' Function to",
"user_exists = verify_user(user_name, password) if user_exists == user_name: print( f'Welcome {user_name}.Please choose an",
"''' new_credential = Credentials(user_name,site_name,account_name,password) return new_credential def save_credential(credential): ''' function to save a",
"to copy: ') copy_credentials(chosen_site) print('') elif short_code == 'dl': print('Enter the name of",
"return Credentials.copy_credentials(site_name) def delete_credential(credential): ''' function that deletes credential account ''' credential.delete_credential() def",
"site to be deleted') delete_account = input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry account",
"break elif short_code == 'ca': print(\"-\"*30) print(' ') print('To create a new account:')",
"') copy_credentials(chosen_site) print('') elif short_code == 'dl': print('Enter the name of site to",
"print(\"-\"*30) print(' ') print('To create a new account:') first_name = input('Enter your first",
"= generate_password() break elif psw_choice == 'ex': break else: print('Wrong option entered. Retry.')",
"for entering a password: \\n ep-enter existing password \\n gp-generate a password \\n",
"= User(fname, lname, password) return new_user def save_user(user): ''' function to save user",
"user import User, Credentials def create_user(fname, lname, password): ''' Function to create a",
"\\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() if short_code == 'ex': break",
"') print(\"-\"*30) print('Please choose an option for entering a password: \\n ep-enter existing",
"an Account \\n li-Log In \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip()",
"break else: print('Wrong option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print( f'Credential created: Site",
"Credentials.copy_credentials(site_name) def delete_credential(credential): ''' function that deletes credential account ''' credential.delete_credential() def find_by_site_name(site_name):",
"else: print('Sorry account not matched') else: print('Wrong option entered. Retry') else: print(\"-\"*30) print('",
"Credentials.find_by_site_name(site_name) def main(): print(' ') print('Hi! Welcome to Password-locker.') while True: print(' ')",
"print(\"-\"*30) print(' ') print('To login,enter your account details: ') user_name = input('Enter your",
"print(\"-\"*30) print('Please choose an option for entering a password: \\n ep-enter existing password",
"== 'ep': print(\" \") password = input('Enter your password: ').strip() break elif psw_choice",
"{credential.site_name} - Account Name: {credential.account_name} - Password{<PASSWORD>}') print(' ') elif short_code == 'copy':",
"f'Credential created: Site Name:{site_name} - Account Name: {account_name} - Password:{password}') print(' ') elif",
"''' credential.delete_credential() def find_by_site_name(site_name): ''' function that finds a credential by name '''",
"a choice: ').lower().strip() print(\"-\"*30) if short_code == 'ex': print(\" \") print(f'Goodbye {user_name}') break",
"display_credential(user_name): ''' Function to display credentials saved by a user ''' return Credentials.display_credentials(user_name)",
"of site to be deleted') delete_account = input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry",
"finds a credential by name ''' return Credentials.find_by_site_name(site_name) def main(): print(' ') print('Hi!",
"def find_by_site_name(site_name): ''' function that finds a credential by name ''' return Credentials.find_by_site_name(site_name)",
"continue.') print(' ') while True: print(\"-\"*30) print('Navigation codes: \\n cc-Create a Credential \\n",
"return checking_user def generate_password(): ''' function that generates passwords automatically ''' N =",
"first name- ').strip() password = str(input('Enter your password - ')) user_exists = verify_user(user_name,",
"elif short_code == 'cc': print(' ') print('Enter your credential details:') site_name = input('Enter",
"the site\\'s name-').strip() account_name = input('Enter your account\\'s name-').strip() while True: print(' ')",
"if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry account not matched') else: print('Wrong option entered. Retry')",
"elif short_code == 'copy': print(' ') chosen_site = input('Enter the site name for",
"print('Hi! Welcome to Password-locker.') while True: print(' ') print(\"-\"*30) print( 'Use the guide",
"input('Enter an option: ').lower().strip() print(\"-\"*30) if psw_choice == 'ep': print(\" \") password =",
"user_name = input('Enter your first name- ').strip() password = str(input('Enter your password -",
"return new_user def save_user(user): ''' function to save user ''' User.save_user(user) def verify_user(first_name,",
"Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print( f'Credential created: Site Name:{site_name} - Account Name: {account_name}",
"In \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() if short_code == 'ex':",
"\\n').strip() last_name = input('Enter your last name- \\n').strip() password = input('Enter your password",
"if user_exists == user_name: print( f'Welcome {user_name}.Please choose an option to continue.') print('",
"elif short_code == 'dl': print('Enter the name of site to be deleted') delete_account",
"input('Enter your last name- \\n').strip() password = input('Enter your password \\n').strip() save_user(create_user(first_name, last_name,",
"= input('Enter your last name- \\n').strip() password = input('Enter your password \\n').strip() save_user(create_user(first_name,",
"#!/usr/bin/env python3.6 import secrets import string import pyperclip from user import User, Credentials",
"is a list of all your credentials') print(' ') for credential in display_credential(user_name):",
"Password \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() print(\"-\"*30) if short_code ==",
"else: print('Wrong option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print( f'Credential created: Site Name:{site_name}",
"credential ''' Credentials.save_credentials(credential) def display_credential(user_name): ''' Function to display credentials saved by a",
"12 gen_password = ''.join(secrets.choice( string.ascii_lowercase + string.digits)for i in range(N)) return gen_password def",
"dl-Delete \\n copy-Copy Password \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() print(\"-\"*30)",
"the site name for the credential password to copy: ') copy_credentials(chosen_site) print('') elif",
"your password - ')) user_exists = verify_user(user_name, password) if user_exists == user_name: print(",
"print(' ') print('To login,enter your account details: ') user_name = input('Enter your first",
"password): ''' function that veifies the acount ''' checking_user = Credentials.check_user(first_name, password) return",
"elif short_code == 'ca': print(\"-\"*30) print(' ') print('To create a new account:') first_name",
"short_code == 'li': print(\"-\"*30) print(' ') print('To login,enter your account details: ') user_name",
"= input('Enter your first name- \\n').strip() last_name = input('Enter your last name- \\n').strip()",
"that generates passwords automatically ''' N = 12 gen_password = ''.join(secrets.choice( string.ascii_lowercase +",
"- Account Name: {credential.account_name} - Password{<PASSWORD>}') print(' ') elif short_code == 'copy': print('",
"verify_user(first_name, password): ''' function that veifies the acount ''' checking_user = Credentials.check_user(first_name, password)",
"print(\"-\"*30) print( 'Use the guide codes to choose: \\n ca-Create an Account \\n",
"password: {password}') elif short_code == 'li': print(\"-\"*30) print(' ') print('To login,enter your account",
"'ex': break elif short_code == 'ca': print(\"-\"*30) print(' ') print('To create a new",
"codes: \\n cc-Create a Credential \\n dc-Display Credentials \\n dl-Delete \\n copy-Copy Password",
"print('Enter your credential details:') site_name = input('Enter the site\\'s name-').strip() account_name = input('Enter",
"that veifies the acount ''' checking_user = Credentials.check_user(first_name, password) return checking_user def generate_password():",
"input('Enter your password: ').strip() break elif psw_choice == 'gp': password = generate_password() break",
"option entered. Retry') else: print(\"-\"*30) print(' ') print('Sorry wrong option enetered. Retry') if",
"Credentials def create_user(fname, lname, password): ''' Function to create a new user account",
"psw_choice == 'ep': print(\" \") password = input('Enter your password: ').strip() break elif",
"print(' ') chosen_site = input('Enter the site name for the credential password to",
"site name for the credential password to copy: ') copy_credentials(chosen_site) print('') elif short_code",
"gen_password = ''.join(secrets.choice( string.ascii_lowercase + string.digits)for i in range(N)) return gen_password def create_credential(user_name,site_name,account_name,password):",
"True: print(' ') print(\"-\"*30) print( 'Use the guide codes to choose: \\n ca-Create",
"codes to choose: \\n ca-Create an Account \\n li-Log In \\n ex-Exit') short_code",
"clipboard ''' return Credentials.copy_credentials(site_name) def delete_credential(credential): ''' function that deletes credential account '''",
"function that creates new credential ''' new_credential = Credentials(user_name,site_name,account_name,password) return new_credential def save_credential(credential):",
"''' function that finds a credential by name ''' return Credentials.find_by_site_name(site_name) def main():",
"{password}') elif short_code == 'li': print(\"-\"*30) print(' ') print('To login,enter your account details:",
"account ''' new_user = User(fname, lname, password) return new_user def save_user(user): ''' function",
"entering a password: \\n ep-enter existing password \\n gp-generate a password \\n ex-exit')",
"to the clipboard ''' return Credentials.copy_credentials(site_name) def delete_credential(credential): ''' function that deletes credential",
"pyperclip from user import User, Credentials def create_user(fname, lname, password): ''' Function to",
"input('Enter a choice: ').lower().strip() if short_code == 'ex': break elif short_code == 'ca':",
"credentials saved by a user ''' return Credentials.display_credentials(user_name) def copy_credentials(site_name): ''' Function to",
"= input('Enter your first name- ').strip() password = str(input('Enter your password - '))",
"while True: print(' ') print(\"-\"*30) print('Please choose an option for entering a password:",
"the name of site to be deleted') delete_account = input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account))",
"Retry') else: print(\"-\"*30) print(' ') print('Sorry wrong option enetered. Retry') if __name__ ==",
"\\n gp-generate a password \\n ex-exit') psw_choice = input('Enter an option: ').lower().strip() print(\"-\"*30)",
"input('Enter your first name- \\n').strip() last_name = input('Enter your last name- \\n').strip() password",
"= Credentials.check_user(first_name, password) return checking_user def generate_password(): ''' function that generates passwords automatically",
"''' function that deletes credential account ''' credential.delete_credential() def find_by_site_name(site_name): ''' function that",
"delete_account = input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry account not matched') else: print('Wrong",
"generate_password() break elif psw_choice == 'ex': break else: print('Wrong option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password))",
"credentials details to the clipboard ''' return Credentials.copy_credentials(site_name) def delete_credential(credential): ''' function that",
"print(' ') elif short_code == 'dc': print(' ') if display_credential(user_name): print('Here is a",
"') while True: print(\"-\"*30) print('Navigation codes: \\n cc-Create a Credential \\n dc-Display Credentials",
"- Password{<PASSWORD>}') print(' ') elif short_code == 'copy': print(' ') chosen_site = input('Enter",
"psw_choice == 'ex': break else: print('Wrong option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print(",
"from user import User, Credentials def create_user(fname, lname, password): ''' Function to create",
"save user ''' User.save_user(user) def verify_user(first_name, password): ''' function that veifies the acount",
"True: print(\"-\"*30) print('Navigation codes: \\n cc-Create a Credential \\n dc-Display Credentials \\n dl-Delete",
"an option: ').lower().strip() print(\"-\"*30) if psw_choice == 'ep': print(\" \") password = input('Enter",
"name-').strip() account_name = input('Enter your account\\'s name-').strip() while True: print(' ') print(\"-\"*30) print('Please",
"print('Sorry account not matched') else: print('Wrong option entered. Retry') else: print(\"-\"*30) print(' ')",
"guide codes to choose: \\n ca-Create an Account \\n li-Log In \\n ex-Exit')",
"password = generate_password() break elif psw_choice == 'ex': break else: print('Wrong option entered.",
"print('Wrong option entered. Retry') else: print(\"-\"*30) print(' ') print('Sorry wrong option enetered. Retry')",
"short_code == 'dc': print(' ') if display_credential(user_name): print('Here is a list of all",
"to create a new user account ''' new_user = User(fname, lname, password) return",
"a choice: ').lower().strip() if short_code == 'ex': break elif short_code == 'ca': print(\"-\"*30)",
"print(\"-\"*30) print(' ') print('Sorry wrong option enetered. Retry') if __name__ == '__main__': unittest:",
"User, Credentials def create_user(fname, lname, password): ''' Function to create a new user",
"print(f'Site Name: {credential.site_name} - Account Name: {credential.account_name} - Password{<PASSWORD>}') print(' ') elif short_code",
"'li': print(\"-\"*30) print(' ') print('To login,enter your account details: ') user_name = input('Enter",
"'copy': print(' ') chosen_site = input('Enter the site name for the credential password",
"import secrets import string import pyperclip from user import User, Credentials def create_user(fname,",
"print(' ') print('Sorry wrong option enetered. Retry') if __name__ == '__main__': unittest: main()",
"credential account ''' credential.delete_credential() def find_by_site_name(site_name): ''' function that finds a credential by",
"psw_choice == 'gp': password = generate_password() break elif psw_choice == 'ex': break else:",
"short_code == 'ex': print(\" \") print(f'Goodbye {user_name}') break elif short_code == 'cc': print('",
"li-Log In \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() if short_code ==",
"password to copy: ') copy_credentials(chosen_site) print('') elif short_code == 'dl': print('Enter the name",
"== 'ex': print(\" \") print(f'Goodbye {user_name}') break elif short_code == 'cc': print(' ')",
"Name:{site_name} - Account Name: {account_name} - Password:{password}') print(' ') elif short_code == 'dc':",
"in display_credential(user_name): print(f'Site Name: {credential.site_name} - Account Name: {credential.account_name} - Password{<PASSWORD>}') print(' ')",
"'gp': password = generate_password() break elif psw_choice == 'ex': break else: print('Wrong option",
"password \\n').strip() save_user(create_user(first_name, last_name, password)) print(\" \") print( f'New Account Created for: {first_name}",
"credential.delete_credential() def find_by_site_name(site_name): ''' function that finds a credential by name ''' return",
"Name: {credential.account_name} - Password{<PASSWORD>}') print(' ') elif short_code == 'copy': print(' ') chosen_site",
"Account \\n li-Log In \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() if",
"'ep': print(\" \") password = input('Enter your password: ').strip() break elif psw_choice ==",
"last name- \\n').strip() password = input('Enter your password \\n').strip() save_user(create_user(first_name, last_name, password)) print(\"",
"your account\\'s name-').strip() while True: print(' ') print(\"-\"*30) print('Please choose an option for",
"= input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry account not matched') else: print('Wrong option",
"dc-Display Credentials \\n dl-Delete \\n copy-Copy Password \\n ex-Exit') short_code = input('Enter a",
"new credential ''' new_credential = Credentials(user_name,site_name,account_name,password) return new_credential def save_credential(credential): ''' function to",
"your last name- \\n').strip() password = input('Enter your password \\n').strip() save_user(create_user(first_name, last_name, password))",
"entered. Retry') else: print(\"-\"*30) print(' ') print('Sorry wrong option enetered. Retry') if __name__",
"in range(N)) return gen_password def create_credential(user_name,site_name,account_name,password): ''' function that creates new credential '''",
"\\n').strip() save_user(create_user(first_name, last_name, password)) print(\" \") print( f'New Account Created for: {first_name} {last_name}",
"deletes credential account ''' credential.delete_credential() def find_by_site_name(site_name): ''' function that finds a credential",
"password) return checking_user def generate_password(): ''' function that generates passwords automatically ''' N",
"ep-enter existing password \\n gp-generate a password \\n ex-exit') psw_choice = input('Enter an",
"')) user_exists = verify_user(user_name, password) if user_exists == user_name: print( f'Welcome {user_name}.Please choose",
"def save_user(user): ''' function to save user ''' User.save_user(user) def verify_user(first_name, password): '''",
"password: ').strip() break elif psw_choice == 'gp': password = generate_password() break elif psw_choice",
"ex-exit') psw_choice = input('Enter an option: ').lower().strip() print(\"-\"*30) if psw_choice == 'ep': print(\"",
"\\n copy-Copy Password \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() print(\"-\"*30) if",
"def verify_user(first_name, password): ''' function that veifies the acount ''' checking_user = Credentials.check_user(first_name,",
"account details: ') user_name = input('Enter your first name- ').strip() password = str(input('Enter",
"deleted') delete_account = input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry account not matched') else:",
"account ''' credential.delete_credential() def find_by_site_name(site_name): ''' function that finds a credential by name",
"\") print( f'New Account Created for: {first_name} {last_name} with password: {password}') elif short_code",
"elif psw_choice == 'gp': password = generate_password() break elif psw_choice == 'ex': break",
"choose an option to continue.') print(' ') while True: print(\"-\"*30) print('Navigation codes: \\n",
"name of site to be deleted') delete_account = input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else:",
"for: {first_name} {last_name} with password: {password}') elif short_code == 'li': print(\"-\"*30) print(' ')",
"a credential ''' Credentials.save_credentials(credential) def display_credential(user_name): ''' Function to display credentials saved by",
"save_credential(credential): ''' function to save a credential ''' Credentials.save_credentials(credential) def display_credential(user_name): ''' Function",
"input('Enter your first name- ').strip() password = str(input('Enter your password - ')) user_exists",
"True: print(' ') print(\"-\"*30) print('Please choose an option for entering a password: \\n",
"\") print(f'Goodbye {user_name}') break elif short_code == 'cc': print(' ') print('Enter your credential",
"= 12 gen_password = ''.join(secrets.choice( string.ascii_lowercase + string.digits)for i in range(N)) return gen_password",
"== 'ex': break elif short_code == 'ca': print(\"-\"*30) print(' ') print('To create a",
"gp-generate a password \\n ex-exit') psw_choice = input('Enter an option: ').lower().strip() print(\"-\"*30) if",
"your credential details:') site_name = input('Enter the site\\'s name-').strip() account_name = input('Enter your",
"first name- \\n').strip() last_name = input('Enter your last name- \\n').strip() password = input('Enter",
"choice: ').lower().strip() if short_code == 'ex': break elif short_code == 'ca': print(\"-\"*30) print('",
"an option to continue.') print(' ') while True: print(\"-\"*30) print('Navigation codes: \\n cc-Create",
"= verify_user(user_name, password) if user_exists == user_name: print( f'Welcome {user_name}.Please choose an option",
"Created for: {first_name} {last_name} with password: {password}') elif short_code == 'li': print(\"-\"*30) print('",
"return gen_password def create_credential(user_name,site_name,account_name,password): ''' function that creates new credential ''' new_credential =",
"a new account:') first_name = input('Enter your first name- \\n').strip() last_name = input('Enter",
"credential details:') site_name = input('Enter the site\\'s name-').strip() account_name = input('Enter your account\\'s",
"if display_credential(user_name): print('Here is a list of all your credentials') print(' ') for",
"find_by_site_name(site_name): ''' function that finds a credential by name ''' return Credentials.find_by_site_name(site_name) def",
"import User, Credentials def create_user(fname, lname, password): ''' Function to create a new",
"copy_credentials(site_name): ''' Function to copy a credentials details to the clipboard ''' return",
"print(' ') print(\"-\"*30) print( 'Use the guide codes to choose: \\n ca-Create an",
"copy_credentials(chosen_site) print('') elif short_code == 'dl': print('Enter the name of site to be",
"details: ') user_name = input('Enter your first name- ').strip() password = str(input('Enter your",
"\\n dl-Delete \\n copy-Copy Password \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip()",
"User(fname, lname, password) return new_user def save_user(user): ''' function to save user '''",
"function that deletes credential account ''' credential.delete_credential() def find_by_site_name(site_name): ''' function that finds",
"\\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() print(\"-\"*30) if short_code == 'ex':",
"option for entering a password: \\n ep-enter existing password \\n gp-generate a password",
"not matched') else: print('Wrong option entered. Retry') else: print(\"-\"*30) print(' ') print('Sorry wrong",
"''' return Credentials.find_by_site_name(site_name) def main(): print(' ') print('Hi! Welcome to Password-locker.') while True:",
"''' return Credentials.copy_credentials(site_name) def delete_credential(credential): ''' function that deletes credential account ''' credential.delete_credential()",
"with password: {password}') elif short_code == 'li': print(\"-\"*30) print(' ') print('To login,enter your",
"return Credentials.display_credentials(user_name) def copy_credentials(site_name): ''' Function to copy a credentials details to the",
"choice: ').lower().strip() print(\"-\"*30) if short_code == 'ex': print(\" \") print(f'Goodbye {user_name}') break elif",
"that creates new credential ''' new_credential = Credentials(user_name,site_name,account_name,password) return new_credential def save_credential(credential): '''",
"def create_user(fname, lname, password): ''' Function to create a new user account '''",
"Credential \\n dc-Display Credentials \\n dl-Delete \\n copy-Copy Password \\n ex-Exit') short_code =",
"print( f'Welcome {user_name}.Please choose an option to continue.') print(' ') while True: print(\"-\"*30)",
"an option for entering a password: \\n ep-enter existing password \\n gp-generate a",
"str(input('Enter your password - ')) user_exists = verify_user(user_name, password) if user_exists == user_name:",
"== 'dl': print('Enter the name of site to be deleted') delete_account = input()",
"= input('Enter your password: ').strip() break elif psw_choice == 'gp': password = generate_password()",
"') if display_credential(user_name): print('Here is a list of all your credentials') print(' ')",
"f'New Account Created for: {first_name} {last_name} with password: {password}') elif short_code == 'li':",
"short_code == 'ex': break elif short_code == 'ca': print(\"-\"*30) print(' ') print('To create",
"function that finds a credential by name ''' return Credentials.find_by_site_name(site_name) def main(): print('",
"delete_credential(credential): ''' function that deletes credential account ''' credential.delete_credential() def find_by_site_name(site_name): ''' function",
"\\n ca-Create an Account \\n li-Log In \\n ex-Exit') short_code = input('Enter a",
"display_credential(user_name): print(f'Site Name: {credential.site_name} - Account Name: {credential.account_name} - Password{<PASSWORD>}') print(' ') elif",
"\\n dc-Display Credentials \\n dl-Delete \\n copy-Copy Password \\n ex-Exit') short_code = input('Enter",
"password - ')) user_exists = verify_user(user_name, password) if user_exists == user_name: print( f'Welcome",
"cc-Create a Credential \\n dc-Display Credentials \\n dl-Delete \\n copy-Copy Password \\n ex-Exit')",
"veifies the acount ''' checking_user = Credentials.check_user(first_name, password) return checking_user def generate_password(): '''",
"a credentials details to the clipboard ''' return Credentials.copy_credentials(site_name) def delete_credential(credential): ''' function",
"') elif short_code == 'dc': print(' ') if display_credential(user_name): print('Here is a list",
"\\n ep-enter existing password \\n gp-generate a password \\n ex-exit') psw_choice = input('Enter",
"= Credentials(user_name,site_name,account_name,password) return new_credential def save_credential(credential): ''' function to save a credential '''",
"ca-Create an Account \\n li-Log In \\n ex-Exit') short_code = input('Enter a choice:",
"generates passwords automatically ''' N = 12 gen_password = ''.join(secrets.choice( string.ascii_lowercase + string.digits)for",
"secrets import string import pyperclip from user import User, Credentials def create_user(fname, lname,",
"') user_name = input('Enter your first name- ').strip() password = str(input('Enter your password",
"def main(): print(' ') print('Hi! Welcome to Password-locker.') while True: print(' ') print(\"-\"*30)",
"Account Name: {account_name} - Password:{password}') print(' ') elif short_code == 'dc': print(' ')",
"print(\" \") print( f'New Account Created for: {first_name} {last_name} with password: {password}') elif",
"') elif short_code == 'copy': print(' ') chosen_site = input('Enter the site name",
"copy-Copy Password \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() print(\"-\"*30) if short_code",
"print(\" \") password = input('Enter your password: ').strip() break elif psw_choice == 'gp':",
"create a new account:') first_name = input('Enter your first name- \\n').strip() last_name =",
"User.save_user(user) def verify_user(first_name, password): ''' function that veifies the acount ''' checking_user =",
"== user_name: print( f'Welcome {user_name}.Please choose an option to continue.') print(' ') while",
"= input('Enter a choice: ').lower().strip() print(\"-\"*30) if short_code == 'ex': print(\" \") print(f'Goodbye",
"function to save user ''' User.save_user(user) def verify_user(first_name, password): ''' function that veifies",
"passwords automatically ''' N = 12 gen_password = ''.join(secrets.choice( string.ascii_lowercase + string.digits)for i",
"print(' ') if display_credential(user_name): print('Here is a list of all your credentials') print('",
"to be deleted') delete_account = input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry account not",
"delete_credential(find_by_site_name(delete_account)) else: print('Sorry account not matched') else: print('Wrong option entered. Retry') else: print(\"-\"*30)",
"Password-locker.') while True: print(' ') print(\"-\"*30) print( 'Use the guide codes to choose:",
"= input('Enter an option: ').lower().strip() print(\"-\"*30) if psw_choice == 'ep': print(\" \") password",
"== 'cc': print(' ') print('Enter your credential details:') site_name = input('Enter the site\\'s",
"').strip() password = str(input('Enter your password - ')) user_exists = verify_user(user_name, password) if",
"') print(\"-\"*30) print( 'Use the guide codes to choose: \\n ca-Create an Account",
"password = input('Enter your password: ').strip() break elif psw_choice == 'gp': password =",
"Credentials.check_user(first_name, password) return checking_user def generate_password(): ''' function that generates passwords automatically '''",
"that finds a credential by name ''' return Credentials.find_by_site_name(site_name) def main(): print(' ')",
"\") password = input('Enter your password: ').strip() break elif psw_choice == 'gp': password",
"string import pyperclip from user import User, Credentials def create_user(fname, lname, password): '''",
"ex-Exit') short_code = input('Enter a choice: ').lower().strip() print(\"-\"*30) if short_code == 'ex': print(\"",
"''' User.save_user(user) def verify_user(first_name, password): ''' function that veifies the acount ''' checking_user",
"your first name- \\n').strip() last_name = input('Enter your last name- \\n').strip() password =",
"'dl': print('Enter the name of site to be deleted') delete_account = input() if",
"''' Function to copy a credentials details to the clipboard ''' return Credentials.copy_credentials(site_name)",
"input('Enter your password \\n').strip() save_user(create_user(first_name, last_name, password)) print(\" \") print( f'New Account Created",
"print('Please choose an option for entering a password: \\n ep-enter existing password \\n",
"print( f'New Account Created for: {first_name} {last_name} with password: {password}') elif short_code ==",
"your first name- ').strip() password = str(input('Enter your password - ')) user_exists =",
"').lower().strip() if short_code == 'ex': break elif short_code == 'ca': print(\"-\"*30) print(' ')",
"your password \\n').strip() save_user(create_user(first_name, last_name, password)) print(\" \") print( f'New Account Created for:",
"return Credentials.find_by_site_name(site_name) def main(): print(' ') print('Hi! Welcome to Password-locker.') while True: print('",
"if short_code == 'ex': break elif short_code == 'ca': print(\"-\"*30) print(' ') print('To",
"password = str(input('Enter your password - ')) user_exists = verify_user(user_name, password) if user_exists",
"create a new user account ''' new_user = User(fname, lname, password) return new_user",
"{credential.account_name} - Password{<PASSWORD>}') print(' ') elif short_code == 'copy': print(' ') chosen_site =",
"short_code = input('Enter a choice: ').lower().strip() print(\"-\"*30) if short_code == 'ex': print(\" \")",
"print(' ') print(\"-\"*30) print('Please choose an option for entering a password: \\n ep-enter",
"= input('Enter a choice: ').lower().strip() if short_code == 'ex': break elif short_code ==",
"a password \\n ex-exit') psw_choice = input('Enter an option: ').lower().strip() print(\"-\"*30) if psw_choice",
"while True: print(' ') print(\"-\"*30) print( 'Use the guide codes to choose: \\n",
"to save a credential ''' Credentials.save_credentials(credential) def display_credential(user_name): ''' Function to display credentials",
"+ string.digits)for i in range(N)) return gen_password def create_credential(user_name,site_name,account_name,password): ''' function that creates",
"existing password \\n gp-generate a password \\n ex-exit') psw_choice = input('Enter an option:",
"''' Function to create a new user account ''' new_user = User(fname, lname,",
"all your credentials') print(' ') for credential in display_credential(user_name): print(f'Site Name: {credential.site_name} -",
"a list of all your credentials') print(' ') for credential in display_credential(user_name): print(f'Site",
"N = 12 gen_password = ''.join(secrets.choice( string.ascii_lowercase + string.digits)for i in range(N)) return",
"short_code = input('Enter a choice: ').lower().strip() if short_code == 'ex': break elif short_code",
"print(' ') print('Hi! Welcome to Password-locker.') while True: print(' ') print(\"-\"*30) print( 'Use",
"copy a credentials details to the clipboard ''' return Credentials.copy_credentials(site_name) def delete_credential(credential): '''",
"python3.6 import secrets import string import pyperclip from user import User, Credentials def",
"to Password-locker.') while True: print(' ') print(\"-\"*30) print( 'Use the guide codes to",
"matched') else: print('Wrong option entered. Retry') else: print(\"-\"*30) print(' ') print('Sorry wrong option",
"Site Name:{site_name} - Account Name: {account_name} - Password:{password}') print(' ') elif short_code ==",
"lname, password): ''' Function to create a new user account ''' new_user =",
"== 'copy': print(' ') chosen_site = input('Enter the site name for the credential",
"{user_name}.Please choose an option to continue.') print(' ') while True: print(\"-\"*30) print('Navigation codes:",
"credential in display_credential(user_name): print(f'Site Name: {credential.site_name} - Account Name: {credential.account_name} - Password{<PASSWORD>}') print('",
"user ''' return Credentials.display_credentials(user_name) def copy_credentials(site_name): ''' Function to copy a credentials details",
"') for credential in display_credential(user_name): print(f'Site Name: {credential.site_name} - Account Name: {credential.account_name} -",
"password) if user_exists == user_name: print( f'Welcome {user_name}.Please choose an option to continue.')",
"gen_password def create_credential(user_name,site_name,account_name,password): ''' function that creates new credential ''' new_credential = Credentials(user_name,site_name,account_name,password)",
"'ex': print(\" \") print(f'Goodbye {user_name}') break elif short_code == 'cc': print(' ') print('Enter",
"\\n ex-exit') psw_choice = input('Enter an option: ').lower().strip() print(\"-\"*30) if psw_choice == 'ep':",
"while True: print(\"-\"*30) print('Navigation codes: \\n cc-Create a Credential \\n dc-Display Credentials \\n",
"automatically ''' N = 12 gen_password = ''.join(secrets.choice( string.ascii_lowercase + string.digits)for i in",
"to save user ''' User.save_user(user) def verify_user(first_name, password): ''' function that veifies the",
"password: \\n ep-enter existing password \\n gp-generate a password \\n ex-exit') psw_choice =",
"print(' ') for credential in display_credential(user_name): print(f'Site Name: {credential.site_name} - Account Name: {credential.account_name}",
"short_code == 'dl': print('Enter the name of site to be deleted') delete_account =",
"') print('To create a new account:') first_name = input('Enter your first name- \\n').strip()",
"def create_credential(user_name,site_name,account_name,password): ''' function that creates new credential ''' new_credential = Credentials(user_name,site_name,account_name,password) return",
"{account_name} - Password:{password}') print(' ') elif short_code == 'dc': print(' ') if display_credential(user_name):",
"by a user ''' return Credentials.display_credentials(user_name) def copy_credentials(site_name): ''' Function to copy a",
"Name: {account_name} - Password:{password}') print(' ') elif short_code == 'dc': print(' ') if",
"for the credential password to copy: ') copy_credentials(chosen_site) print('') elif short_code == 'dl':",
"= str(input('Enter your password - ')) user_exists = verify_user(user_name, password) if user_exists ==",
"'dc': print(' ') if display_credential(user_name): print('Here is a list of all your credentials')",
"print( 'Use the guide codes to choose: \\n ca-Create an Account \\n li-Log",
"') print('To login,enter your account details: ') user_name = input('Enter your first name-",
"user ''' User.save_user(user) def verify_user(first_name, password): ''' function that veifies the acount '''",
"acount ''' checking_user = Credentials.check_user(first_name, password) return checking_user def generate_password(): ''' function that",
"the credential password to copy: ') copy_credentials(chosen_site) print('') elif short_code == 'dl': print('Enter",
"a password: \\n ep-enter existing password \\n gp-generate a password \\n ex-exit') psw_choice",
"new user account ''' new_user = User(fname, lname, password) return new_user def save_user(user):",
"def copy_credentials(site_name): ''' Function to copy a credentials details to the clipboard '''",
"f'Welcome {user_name}.Please choose an option to continue.') print(' ') while True: print(\"-\"*30) print('Navigation",
"print(' ') while True: print(\"-\"*30) print('Navigation codes: \\n cc-Create a Credential \\n dc-Display",
"psw_choice = input('Enter an option: ').lower().strip() print(\"-\"*30) if psw_choice == 'ep': print(\" \")",
"print('Wrong option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print( f'Credential created: Site Name:{site_name} -",
"Account Created for: {first_name} {last_name} with password: {password}') elif short_code == 'li': print(\"-\"*30)",
"credential by name ''' return Credentials.find_by_site_name(site_name) def main(): print(' ') print('Hi! Welcome to",
"last_name = input('Enter your last name- \\n').strip() password = input('Enter your password \\n').strip()",
"short_code == 'ca': print(\"-\"*30) print(' ') print('To create a new account:') first_name =",
"- ')) user_exists = verify_user(user_name, password) if user_exists == user_name: print( f'Welcome {user_name}.Please",
"site\\'s name-').strip() account_name = input('Enter your account\\'s name-').strip() while True: print(' ') print(\"-\"*30)",
"your credentials') print(' ') for credential in display_credential(user_name): print(f'Site Name: {credential.site_name} - Account",
"').lower().strip() print(\"-\"*30) if short_code == 'ex': print(\" \") print(f'Goodbye {user_name}') break elif short_code",
"= input('Enter the site name for the credential password to copy: ') copy_credentials(chosen_site)",
"== 'dc': print(' ') if display_credential(user_name): print('Here is a list of all your",
"to copy a credentials details to the clipboard ''' return Credentials.copy_credentials(site_name) def delete_credential(credential):",
"credentials') print(' ') for credential in display_credential(user_name): print(f'Site Name: {credential.site_name} - Account Name:",
"last_name, password)) print(\" \") print( f'New Account Created for: {first_name} {last_name} with password:",
"save a credential ''' Credentials.save_credentials(credential) def display_credential(user_name): ''' Function to display credentials saved",
"created: Site Name:{site_name} - Account Name: {account_name} - Password:{password}') print(' ') elif short_code",
"main(): print(' ') print('Hi! Welcome to Password-locker.') while True: print(' ') print(\"-\"*30) print(",
"''' Function to display credentials saved by a user ''' return Credentials.display_credentials(user_name) def",
"print(' ') print( f'Credential created: Site Name:{site_name} - Account Name: {account_name} - Password:{password}')",
"else: print('Wrong option entered. Retry') else: print(\"-\"*30) print(' ') print('Sorry wrong option enetered.",
"display_credential(user_name): print('Here is a list of all your credentials') print(' ') for credential",
"''' return Credentials.display_credentials(user_name) def copy_credentials(site_name): ''' Function to copy a credentials details to",
"of all your credentials') print(' ') for credential in display_credential(user_name): print(f'Site Name: {credential.site_name}",
"user account ''' new_user = User(fname, lname, password) return new_user def save_user(user): '''",
"your account details: ') user_name = input('Enter your first name- ').strip() password =",
"print(\"-\"*30) if short_code == 'ex': print(\" \") print(f'Goodbye {user_name}') break elif short_code ==",
"string.digits)for i in range(N)) return gen_password def create_credential(user_name,site_name,account_name,password): ''' function that creates new",
"print('Here is a list of all your credentials') print(' ') for credential in",
"Password{<PASSWORD>}') print(' ') elif short_code == 'copy': print(' ') chosen_site = input('Enter the",
"').strip() break elif psw_choice == 'gp': password = generate_password() break elif psw_choice ==",
"lname, password) return new_user def save_user(user): ''' function to save user ''' User.save_user(user)",
"''.join(secrets.choice( string.ascii_lowercase + string.digits)for i in range(N)) return gen_password def create_credential(user_name,site_name,account_name,password): ''' function",
"'ca': print(\"-\"*30) print(' ') print('To create a new account:') first_name = input('Enter your",
"{user_name}') break elif short_code == 'cc': print(' ') print('Enter your credential details:') site_name",
"name- \\n').strip() last_name = input('Enter your last name- \\n').strip() password = input('Enter your",
"new_credential = Credentials(user_name,site_name,account_name,password) return new_credential def save_credential(credential): ''' function to save a credential",
"checking_user def generate_password(): ''' function that generates passwords automatically ''' N = 12",
"def display_credential(user_name): ''' Function to display credentials saved by a user ''' return",
"new_user def save_user(user): ''' function to save user ''' User.save_user(user) def verify_user(first_name, password):",
"- Password:{password}') print(' ') elif short_code == 'dc': print(' ') if display_credential(user_name): print('Here",
"''' function that creates new credential ''' new_credential = Credentials(user_name,site_name,account_name,password) return new_credential def",
"option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print( f'Credential created: Site Name:{site_name} - Account",
"Function to display credentials saved by a user ''' return Credentials.display_credentials(user_name) def copy_credentials(site_name):",
"Credentials \\n dl-Delete \\n copy-Copy Password \\n ex-Exit') short_code = input('Enter a choice:",
"account_name = input('Enter your account\\'s name-').strip() while True: print(' ') print(\"-\"*30) print('Please choose",
"\\n li-Log In \\n ex-Exit') short_code = input('Enter a choice: ').lower().strip() if short_code",
"user_name: print( f'Welcome {user_name}.Please choose an option to continue.') print(' ') while True:",
"name for the credential password to copy: ') copy_credentials(chosen_site) print('') elif short_code ==",
"''' function that generates passwords automatically ''' N = 12 gen_password = ''.join(secrets.choice(",
"password)) print(\" \") print( f'New Account Created for: {first_name} {last_name} with password: {password}')",
"creates new credential ''' new_credential = Credentials(user_name,site_name,account_name,password) return new_credential def save_credential(credential): ''' function",
"name ''' return Credentials.find_by_site_name(site_name) def main(): print(' ') print('Hi! Welcome to Password-locker.') while",
"') print('Hi! Welcome to Password-locker.') while True: print(' ') print(\"-\"*30) print( 'Use the",
"a user ''' return Credentials.display_credentials(user_name) def copy_credentials(site_name): ''' Function to copy a credentials",
"import string import pyperclip from user import User, Credentials def create_user(fname, lname, password):",
"password \\n ex-exit') psw_choice = input('Enter an option: ').lower().strip() print(\"-\"*30) if psw_choice ==",
"details:') site_name = input('Enter the site\\'s name-').strip() account_name = input('Enter your account\\'s name-').strip()",
"Credentials.display_credentials(user_name) def copy_credentials(site_name): ''' Function to copy a credentials details to the clipboard",
"== 'ca': print(\"-\"*30) print(' ') print('To create a new account:') first_name = input('Enter",
"to continue.') print(' ') while True: print(\"-\"*30) print('Navigation codes: \\n cc-Create a Credential",
"checking_user = Credentials.check_user(first_name, password) return checking_user def generate_password(): ''' function that generates passwords",
"def generate_password(): ''' function that generates passwords automatically ''' N = 12 gen_password",
"').lower().strip() print(\"-\"*30) if psw_choice == 'ep': print(\" \") password = input('Enter your password:",
"password): ''' Function to create a new user account ''' new_user = User(fname,",
"print(\"-\"*30) print('Navigation codes: \\n cc-Create a Credential \\n dc-Display Credentials \\n dl-Delete \\n",
"'ex': break else: print('Wrong option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print( f'Credential created:",
"Account Name: {credential.account_name} - Password{<PASSWORD>}') print(' ') elif short_code == 'copy': print(' ')",
"print('To create a new account:') first_name = input('Enter your first name- \\n').strip() last_name",
"print(' ') print('To create a new account:') first_name = input('Enter your first name-",
"= input('Enter your password \\n').strip() save_user(create_user(first_name, last_name, password)) print(\" \") print( f'New Account",
"to choose: \\n ca-Create an Account \\n li-Log In \\n ex-Exit') short_code =",
"credential ''' new_credential = Credentials(user_name,site_name,account_name,password) return new_credential def save_credential(credential): ''' function to save",
"print(' ') elif short_code == 'copy': print(' ') chosen_site = input('Enter the site",
"- Account Name: {account_name} - Password:{password}') print(' ') elif short_code == 'dc': print('",
"print( f'Credential created: Site Name:{site_name} - Account Name: {account_name} - Password:{password}') print(' ')",
"print(\"-\"*30) if psw_choice == 'ep': print(\" \") password = input('Enter your password: ').strip()",
"''' function that veifies the acount ''' checking_user = Credentials.check_user(first_name, password) return checking_user",
"i in range(N)) return gen_password def create_credential(user_name,site_name,account_name,password): ''' function that creates new credential",
"input('Enter your account\\'s name-').strip() while True: print(' ') print(\"-\"*30) print('Please choose an option",
"account not matched') else: print('Wrong option entered. Retry') else: print(\"-\"*30) print(' ') print('Sorry",
"save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print( f'Credential created: Site Name:{site_name} - Account Name: {account_name} -",
"\\n').strip() password = input('Enter your password \\n').strip() save_user(create_user(first_name, last_name, password)) print(\" \") print(",
"user_exists == user_name: print( f'Welcome {user_name}.Please choose an option to continue.') print(' ')",
"save_user(user): ''' function to save user ''' User.save_user(user) def verify_user(first_name, password): ''' function",
"the clipboard ''' return Credentials.copy_credentials(site_name) def delete_credential(credential): ''' function that deletes credential account",
"def delete_credential(credential): ''' function that deletes credential account ''' credential.delete_credential() def find_by_site_name(site_name): '''",
"== 'li': print(\"-\"*30) print(' ') print('To login,enter your account details: ') user_name =",
"') print('Enter your credential details:') site_name = input('Enter the site\\'s name-').strip() account_name =",
"a new user account ''' new_user = User(fname, lname, password) return new_user def",
"print(f'Goodbye {user_name}') break elif short_code == 'cc': print(' ') print('Enter your credential details:')",
"Password:{password}') print(' ') elif short_code == 'dc': print(' ') if display_credential(user_name): print('Here is",
"\\n cc-Create a Credential \\n dc-Display Credentials \\n dl-Delete \\n copy-Copy Password \\n",
"if short_code == 'ex': print(\" \") print(f'Goodbye {user_name}') break elif short_code == 'cc':",
"input() if find_by_site_name(delete_account): delete_credential(find_by_site_name(delete_account)) else: print('Sorry account not matched') else: print('Wrong option entered.",
"= input('Enter the site\\'s name-').strip() account_name = input('Enter your account\\'s name-').strip() while True:",
"elif short_code == 'dc': print(' ') if display_credential(user_name): print('Here is a list of",
"print('To login,enter your account details: ') user_name = input('Enter your first name- ').strip()",
"short_code == 'copy': print(' ') chosen_site = input('Enter the site name for the",
"'Use the guide codes to choose: \\n ca-Create an Account \\n li-Log In",
"copy: ') copy_credentials(chosen_site) print('') elif short_code == 'dl': print('Enter the name of site",
"= input('Enter your account\\'s name-').strip() while True: print(' ') print(\"-\"*30) print('Please choose an",
"the guide codes to choose: \\n ca-Create an Account \\n li-Log In \\n",
"short_code == 'cc': print(' ') print('Enter your credential details:') site_name = input('Enter the",
"print('Navigation codes: \\n cc-Create a Credential \\n dc-Display Credentials \\n dl-Delete \\n copy-Copy",
"input('Enter the site\\'s name-').strip() account_name = input('Enter your account\\'s name-').strip() while True: print('",
"generate_password(): ''' function that generates passwords automatically ''' N = 12 gen_password =",
"''' function to save user ''' User.save_user(user) def verify_user(first_name, password): ''' function that",
"to display credentials saved by a user ''' return Credentials.display_credentials(user_name) def copy_credentials(site_name): '''",
"option: ').lower().strip() print(\"-\"*30) if psw_choice == 'ep': print(\" \") password = input('Enter your",
"def save_credential(credential): ''' function to save a credential ''' Credentials.save_credentials(credential) def display_credential(user_name): '''",
"the acount ''' checking_user = Credentials.check_user(first_name, password) return checking_user def generate_password(): ''' function",
"== 'gp': password = generate_password() break elif psw_choice == 'ex': break else: print('Wrong",
"'cc': print(' ') print('Enter your credential details:') site_name = input('Enter the site\\'s name-').strip()",
"== 'ex': break else: print('Wrong option entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print( f'Credential",
"site_name = input('Enter the site\\'s name-').strip() account_name = input('Enter your account\\'s name-').strip() while",
"') chosen_site = input('Enter the site name for the credential password to copy:",
"print('') elif short_code == 'dl': print('Enter the name of site to be deleted')",
"that deletes credential account ''' credential.delete_credential() def find_by_site_name(site_name): ''' function that finds a",
"Function to create a new user account ''' new_user = User(fname, lname, password)",
"chosen_site = input('Enter the site name for the credential password to copy: ')",
"input('Enter the site name for the credential password to copy: ') copy_credentials(chosen_site) print('')",
"for credential in display_credential(user_name): print(f'Site Name: {credential.site_name} - Account Name: {credential.account_name} - Password{<PASSWORD>}')",
"function that veifies the acount ''' checking_user = Credentials.check_user(first_name, password) return checking_user def",
"import pyperclip from user import User, Credentials def create_user(fname, lname, password): ''' Function",
"if psw_choice == 'ep': print(\" \") password = input('Enter your password: ').strip() break",
"else: print(\"-\"*30) print(' ') print('Sorry wrong option enetered. Retry') if __name__ == '__main__':",
"display credentials saved by a user ''' return Credentials.display_credentials(user_name) def copy_credentials(site_name): ''' Function",
"''' N = 12 gen_password = ''.join(secrets.choice( string.ascii_lowercase + string.digits)for i in range(N))",
"create_credential(user_name,site_name,account_name,password): ''' function that creates new credential ''' new_credential = Credentials(user_name,site_name,account_name,password) return new_credential",
"Credentials.save_credentials(credential) def display_credential(user_name): ''' Function to display credentials saved by a user '''",
"input('Enter a choice: ').lower().strip() print(\"-\"*30) if short_code == 'ex': print(\" \") print(f'Goodbye {user_name}')",
"first_name = input('Enter your first name- \\n').strip() last_name = input('Enter your last name-",
"entered. Retry.') save_credential(create_credential(user_name,site_name,account_name,password)) print(' ') print( f'Credential created: Site Name:{site_name} - Account Name:",
"function to save a credential ''' Credentials.save_credentials(credential) def display_credential(user_name): ''' Function to display",
"function that generates passwords automatically ''' N = 12 gen_password = ''.join(secrets.choice( string.ascii_lowercase"
] |
[
"arg == '-h': return 1 elif arg == '-c': self.context = True if",
"self.func = False self.depth = 0 self.path = None self.pattern = None self.regexp",
"PythonLexer from pygments import highlight from pygments.formatters.terminal import TerminalFormatter import shutil import re",
"== '-cl': self.cl = True args.remove(arg) elif arg == '-h': return 1 elif",
"+ ' +--{} lines: {}---\\033[0;0m\\n').format( first_top, end_top - first_top, content.splitlines()[first_top-1] )] first =",
"in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] else: curres += [('\\033[1;90m{:0>2}' + ' +--{}",
"f: ln = 0 curres = '' for num, line in enumerate(f, 1):",
"formatted with pep8 guidelines optional arguments: -h show this page -c [depth] show",
"lines: {}---\\033[0;0m\\n').format( first_top, end_top - first_top, content.splitlines()[first_top-1] )] first = end_top+1 curres +=",
"int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth = 1 args.remove(arg) elif arg == '-f': self.func =",
"num, line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def parse(args): results",
"else: results.append(curres) curres = a ln = num results.append(curres) if ''.join(results) == '':",
"ast.walk(root): for child in ast.iter_child_nodes(node): child.parent = node # search for pattern for",
"for arg in [self.cl, self.func, self.context] if arg is True] ) > 1:",
"in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def context_parse(args): with open(args.path) as",
"is True: if pattern_node is not root.body[0]: top = root.body[root.body.index(pattern_node)-1] first_top = top.lineno",
"TerminalFormatter() ).strip('\\n') return resstring + '\\n' class Args: def __init__(self, args): self.context =",
"arg == '-re': self.regexp = True args.remove(arg) if arg == '-cl': self.cl =",
"= self.parseargs(args) def parseargs(self, args): if len(args) == 0: return 1 for arg",
"pattern_node.parent if pattern_node.parent is root: top_root = True break first = pattern_node.lineno end",
"num: return child def get_end(node): ints = [] ints.append(node.lineno) for child in ast.walk(node):",
"[depth] show context of the string. -cl show class containing string (ignored if",
"args.context: results = context_parse(args) else: with open(args.path) as f: ln = 0 curres",
"args.cl or args.func: results = class_parse(args) elif args.context: results = context_parse(args) else: with",
"pass else: pattern = None if not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight(",
"= pattern_node.lineno end = get_end(pattern_node) curres += [ mhighlight( num, line, args.pattern, args.regexp",
"num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] else: curres += [('\\033[1;90m{:0>2}' +",
"for split in splits: resstring += highlight( split, PythonLexer(), TerminalFormatter() ).strip('\\n') if split",
"if pattern_node is not root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno if first_bottom",
"False if pattern_node.parent is root: top_root = True else: for i in range(args.depth):",
"usage: pytgrep [-c <depth> | -cl | -f | -re] (optional) pattern file",
"else: while objsearch not in str(pattern_node): if pattern_node.parent is root: break pattern_node =",
"# search for pattern for num, line in enumerate(content.splitlines(), 1): if (args.pattern in",
"for i in range(len(found)): resstring += highlight( splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n') resstring +=",
"range(args.depth): pattern_node = pattern_node.parent if pattern_node.parent is root: top_root = True break first",
"-f show function containing string (ignored if no function) -re pattern is regexp",
"not recognized option'.format(arg)) return 1 if len( [arg for arg in [self.cl, self.func,",
"root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno if first_bottom - end > 1:",
"self.context = True if arg != args[-1] and args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1])",
"not os.path.exists(args[-1]): print('Error: no file {}'.format(args[-1])) return 1 elif not args[-1].endswith('.py'): with open(args[-1])",
"+--{} lines: {}---\\033[0;0m\\n').format( first_top, end_top - first_top, content.splitlines()[first_top-1] )] first = end_top+1 curres",
"args.func: objsearch = 'FunctionDef' with open(args.path) as f: content = f.read() results =",
"is root: top_root = True else: for i in range(args.depth): pattern_node = pattern_node.parent",
"root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno if first_bottom - end > 1: added_lines += content.splitlines()[",
"False self.depth = 0 self.path = None self.pattern = None self.regexp = False",
")) else: if regexp is False: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits = string.split(pattern)",
"is root: top_root = True break first = pattern_node.lineno end = get_end(pattern_node) curres",
"end:first_bottom] end_bottom = get_end(bottom) if end_bottom - first_bottom < 3: curres += [",
"mhighlight( num, line, args.pattern, args.regexp ) for num, line in enumerate(content.splitlines()[first-1:end], first) ]",
"num, line in enumerate(f, 1): if args.pattern in line or ( re.search(args.pattern, line)",
"+= '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring + '\\n' else: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt",
"usage(): print(''' usage: pytgrep [-c <depth> | -cl | -f | -re] (optional)",
"pygments.formatters.terminal import TerminalFormatter import shutil import re import ast import sys import os",
"content.splitlines()[first_bottom-1] )] else: curres += [ mhighlight( num, line, args.pattern, args.regexp ) for",
"is not root.body[0]: top = root.body[root.body.index(pattern_node)-1] first_top = top.lineno end_top = get_end(top) if",
"import highlight from pygments.formatters.terminal import TerminalFormatter import shutil import re import ast import",
"results = [] if args.cl or args.func: results = class_parse(args) elif args.context: results",
"else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom - first_bottom,",
"not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'), )) else: if",
"return 1 self.path = args[-1] args.remove(args[-1]) if len(args) != 0: self.pattern = args[-1]",
"\\ child.lineno == num: return child def get_end(node): ints = [] ints.append(node.lineno) for",
"hasattr(ch, 'lineno'): ints.append(ch.lineno) return max(ints) def class_parse(args): if args.cl: objsearch = 'ClassDef' elif",
"containing string (ignored if no function) -re pattern is regexp Note: only one",
"highlight from pygments.formatters.terminal import TerminalFormatter import shutil import re import ast import sys",
"show class containing string (ignored if no class) -f show function containing string",
"used at a time') return 1 return 0 def find_match_node(results, num, root, args):",
"ast.iter_child_nodes(child): if hasattr(ch, 'lineno'): ints.append(ch.lineno) return max(ints) def class_parse(args): if args.cl: objsearch =",
"for i in range(args.depth): pattern_node = pattern_node.parent if pattern_node.parent is root: top_root =",
"if (args.pattern in line or ( args.regexp and re.search(args.pattern, line) )) and (num,",
"0 def find_match_node(results, num, root, args): for node in ast.walk(root): for child in",
"0: return 1 for arg in args: arg = args[0] if arg ==",
"in enumerate( content.splitlines()[first_top-1:end_top], first_top )] added_lines += [ (num, line) for num, line",
"'\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring + '\\n' else: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt =",
"3: curres += [ mhighlight( num, line, args.pattern, args.regexp ) for num, line",
"no search pattern') return 1 if len(args) != 0: print(args) for arg in",
"time') return 1 return 0 def find_match_node(results, num, root, args): for node in",
"objsearch = 'ClassDef' elif args.func: objsearch = 'FunctionDef' with open(args.path) as f: content",
"' +--{} lines: {}---\\033[0;0m\\n').format( first_top, end_top - first_top, content.splitlines()[first_top-1] )] first = end_top+1",
"no function) -re pattern is regexp Note: only one option (except -re) can",
"self.context = False self.cl = False self.func = False self.depth = 0 self.path",
"highlight( splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring += highlight( splits[-1],",
"args: print('{} is not recognized option'.format(arg)) return 1 if len( [arg for arg",
"'-c': self.context = True if arg != args[-1] and args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1])",
"Only one of -cl, -c, -f can be used at a time') return",
"resstring + '\\n' else: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt = re.compile(pattern) splits =",
"os.path.exists(args[-1]): print('Error: no file {}'.format(args[-1])) return 1 elif not args[-1].endswith('.py'): with open(args[-1]) as",
"= end_top+1 curres += [ mhighlight( num, line, args.pattern, args.regexp ) for num,",
"for arg in args: print('{} is not recognized option'.format(arg)) return 1 if len(",
"''') def get_numlines(node): return len(codegen.to_source(node).splitlines()) def mhighlight(num, string, pattern, regexp): if pattern in",
"1): if args.pattern in line or ( re.search(args.pattern, line) and args.regexp ): a",
"for node in ast.walk(root): for child in ast.iter_child_nodes(node): child.parent = node # search",
"class_parse(args): if args.cl: objsearch = 'ClassDef' elif args.func: objsearch = 'FunctionDef' with open(args.path)",
"<reponame>skvoter/pygreppy<filename>pygreppy/core.py from pygments.lexers.python import PythonLexer from pygments import highlight from pygments.formatters.terminal import TerminalFormatter",
"top = root.body[root.body.index(pattern_node)-1] first_top = top.lineno end_top = get_end(top) if end_top - first_top",
"len( [arg for arg in [self.cl, self.func, self.context] if arg is True] )",
"None: continue else: while objsearch not in str(pattern_node): if pattern_node.parent is root: break",
"if args.cl or args.func: results = class_parse(args) elif args.context: results = context_parse(args) else:",
"with open(args.path) as f: ln = 0 curres = '' for num, line",
"a = mhighlight(num, line, args.pattern, args.regexp) if num == ln + 1: curres",
").strip('\\n') if split != splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring + '\\n'",
"pattern_node is None: continue else: while objsearch not in str(pattern_node): if pattern_node.parent is",
"True break first = pattern_node.lineno end = get_end(pattern_node) curres = [] if top_root",
")] results.append(''.join(curres)) return results def parse(args): results = [] if args.cl or args.func:",
"for num, line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def context_parse(args):",
"'\\n' class Args: def __init__(self, args): self.context = False self.cl = False self.func",
"| -f | -re] (optional) pattern file file should be python script formatted",
"+= highlight( split, PythonLexer(), TerminalFormatter() ).strip('\\n') if split != splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format(",
"= [] if objsearch in str(pattern_node): first = pattern_node.lineno end = get_end(pattern_node) curres",
"first )] results.append(''.join(curres)) return results def context_parse(args): with open(args.path) as f: content =",
"continue else: while objsearch not in str(pattern_node): if pattern_node.parent is root: break pattern_node",
"= get_end(pattern_node) curres = [] if top_root is True: if pattern_node is not",
"else: curres += [ mhighlight( num, line, args.pattern, args.regexp ) for num, line",
"ln = num results.append(curres) if ''.join(results) == '': results = [] return ('\\n\\033[1;90m'",
"if arg == '-re': self.regexp = True args.remove(arg) if arg == '-cl': self.cl",
"elif not args[-1].endswith('.py'): with open(args[-1]) as f: line = f.readline(0) if '#!' not",
"'\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring += highlight( splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n') return resstring + '\\n'",
"== num: return child def get_end(node): ints = [] ints.append(node.lineno) for child in",
"line, args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )]",
"self.path = None self.pattern = None self.regexp = False self.args = self.parseargs(args) def",
"end_bottom = get_end(bottom) if end_bottom - first_bottom < 3: curres += [ mhighlight(",
"first_bottom = bottom.lineno if first_bottom - end > 1: added_lines += content.splitlines()[ end:first_bottom]",
"a time. ''') def get_numlines(node): return len(codegen.to_source(node).splitlines()) def mhighlight(num, string, pattern, regexp): if",
"node # search for pattern for num, line in enumerate(content.splitlines(), 1): if (args.pattern",
"file should be python script formatted with pep8 guidelines optional arguments: -h show",
"def parseargs(self, args): if len(args) == 0: return 1 for arg in args:",
"not args[-1].endswith('.py'): with open(args[-1]) as f: line = f.readline(0) if '#!' not in",
"= 'ClassDef' elif args.func: objsearch = 'FunctionDef' with open(args.path) as f: content =",
"for num, line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def parse(args):",
"get_numlines(node): return len(codegen.to_source(node).splitlines()) def mhighlight(num, string, pattern, regexp): if pattern in string or",
"results def parse(args): results = [] if args.cl or args.func: results = class_parse(args)",
"re.search(args.pattern, line) )) and (num, line) not in added_lines: pattern_node = find_match_node(results, num,",
"ln + 1: curres += a else: results.append(curres) curres = a ln =",
"content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] added_lines += [ (num, line) for num, line in",
"return 0 def find_match_node(results, num, root, args): for node in ast.walk(root): for child",
"(args.pattern in line or ( args.regexp and re.search(args.pattern, line) )) and (num, line)",
"( re.search(args.pattern, line) and args.regexp ): a = mhighlight(num, line, args.pattern, args.regexp) if",
"'-cl': self.cl = True args.remove(arg) elif arg == '-h': return 1 elif arg",
"should be python script formatted with pep8 guidelines optional arguments: -h show this",
"time. ''') def get_numlines(node): return len(codegen.to_source(node).splitlines()) def mhighlight(num, string, pattern, regexp): if pattern",
"if arg != args[-1] and args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth =",
"'-h': return 1 elif arg == '-c': self.context = True if arg !=",
"arg in [self.cl, self.func, self.context] if arg is True] ) > 1: print('Error:",
"context_parse(args) else: with open(args.path) as f: ln = 0 curres = '' for",
"enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def context_parse(args): with open(args.path) as f:",
"a python script'.format(args[-1])) return 1 self.path = args[-1] args.remove(args[-1]) if len(args) != 0:",
"0: self.pattern = args[-1] args.remove(args[-1]) else: print('Error: there is no search pattern') return",
"file {}'.format(args[-1])) return 1 elif not args[-1].endswith('.py'): with open(args[-1]) as f: line =",
"highlight( splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n') return resstring + '\\n' class Args: def __init__(self,",
"print(args) for arg in args: print('{} is not recognized option'.format(arg)) return 1 if",
"get_end(pattern_node) curres = [] if top_root is True: if pattern_node is not root.body[0]:",
"[-c <depth> | -cl | -f | -re] (optional) pattern file file should",
"first_top, content.splitlines()[first_top-1] )] first = end_top+1 curres += [ mhighlight( num, line, args.pattern,",
"a else: results.append(curres) curres = a ln = num results.append(curres) if ''.join(results) ==",
"PythonLexer(), TerminalFormatter() ).strip('\\n') if split != splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring",
"(except -re) can be specified at a time. ''') def get_numlines(node): return len(codegen.to_source(node).splitlines())",
"in codegen.to_source(child) and \\ hasattr(child, 'lineno') and \\ child.lineno == num: return child",
"ast.iter_child_nodes(node): child.parent = node # search for pattern for num, line in enumerate(content.splitlines(),",
"if regexp is False: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits = string.split(pattern) for split",
") for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] added_lines += [",
"= None if not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'),",
"curres = [] if objsearch in str(pattern_node): first = pattern_node.lineno end = get_end(pattern_node)",
"highlight( split, PythonLexer(), TerminalFormatter() ).strip('\\n') if split != splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n'))",
". import codegen def usage(): print(''' usage: pytgrep [-c <depth> | -cl |",
"else: pattern = None if not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight( string,",
"def context_parse(args): with open(args.path) as f: content = f.read() results = [] added_lines",
"= False self.cl = False self.func = False self.depth = 0 self.path =",
"if len(args) != 0: print(args) for arg in args: print('{} is not recognized",
"line) not in added_lines: pattern_node = find_match_node(results, num, root, args) if pattern_node is",
"args.remove(arg) elif arg == '-f': self.func = True args.remove(arg) if not os.path.exists(args[-1]): print('Error:",
"root.body[0]: top = root.body[root.body.index(pattern_node)-1] first_top = top.lineno end_top = get_end(top) if end_top -",
"results = class_parse(args) elif args.context: results = context_parse(args) else: with open(args.path) as f:",
"''.join(results) == '': results = [] return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def",
"== num: return child else: if args.pattern in codegen.to_source(child) and \\ hasattr(child, 'lineno')",
"+= highlight( splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n') return resstring + '\\n' class Args: def",
"from pygments.lexers.python import PythonLexer from pygments import highlight from pygments.formatters.terminal import TerminalFormatter import",
"= class_parse(args) elif args.context: results = context_parse(args) else: with open(args.path) as f: ln",
"return child else: if args.pattern in codegen.to_source(child) and \\ hasattr(child, 'lineno') and \\",
"if len(args) == 0: return 1 for arg in args: arg = args[0]",
"import re import ast import sys import os from . import codegen def",
"else: print('Error: there is no search pattern') return 1 if len(args) != 0:",
"self.pattern = args[-1] args.remove(args[-1]) else: print('Error: there is no search pattern') return 1",
"if hasattr(ch, 'lineno'): ints.append(ch.lineno) return max(ints) def class_parse(args): if args.cl: objsearch = 'ClassDef'",
"content.splitlines()[first-1:end], first )] if pattern_node is not root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1] first_bottom =",
"True args.remove(arg) if arg == '-cl': self.cl = True args.remove(arg) elif arg ==",
"= get_end(top) if end_top - first_top < 3: curres += [ mhighlight( num,",
"= [] if args.cl or args.func: results = class_parse(args) elif args.context: results =",
"import TerminalFormatter import shutil import re import ast import sys import os from",
"import PythonLexer from pygments import highlight from pygments.formatters.terminal import TerminalFormatter import shutil import",
"elif arg == '-f': self.func = True args.remove(arg) if not os.path.exists(args[-1]): print('Error: no",
"= end_top+1 else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_top, end_top",
"self.regexp = False self.args = self.parseargs(args) def parseargs(self, args): if len(args) == 0:",
"| -re] (optional) pattern file file should be python script formatted with pep8",
"content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format(",
"class Args: def __init__(self, args): self.context = False self.cl = False self.func =",
"mhighlight(num, string, pattern, regexp): if pattern in string or (regexp is True and",
"= re.compile(pattern) splits = patt.split(string) found = patt.findall(string) for i in range(len(found)): resstring",
"resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt = re.compile(pattern) splits = patt.split(string) found = patt.findall(string)",
"in range(args.depth): pattern_node = pattern_node.parent if pattern_node.parent is root: top_root = True break",
"'': results = [] return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def main(): args",
"{} is not a python script'.format(args[-1])) return 1 self.path = args[-1] args.remove(args[-1]) if",
"'.format(num) patt = re.compile(pattern) splits = patt.split(string) found = patt.findall(string) for i in",
"import ast import sys import os from . import codegen def usage(): print('''",
"script formatted with pep8 guidelines optional arguments: -h show this page -c [depth]",
"(ignored if no class) -f show function containing string (ignored if no function)",
"splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n') return resstring + '\\n' class Args: def __init__(self, args):",
"0 self.path = None self.pattern = None self.regexp = False self.args = self.parseargs(args)",
"return 1 for arg in args: arg = args[0] if arg == '-re':",
"re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and \\ hasattr(child, 'lineno') and \\ child.lineno == num: return",
"args): for node in ast.walk(root): for child in ast.iter_child_nodes(node): if args.regexp: pattern =",
"else: for i in range(args.depth): pattern_node = pattern_node.parent if pattern_node.parent is root: top_root",
"resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring + '\\n' else: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num)",
"else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_top, end_top - first_top,",
"ints = [] ints.append(node.lineno) for child in ast.walk(node): for ch in ast.iter_child_nodes(child): if",
"pattern for num, line in enumerate(content.splitlines(), 1): if (args.pattern in line or (",
"True else: for i in range(args.depth): pattern_node = pattern_node.parent if pattern_node.parent is root:",
"continue top_root = False if pattern_node.parent is root: top_root = True else: for",
"a time') return 1 return 0 def find_match_node(results, num, root, args): for node",
"- first_bottom, content.splitlines()[first_bottom-1] )] else: curres += [ mhighlight( num, line, args.pattern, args.regexp",
"= string.split(pattern) for split in splits: resstring += highlight( split, PythonLexer(), TerminalFormatter() ).strip('\\n')",
"arg in args: arg = args[0] if arg == '-re': self.regexp = True",
"find_match_node(results, num, root, args): for node in ast.walk(root): for child in ast.iter_child_nodes(node): if",
"python script formatted with pep8 guidelines optional arguments: -h show this page -c",
"args.regexp) if num == ln + 1: curres += a else: results.append(curres) curres",
"max(ints) def class_parse(args): if args.cl: objsearch = 'ClassDef' elif args.func: objsearch = 'FunctionDef'",
"[ mhighlight( num, line, args.pattern, args.regexp ) for num, line in enumerate(content.splitlines()[first-1:end], first)",
"args[-1].endswith('.py'): with open(args[-1]) as f: line = f.readline(0) if '#!' not in line",
"'lineno'): ints.append(ch.lineno) return max(ints) def class_parse(args): if args.cl: objsearch = 'ClassDef' elif args.func:",
"args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] added_lines",
"is None: continue top_root = False if pattern_node.parent is root: top_root = True",
"pattern = None if not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight( string, PythonLexer(),",
"= num results.append(curres) if ''.join(results) == '': results = [] return ('\\n\\033[1;90m' +",
"args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth = 1 args.remove(arg) elif arg ==",
"end = get_end(pattern_node) curres = [] if top_root is True: if pattern_node is",
"line, args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] added_lines",
"= pattern_node.lineno end = get_end(pattern_node) curres = [] if top_root is True: if",
"find_match_node(results, num, root, args) if pattern_node is None: continue top_root = False if",
"mhighlight( num, line, args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top",
")] first = end_top+1 else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format(",
"only one option (except -re) can be specified at a time. ''') def",
"added_lines: pattern_node = find_match_node(results, num, root, args) if pattern_node is None: continue else:",
"line) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] else: curres +=",
"with pep8 guidelines optional arguments: -h show this page -c [depth] show context",
"from . import codegen def usage(): print(''' usage: pytgrep [-c <depth> | -cl",
"objsearch = 'FunctionDef' with open(args.path) as f: content = f.read() results = []",
"line) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] first = end_top+1 else:",
"1 elif arg == '-c': self.context = True if arg != args[-1] and",
"] added_lines += [ (num, line) for num, line in enumerate( content.splitlines()[first-1:end], first",
"line in enumerate(content.splitlines(), 1): if (args.pattern in line or ( args.regexp and re.search(args.pattern,",
"= pattern_node.parent curres = [] if objsearch in str(pattern_node): first = pattern_node.lineno end",
"= args[0] if arg == '-re': self.regexp = True args.remove(arg) if arg ==",
"None if not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'), ))",
"+ '\\033[0;0m\\n\\n').join(results) def main(): args = Args(sys.argv[1:]) if args.args == 1: usage() sys.exit(1)",
"main(): args = Args(sys.argv[1:]) if args.args == 1: usage() sys.exit(1) else: print('\\n' +",
"else: self.depth = 1 args.remove(arg) elif arg == '-f': self.func = True args.remove(arg)",
"top_root = True else: for i in range(args.depth): pattern_node = pattern_node.parent if pattern_node.parent",
"first = end_top+1 curres += [ mhighlight( num, line, args.pattern, args.regexp ) for",
"end_bottom - first_bottom < 3: curres += [ mhighlight( num, line, args.pattern, args.regexp",
"root.body[root.body.index(pattern_node)-1] first_top = top.lineno end_top = get_end(top) if end_top - first_top < 3:",
"args.cl: objsearch = 'ClassDef' elif args.func: objsearch = 'FunctionDef' with open(args.path) as f:",
"in line or ( re.search(args.pattern, line) and args.regexp ): a = mhighlight(num, line,",
"regexp Note: only one option (except -re) can be specified at a time.",
"'ClassDef' elif args.func: objsearch = 'FunctionDef' with open(args.path) as f: content = f.read()",
"hasattr(child, 'lineno') and \\ child.lineno == num: return child else: if args.pattern in",
"in added_lines: pattern_node = find_match_node(results, num, root, args) if pattern_node is None: continue",
"return max(ints) def class_parse(args): if args.cl: objsearch = 'ClassDef' elif args.func: objsearch =",
"curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_top, end_top - first_top, content.splitlines()[first_top-1]",
"= True else: for i in range(args.depth): pattern_node = pattern_node.parent if pattern_node.parent is",
"1: added_lines += content.splitlines()[ end:first_bottom] end_bottom = get_end(bottom) if end_bottom - first_bottom <",
"results.append(''.join(curres)) return results def parse(args): results = [] if args.cl or args.func: results",
"file file should be python script formatted with pep8 guidelines optional arguments: -h",
"found = patt.findall(string) for i in range(len(found)): resstring += highlight( splits[i], PythonLexer(), TerminalFormatter()",
"('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def main(): args = Args(sys.argv[1:]) if args.args ==",
"def mhighlight(num, string, pattern, regexp): if pattern in string or (regexp is True",
"for child in ast.walk(node): for ch in ast.iter_child_nodes(child): if hasattr(ch, 'lineno'): ints.append(ch.lineno) return",
"> 1: added_lines += content.splitlines()[ end:first_bottom] end_bottom = get_end(bottom) if end_bottom - first_bottom",
"-re] (optional) pattern file file should be python script formatted with pep8 guidelines",
"root: break pattern_node = pattern_node.parent curres = [] if objsearch in str(pattern_node): first",
"if pattern_node is None: continue top_root = False if pattern_node.parent is root: top_root",
"'' for num, line in enumerate(f, 1): if args.pattern in line or (",
"{}\\n'.format( num, highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'), )) else: if regexp is False: resstring",
"resstring += highlight( split, PythonLexer(), TerminalFormatter() ).strip('\\n') if split != splits[-1]: resstring +=",
"if top_root is True: if pattern_node is not root.body[0]: top = root.body[root.body.index(pattern_node)-1] first_top",
"len(codegen.to_source(node).splitlines()) def mhighlight(num, string, pattern, regexp): if pattern in string or (regexp is",
"from pygments.formatters.terminal import TerminalFormatter import shutil import re import ast import sys import",
"{}'.format(args[-1])) return 1 elif not args[-1].endswith('.py'): with open(args[-1]) as f: line = f.readline(0)",
"parse(args): results = [] if args.cl or args.func: results = class_parse(args) elif args.context:",
"__init__(self, args): self.context = False self.cl = False self.func = False self.depth =",
"= [] ints.append(node.lineno) for child in ast.walk(node): for ch in ast.iter_child_nodes(child): if hasattr(ch,",
"curres = a ln = num results.append(curres) if ''.join(results) == '': results =",
"def parse(args): results = [] if args.cl or args.func: results = class_parse(args) elif",
"'-f': self.func = True args.remove(arg) if not os.path.exists(args[-1]): print('Error: no file {}'.format(args[-1])) return",
"def get_end(node): ints = [] ints.append(node.lineno) for child in ast.walk(node): for ch in",
"False self.args = self.parseargs(args) def parseargs(self, args): if len(args) == 0: return 1",
"not in added_lines: pattern_node = find_match_node(results, num, root, args) if pattern_node is None:",
"string.split(pattern) for split in splits: resstring += highlight( split, PythonLexer(), TerminalFormatter() ).strip('\\n') if",
"is no search pattern') return 1 if len(args) != 0: print(args) for arg",
"child in ast.iter_child_nodes(node): child.parent = node # search for pattern for num, line",
"= Args(sys.argv[1:]) if args.args == 1: usage() sys.exit(1) else: print('\\n' + parse(args)) if",
"[ (num, line) for num, line in enumerate( content.splitlines()[first-1:end], first )] if pattern_node",
"= args[-1] args.remove(args[-1]) else: print('Error: there is no search pattern') return 1 if",
"if pattern_node is None: continue else: while objsearch not in str(pattern_node): if pattern_node.parent",
"root = ast.parse(content) for node in ast.walk(root): for child in ast.iter_child_nodes(node): child.parent =",
"curres += a else: results.append(curres) curres = a ln = num results.append(curres) if",
"args.regexp: pattern = re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and \\ hasattr(child, 'lineno') and \\ child.lineno",
"args = Args(sys.argv[1:]) if args.args == 1: usage() sys.exit(1) else: print('\\n' + parse(args))",
"num: return child else: if args.pattern in codegen.to_source(child) and \\ hasattr(child, 'lineno') and",
"== ln + 1: curres += a else: results.append(curres) curres = a ln",
"= False self.func = False self.depth = 0 self.path = None self.pattern =",
"line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] added_lines += [ (num, line) for",
"in splits: resstring += highlight( split, PythonLexer(), TerminalFormatter() ).strip('\\n') if split != splits[-1]:",
"pattern_node.parent curres = [] if objsearch in str(pattern_node): first = pattern_node.lineno end =",
"can be specified at a time. ''') def get_numlines(node): return len(codegen.to_source(node).splitlines()) def mhighlight(num,",
"if pattern_node.parent is root: top_root = True break first = pattern_node.lineno end =",
"== 1: usage() sys.exit(1) else: print('\\n' + parse(args)) if __name__ == '__main__': main()",
"+= [ mhighlight( num, line, args.pattern, args.regexp ) for num, line in enumerate(",
"from pygments import highlight from pygments.formatters.terminal import TerminalFormatter import shutil import re import",
"added_lines += [ (num, line) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )]",
"ast.walk(node): for ch in ast.iter_child_nodes(child): if hasattr(ch, 'lineno'): ints.append(ch.lineno) return max(ints) def class_parse(args):",
"for child in ast.iter_child_nodes(node): child.parent = node # search for pattern for num,",
"= [] added_lines = [] root = ast.parse(content) for node in ast.walk(root): for",
"python script'.format(args[-1])) return 1 self.path = args[-1] args.remove(args[-1]) if len(args) != 0: self.pattern",
"lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom - first_bottom, content.splitlines()[first_bottom-1] )] else: curres += [ mhighlight(",
"+= [ mhighlight( num, line, args.pattern, args.regexp ) for num, line in enumerate(content.splitlines()[first-1:end],",
"num == ln + 1: curres += a else: results.append(curres) curres = a",
"self.parseargs(args) def parseargs(self, args): if len(args) == 0: return 1 for arg in",
"\\ child.lineno == num: return child else: if args.pattern in codegen.to_source(child) and \\",
"one option (except -re) can be specified at a time. ''') def get_numlines(node):",
"split in splits: resstring += highlight( split, PythonLexer(), TerminalFormatter() ).strip('\\n') if split !=",
"Args: def __init__(self, args): self.context = False self.cl = False self.func = False",
"[ (num, line) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] first =",
"arg = args[0] if arg == '-re': self.regexp = True args.remove(arg) if arg",
"def usage(): print(''' usage: pytgrep [-c <depth> | -cl | -f | -re]",
"or ( re.search(args.pattern, line) and args.regexp ): a = mhighlight(num, line, args.pattern, args.regexp)",
"= patt.split(string) found = patt.findall(string) for i in range(len(found)): resstring += highlight( splits[i],",
"root, args) if pattern_node is None: continue else: while objsearch not in str(pattern_node):",
"class_parse(args) elif args.context: results = context_parse(args) else: with open(args.path) as f: ln =",
"import codegen def usage(): print(''' usage: pytgrep [-c <depth> | -cl | -f",
"line or ( args.regexp and re.search(args.pattern, line) )) and (num, line) not in",
"| -cl | -f | -re] (optional) pattern file file should be python",
"for ch in ast.iter_child_nodes(child): if hasattr(ch, 'lineno'): ints.append(ch.lineno) return max(ints) def class_parse(args): if",
"1 if len(args) != 0: print(args) for arg in args: print('{} is not",
"str(pattern_node): if pattern_node.parent is root: break pattern_node = pattern_node.parent curres = [] if",
"if pattern_node is not root.body[0]: top = root.body[root.body.index(pattern_node)-1] first_top = top.lineno end_top =",
"args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] added_lines +=",
"as f: ln = 0 curres = '' for num, line in enumerate(f,",
"True: if pattern_node is not root.body[0]: top = root.body[root.body.index(pattern_node)-1] first_top = top.lineno end_top",
"first )] if pattern_node is not root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno",
"None self.regexp = False self.args = self.parseargs(args) def parseargs(self, args): if len(args) ==",
"arg == '-cl': self.cl = True args.remove(arg) elif arg == '-h': return 1",
"arg == '-f': self.func = True args.remove(arg) if not os.path.exists(args[-1]): print('Error: no file",
"pattern_node is not root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno if first_bottom -",
"args.args == 1: usage() sys.exit(1) else: print('\\n' + parse(args)) if __name__ == '__main__':",
"= find_match_node(results, num, root, args) if pattern_node is None: continue else: while objsearch",
"resstring += highlight( splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring +=",
"of -cl, -c, -f can be used at a time') return 1 return",
"(num, line) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] else: curres",
"in ast.iter_child_nodes(node): child.parent = node # search for pattern for num, line in",
"ch in ast.iter_child_nodes(child): if hasattr(ch, 'lineno'): ints.append(ch.lineno) return max(ints) def class_parse(args): if args.cl:",
"args[-1] args.remove(args[-1]) if len(args) != 0: self.pattern = args[-1] args.remove(args[-1]) else: print('Error: there",
"pattern_node.parent is root: top_root = True else: for i in range(args.depth): pattern_node =",
"f.read() results = [] added_lines = [] root = ast.parse(content) for node in",
"open(args[-1]) as f: line = f.readline(0) if '#!' not in line and 'python'",
"added_lines: pattern_node = find_match_node(results, num, root, args) if pattern_node is None: continue top_root",
"for num, line in enumerate(content.splitlines()[first-1:end], first) ] added_lines += [ (num, line) for",
"in line: print('Error: {} is not a python script'.format(args[-1])) return 1 self.path =",
"+= a else: results.append(curres) curres = a ln = num results.append(curres) if ''.join(results)",
"first = end_top+1 else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_top,",
"curres += [ mhighlight( num, line, args.pattern, args.regexp ) for num, line in",
"first_bottom )] else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom",
"= '' for num, line in enumerate(f, 1): if args.pattern in line or",
"1 if len( [arg for arg in [self.cl, self.func, self.context] if arg is",
"in [self.cl, self.func, self.context] if arg is True] ) > 1: print('Error: Only",
"[arg for arg in [self.cl, self.func, self.context] if arg is True] ) >",
"= root.body[root.body.index(pattern_node)-1] first_top = top.lineno end_top = get_end(top) if end_top - first_top <",
"is not a python script'.format(args[-1])) return 1 self.path = args[-1] args.remove(args[-1]) if len(args)",
"pattern_node is not root.body[0]: top = root.body[root.body.index(pattern_node)-1] first_top = top.lineno end_top = get_end(top)",
"+= [ (num, line) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] first",
"-cl | -f | -re] (optional) pattern file file should be python script",
"and args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth = 1 args.remove(arg) elif arg",
"elif arg == '-c': self.context = True if arg != args[-1] and args[args.index(arg)+1].isdigit():",
"- first_top < 3: curres += [ mhighlight( num, line, args.pattern, args.regexp )",
"line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def parse(args): results =",
"if pattern in string or (regexp is True and re.search(pattern, string)): pass else:",
"line and 'python' not in line: print('Error: {} is not a python script'.format(args[-1]))",
"content.splitlines()[first_top-1] )] first = end_top+1 curres += [ mhighlight( num, line, args.pattern, args.regexp",
"pattern is regexp Note: only one option (except -re) can be specified at",
"script'.format(args[-1])) return 1 self.path = args[-1] args.remove(args[-1]) if len(args) != 0: self.pattern =",
"enumerate(content.splitlines()[first-1:end], first) ] added_lines += [ (num, line) for num, line in enumerate(",
")) and (num, line) not in added_lines: pattern_node = find_match_node(results, num, root, args)",
"get_end(pattern_node) curres += [ mhighlight( num, line, args.pattern, args.regexp ) for num, line",
"False: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits = string.split(pattern) for split in splits: resstring",
"not in str(pattern_node): if pattern_node.parent is root: break pattern_node = pattern_node.parent curres =",
"+= '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring += highlight( splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n') return resstring +",
"-re) can be specified at a time. ''') def get_numlines(node): return len(codegen.to_source(node).splitlines()) def",
"end = get_end(pattern_node) curres += [ mhighlight( num, line, args.pattern, args.regexp ) for",
"first_bottom < 3: curres += [ mhighlight( num, line, args.pattern, args.regexp ) for",
"arguments: -h show this page -c [depth] show context of the string. -cl",
"= context_parse(args) else: with open(args.path) as f: ln = 0 curres = ''",
"= a ln = num results.append(curres) if ''.join(results) == '': results = []",
"self.func, self.context] if arg is True] ) > 1: print('Error: Only one of",
"enumerate(f, 1): if args.pattern in line or ( re.search(args.pattern, line) and args.regexp ):",
"True] ) > 1: print('Error: Only one of -cl, -c, -f can be",
"'='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def main(): args = Args(sys.argv[1:]) if args.args == 1: usage()",
"line in enumerate(f, 1): if args.pattern in line or ( re.search(args.pattern, line) and",
"args.regexp ) for num, line in enumerate(content.splitlines()[first-1:end], first) ] added_lines += [ (num,",
"can be used at a time') return 1 return 0 def find_match_node(results, num,",
"option (except -re) can be specified at a time. ''') def get_numlines(node): return",
"num, root, args): for node in ast.walk(root): for child in ast.iter_child_nodes(node): if args.regexp:",
"pygments import highlight from pygments.formatters.terminal import TerminalFormatter import shutil import re import ast",
"return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def main(): args = Args(sys.argv[1:]) if args.args",
"found[i].strip('\\n')) resstring += highlight( splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n') return resstring + '\\n' class",
"recognized option'.format(arg)) return 1 if len( [arg for arg in [self.cl, self.func, self.context]",
"split != splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring + '\\n' else: resstring",
"'-re': self.regexp = True args.remove(arg) if arg == '-cl': self.cl = True args.remove(arg)",
"= True if arg != args[-1] and args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else:",
"args.regexp ): a = mhighlight(num, line, args.pattern, args.regexp) if num == ln +",
"f: content = f.read() results = [] added_lines = [] root = ast.parse(content)",
"= bottom.lineno if first_bottom - end > 1: added_lines += content.splitlines()[ end:first_bottom] end_bottom",
"pattern in string or (regexp is True and re.search(pattern, string)): pass else: pattern",
"= patt.findall(string) for i in range(len(found)): resstring += highlight( splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n')",
"for child in ast.iter_child_nodes(node): if args.regexp: pattern = re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and \\",
"end > 1: added_lines += content.splitlines()[ end:first_bottom] end_bottom = get_end(bottom) if end_bottom -",
"else: with open(args.path) as f: ln = 0 curres = '' for num,",
"get_end(top) if end_top - first_top < 3: curres += [ mhighlight( num, line,",
"pattern_node = pattern_node.parent if pattern_node.parent is root: top_root = True break first =",
"first_bottom-1:end_bottom], first_bottom )] added_lines += [ (num, line) for num, line in enumerate(",
"= args[-1] args.remove(args[-1]) if len(args) != 0: self.pattern = args[-1] args.remove(args[-1]) else: print('Error:",
"results = context_parse(args) else: with open(args.path) as f: ln = 0 curres =",
"is not recognized option'.format(arg)) return 1 if len( [arg for arg in [self.cl,",
"first_top = top.lineno end_top = get_end(top) if end_top - first_top < 3: curres",
"return len(codegen.to_source(node).splitlines()) def mhighlight(num, string, pattern, regexp): if pattern in string or (regexp",
"= ast.parse(content) for node in ast.walk(root): for child in ast.iter_child_nodes(node): child.parent = node",
"len(args) != 0: print(args) for arg in args: print('{} is not recognized option'.format(arg))",
").strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring += highlight( splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n') return",
"page -c [depth] show context of the string. -cl show class containing string",
"not in line and 'python' not in line: print('Error: {} is not a",
"args.regexp and re.search(args.pattern, line) )) and (num, line) not in added_lines: pattern_node =",
"a ln = num results.append(curres) if ''.join(results) == '': results = [] return",
"not a python script'.format(args[-1])) return 1 self.path = args[-1] args.remove(args[-1]) if len(args) !=",
"enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] added_lines += [ (num, line) for num, line",
"(regexp is True and re.search(pattern, string)): pass else: pattern = None if not",
"= False if pattern_node.parent is root: top_root = True else: for i in",
"in ast.walk(root): for child in ast.iter_child_nodes(node): child.parent = node # search for pattern",
"[self.cl, self.func, self.context] if arg is True] ) > 1: print('Error: Only one",
"show function containing string (ignored if no function) -re pattern is regexp Note:",
"+= content.splitlines()[ end:first_bottom] end_bottom = get_end(bottom) if end_bottom - first_bottom < 3: curres",
"in str(pattern_node): if pattern_node.parent is root: break pattern_node = pattern_node.parent curres = []",
").strip('\\n') return resstring + '\\n' class Args: def __init__(self, args): self.context = False",
"= True args.remove(arg) elif arg == '-h': return 1 elif arg == '-c':",
"this page -c [depth] show context of the string. -cl show class containing",
"args[0] if arg == '-re': self.regexp = True args.remove(arg) if arg == '-cl':",
"= f.readline(0) if '#!' not in line and 'python' not in line: print('Error:",
"option'.format(arg)) return 1 if len( [arg for arg in [self.cl, self.func, self.context] if",
"= 1 args.remove(arg) elif arg == '-f': self.func = True args.remove(arg) if not",
"len(args) == 0: return 1 for arg in args: arg = args[0] if",
"and \\ hasattr(child, 'lineno') and \\ child.lineno == num: return child else: if",
"print('Error: {} is not a python script'.format(args[-1])) return 1 self.path = args[-1] args.remove(args[-1])",
"= False self.depth = 0 self.path = None self.pattern = None self.regexp =",
"if pattern_node.parent is root: break pattern_node = pattern_node.parent curres = [] if objsearch",
"patt.split(string) found = patt.findall(string) for i in range(len(found)): resstring += highlight( splits[i], PythonLexer(),",
"return 1 elif arg == '-c': self.context = True if arg != args[-1]",
"= 'FunctionDef' with open(args.path) as f: content = f.read() results = [] added_lines",
"codegen def usage(): print(''' usage: pytgrep [-c <depth> | -cl | -f |",
"[ (num, line) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] else:",
"[] if args.cl or args.func: results = class_parse(args) elif args.context: results = context_parse(args)",
"search pattern') return 1 if len(args) != 0: print(args) for arg in args:",
"else: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt = re.compile(pattern) splits = patt.split(string) found =",
"args) if pattern_node is None: continue else: while objsearch not in str(pattern_node): if",
"args.remove(arg) elif arg == '-h': return 1 elif arg == '-c': self.context =",
"ast.parse(content) for node in ast.walk(root): for child in ast.iter_child_nodes(node): child.parent = node #",
"with open(args[-1]) as f: line = f.readline(0) if '#!' not in line and",
"results.append(''.join(curres)) return results def context_parse(args): with open(args.path) as f: content = f.read() results",
"args) if pattern_node is None: continue top_root = False if pattern_node.parent is root:",
"import shutil import re import ast import sys import os from . import",
"optional arguments: -h show this page -c [depth] show context of the string.",
"('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'), )) else: if regexp is False:",
"is regexp Note: only one option (except -re) can be specified at a",
"None self.pattern = None self.regexp = False self.args = self.parseargs(args) def parseargs(self, args):",
"num, line in enumerate( content.splitlines()[first-1:end], first )] if pattern_node is not root.body[-1]: bottom",
"resstring += highlight( splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n') return resstring + '\\n' class Args:",
"[] root = ast.parse(content) for node in ast.walk(root): for child in ast.iter_child_nodes(node): child.parent",
"args.remove(args[args.index(arg)+1]) else: self.depth = 1 args.remove(arg) elif arg == '-f': self.func = True",
"num, line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def context_parse(args): with",
"first_bottom-1:end_bottom], first_bottom )] else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_bottom,",
"args[-1] and args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth = 1 args.remove(arg) elif",
")] if pattern_node is not root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno if",
"there is no search pattern') return 1 if len(args) != 0: print(args) for",
"- first_bottom < 3: curres += [ mhighlight( num, line, args.pattern, args.regexp )",
"= 0 curres = '' for num, line in enumerate(f, 1): if args.pattern",
"PythonLexer(), TerminalFormatter() ).strip('\\n') return resstring + '\\n' class Args: def __init__(self, args): self.context",
"arg is True] ) > 1: print('Error: Only one of -cl, -c, -f",
"'FunctionDef' with open(args.path) as f: content = f.read() results = [] added_lines =",
"line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] else: curres += [('\\033[1;90m{:0>2}' + '",
"(num, line) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] first = end_top+1",
"and 'python' not in line: print('Error: {} is not a python script'.format(args[-1])) return",
"(num, line) not in added_lines: pattern_node = find_match_node(results, num, root, args) if pattern_node",
"+= [ (num, line) for num, line in enumerate( content.splitlines()[first-1:end], first )] if",
"{}---\\033[0;0m\\n').format( first_top, end_top - first_top, content.splitlines()[first_top-1] )] first = end_top+1 curres += [",
"specified at a time. ''') def get_numlines(node): return len(codegen.to_source(node).splitlines()) def mhighlight(num, string, pattern,",
"<depth> | -cl | -f | -re] (optional) pattern file file should be",
"regexp): if pattern in string or (regexp is True and re.search(pattern, string)): pass",
"if end_top - first_top < 3: curres += [ mhighlight( num, line, args.pattern,",
"class) -f show function containing string (ignored if no function) -re pattern is",
"or (regexp is True and re.search(pattern, string)): pass else: pattern = None if",
"'.format(num) splits = string.split(pattern) for split in splits: resstring += highlight( split, PythonLexer(),",
"first )] results.append(''.join(curres)) return results def parse(args): results = [] if args.cl or",
"+= [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom - first_bottom, content.splitlines()[first_bottom-1] )]",
"0 curres = '' for num, line in enumerate(f, 1): if args.pattern in",
"in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] added_lines += [ (num, line) for num,",
"pattern') return 1 if len(args) != 0: print(args) for arg in args: print('{}",
"bottom = root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno if first_bottom - end > 1: added_lines",
"line or ( re.search(args.pattern, line) and args.regexp ): a = mhighlight(num, line, args.pattern,",
"-f can be used at a time') return 1 return 0 def find_match_node(results,",
"args): self.context = False self.cl = False self.func = False self.depth = 0",
"else: if args.pattern in codegen.to_source(child) and \\ hasattr(child, 'lineno') and \\ child.lineno ==",
"self.cl = True args.remove(arg) elif arg == '-h': return 1 elif arg ==",
"no class) -f show function containing string (ignored if no function) -re pattern",
"= '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt = re.compile(pattern) splits = patt.split(string) found = patt.findall(string) for",
"in str(pattern_node): first = pattern_node.lineno end = get_end(pattern_node) curres += [ mhighlight( num,",
"be python script formatted with pep8 guidelines optional arguments: -h show this page",
"= None self.pattern = None self.regexp = False self.args = self.parseargs(args) def parseargs(self,",
"pattern.strip('\\n')) return resstring + '\\n' else: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt = re.compile(pattern)",
"first) ] added_lines += [ (num, line) for num, line in enumerate( content.splitlines()[first-1:end],",
"one of -cl, -c, -f can be used at a time') return 1",
"num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] added_lines += [ (num, line) for",
"if '#!' not in line and 'python' not in line: print('Error: {} is",
"args.remove(arg) if not os.path.exists(args[-1]): print('Error: no file {}'.format(args[-1])) return 1 elif not args[-1].endswith('.py'):",
"f.readline(0) if '#!' not in line and 'python' not in line: print('Error: {}",
"pattern, regexp): if pattern in string or (regexp is True and re.search(pattern, string)):",
"child in ast.walk(node): for ch in ast.iter_child_nodes(child): if hasattr(ch, 'lineno'): ints.append(ch.lineno) return max(ints)",
"end_top+1 curres += [ mhighlight( num, line, args.pattern, args.regexp ) for num, line",
"if len( [arg for arg in [self.cl, self.func, self.context] if arg is True]",
"bottom.lineno if first_bottom - end > 1: added_lines += content.splitlines()[ end:first_bottom] end_bottom =",
"ast import sys import os from . import codegen def usage(): print(''' usage:",
"string, PythonLexer(), TerminalFormatter()).strip('\\n'), )) else: if regexp is False: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num)",
"patt = re.compile(pattern) splits = patt.split(string) found = patt.findall(string) for i in range(len(found)):",
"args.remove(args[-1]) else: print('Error: there is no search pattern') return 1 if len(args) !=",
"print(''' usage: pytgrep [-c <depth> | -cl | -f | -re] (optional) pattern",
"= int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth = 1 args.remove(arg) elif arg == '-f': self.func",
"if arg is True] ) > 1: print('Error: Only one of -cl, -c,",
"in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def parse(args): results = []",
"line, args.pattern, args.regexp) if num == ln + 1: curres += a else:",
") for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] added_lines += [ (num,",
"if not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'), )) else:",
"= True break first = pattern_node.lineno end = get_end(pattern_node) curres = [] if",
"return results def parse(args): results = [] if args.cl or args.func: results =",
"def __init__(self, args): self.context = False self.cl = False self.func = False self.depth",
"root, args) if pattern_node is None: continue top_root = False if pattern_node.parent is",
"top_root = True break first = pattern_node.lineno end = get_end(pattern_node) curres = []",
"string)): pass else: pattern = None if not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num,",
"in args: print('{} is not recognized option'.format(arg)) return 1 if len( [arg for",
"be used at a time') return 1 return 0 def find_match_node(results, num, root,",
"in enumerate(content.splitlines()[first-1:end], first) ] added_lines += [ (num, line) for num, line in",
"first = pattern_node.lineno end = get_end(pattern_node) curres = [] if top_root is True:",
"[('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_top, end_top - first_top, content.splitlines()[first_top-1] )] first",
"string, pattern, regexp): if pattern in string or (regexp is True and re.search(pattern,",
"pattern_node.parent is root: top_root = True break first = pattern_node.lineno end = get_end(pattern_node)",
"return 1 elif not args[-1].endswith('.py'): with open(args[-1]) as f: line = f.readline(0) if",
"pep8 guidelines optional arguments: -h show this page -c [depth] show context of",
"and \\ hasattr(child, 'lineno') and \\ child.lineno == num: return child def get_end(node):",
"while objsearch not in str(pattern_node): if pattern_node.parent is root: break pattern_node = pattern_node.parent",
"highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'), )) else: if regexp is False: resstring = '\\033[1;90m{:0>2}\\033[0;0m",
"is not root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno if first_bottom - end",
"search for pattern for num, line in enumerate(content.splitlines(), 1): if (args.pattern in line",
"re import ast import sys import os from . import codegen def usage():",
"node in ast.walk(root): for child in ast.iter_child_nodes(node): child.parent = node # search for",
"at a time. ''') def get_numlines(node): return len(codegen.to_source(node).splitlines()) def mhighlight(num, string, pattern, regexp):",
"f: line = f.readline(0) if '#!' not in line and 'python' not in",
"line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def context_parse(args): with open(args.path)",
"curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom - first_bottom, content.splitlines()[first_bottom-1]",
"function containing string (ignored if no function) -re pattern is regexp Note: only",
"show this page -c [depth] show context of the string. -cl show class",
"+ '\\n' class Args: def __init__(self, args): self.context = False self.cl = False",
"and \\ child.lineno == num: return child def get_end(node): ints = [] ints.append(node.lineno)",
"find_match_node(results, num, root, args) if pattern_node is None: continue else: while objsearch not",
"'\\033[0;0m\\n\\n').join(results) def main(): args = Args(sys.argv[1:]) if args.args == 1: usage() sys.exit(1) else:",
"self.path = args[-1] args.remove(args[-1]) if len(args) != 0: self.pattern = args[-1] args.remove(args[-1]) else:",
"is True and re.search(pattern, string)): pass else: pattern = None if not pattern:",
"if ''.join(results) == '': results = [] return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results)",
"at a time') return 1 return 0 def find_match_node(results, num, root, args): for",
"string or (regexp is True and re.search(pattern, string)): pass else: pattern = None",
"enumerate( content.splitlines()[first_top-1:end_top], first_top )] added_lines += [ (num, line) for num, line in",
"args.regexp ) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] added_lines += [",
"pattern.search(codegen.to_source(child)) and \\ hasattr(child, 'lineno') and \\ child.lineno == num: return child else:",
"in range(len(found)): resstring += highlight( splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n'))",
"if split != splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring + '\\n' else:",
"arg == '-c': self.context = True if arg != args[-1] and args[args.index(arg)+1].isdigit(): self.depth",
"if first_bottom - end > 1: added_lines += content.splitlines()[ end:first_bottom] end_bottom = get_end(bottom)",
"if end_bottom - first_bottom < 3: curres += [ mhighlight( num, line, args.pattern,",
"in ast.walk(root): for child in ast.iter_child_nodes(node): if args.regexp: pattern = re.compile(args.pattern) if pattern.search(codegen.to_source(child))",
"open(args.path) as f: ln = 0 curres = '' for num, line in",
"mhighlight(num, line, args.pattern, args.regexp) if num == ln + 1: curres += a",
"False self.func = False self.depth = 0 self.path = None self.pattern = None",
"args.func: results = class_parse(args) elif args.context: results = context_parse(args) else: with open(args.path) as",
"regexp is False: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits = string.split(pattern) for split in",
"1: print('Error: Only one of -cl, -c, -f can be used at a",
"context of the string. -cl show class containing string (ignored if no class)",
"if pattern.search(codegen.to_source(child)) and \\ hasattr(child, 'lineno') and \\ child.lineno == num: return child",
"(optional) pattern file file should be python script formatted with pep8 guidelines optional",
"args.remove(args[-1]) if len(args) != 0: self.pattern = args[-1] args.remove(args[-1]) else: print('Error: there is",
"[] ints.append(node.lineno) for child in ast.walk(node): for ch in ast.iter_child_nodes(child): if hasattr(ch, 'lineno'):",
"-cl show class containing string (ignored if no class) -f show function containing",
"\\ hasattr(child, 'lineno') and \\ child.lineno == num: return child def get_end(node): ints",
"PythonLexer(), TerminalFormatter() ).strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring += highlight( splits[-1], PythonLexer(), TerminalFormatter()",
"1 return 0 def find_match_node(results, num, root, args): for node in ast.walk(root): for",
"pytgrep [-c <depth> | -cl | -f | -re] (optional) pattern file file",
"[ mhighlight( num, line, args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[",
"!= args[-1] and args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth = 1 args.remove(arg)",
"-h show this page -c [depth] show context of the string. -cl show",
"open(args.path) as f: content = f.read() results = [] added_lines = [] root",
")] results.append(''.join(curres)) return results def context_parse(args): with open(args.path) as f: content = f.read()",
"< 3: curres += [ mhighlight( num, line, args.pattern, args.regexp ) for num,",
"show context of the string. -cl show class containing string (ignored if no",
"content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def parse(args): results = [] if args.cl",
"is False: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits = string.split(pattern) for split in splits:",
"return 1 if len(args) != 0: print(args) for arg in args: print('{} is",
"return 1 if len( [arg for arg in [self.cl, self.func, self.context] if arg",
"False self.cl = False self.func = False self.depth = 0 self.path = None",
"'\\n' else: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt = re.compile(pattern) splits = patt.split(string) found",
"== 0: return 1 for arg in args: arg = args[0] if arg",
"self.func = True args.remove(arg) if not os.path.exists(args[-1]): print('Error: no file {}'.format(args[-1])) return 1",
"child.parent = node # search for pattern for num, line in enumerate(content.splitlines(), 1):",
"is True] ) > 1: print('Error: Only one of -cl, -c, -f can",
"= [] if top_root is True: if pattern_node is not root.body[0]: top =",
"ln = 0 curres = '' for num, line in enumerate(f, 1): if",
"print('Error: Only one of -cl, -c, -f can be used at a time')",
"1: curres += a else: results.append(curres) curres = a ln = num results.append(curres)",
"end_top - first_top < 3: curres += [ mhighlight( num, line, args.pattern, args.regexp",
"child else: if args.pattern in codegen.to_source(child) and \\ hasattr(child, 'lineno') and \\ child.lineno",
"-c, -f can be used at a time') return 1 return 0 def",
"= True args.remove(arg) if not os.path.exists(args[-1]): print('Error: no file {}'.format(args[-1])) return 1 elif",
"[ mhighlight( num, line, args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[first_top-1:end_top],",
"containing string (ignored if no class) -f show function containing string (ignored if",
"self.regexp = True args.remove(arg) if arg == '-cl': self.cl = True args.remove(arg) elif",
"for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] added_lines += [ (num, line)",
"results = [] return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def main(): args =",
"+= highlight( splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring += highlight(",
"or ( args.regexp and re.search(args.pattern, line) )) and (num, line) not in added_lines:",
"function) -re pattern is regexp Note: only one option (except -re) can be",
"!= splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring + '\\n' else: resstring =",
"'python' not in line: print('Error: {} is not a python script'.format(args[-1])) return 1",
"): a = mhighlight(num, line, args.pattern, args.regexp) if num == ln + 1:",
"= False self.args = self.parseargs(args) def parseargs(self, args): if len(args) == 0: return",
"added_lines += [ (num, line) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom",
"args.pattern in codegen.to_source(child) and \\ hasattr(child, 'lineno') and \\ child.lineno == num: return",
"elif args.context: results = context_parse(args) else: with open(args.path) as f: ln = 0",
"class containing string (ignored if no class) -f show function containing string (ignored",
"line, args.pattern, args.regexp ) for num, line in enumerate(content.splitlines()[first-1:end], first) ] added_lines +=",
"splits: resstring += highlight( split, PythonLexer(), TerminalFormatter() ).strip('\\n') if split != splits[-1]: resstring",
"len(args) != 0: self.pattern = args[-1] args.remove(args[-1]) else: print('Error: there is no search",
"no file {}'.format(args[-1])) return 1 elif not args[-1].endswith('.py'): with open(args[-1]) as f: line",
"line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] first = end_top+1 else: curres += [('\\033[1;90m{:0>2}'",
"re.search(args.pattern, line) and args.regexp ): a = mhighlight(num, line, args.pattern, args.regexp) if num",
"TerminalFormatter() ).strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring += highlight( splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n')",
"in enumerate(f, 1): if args.pattern in line or ( re.search(args.pattern, line) and args.regexp",
"- end > 1: added_lines += content.splitlines()[ end:first_bottom] end_bottom = get_end(bottom) if end_bottom",
"def main(): args = Args(sys.argv[1:]) if args.args == 1: usage() sys.exit(1) else: print('\\n'",
"num, highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'), )) else: if regexp is False: resstring =",
"patt.findall(string) for i in range(len(found)): resstring += highlight( splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n') resstring",
"self.pattern = None self.regexp = False self.args = self.parseargs(args) def parseargs(self, args): if",
"arg != args[-1] and args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth = 1",
"and re.search(args.pattern, line) )) and (num, line) not in added_lines: pattern_node = find_match_node(results,",
"def class_parse(args): if args.cl: objsearch = 'ClassDef' elif args.func: objsearch = 'FunctionDef' with",
"for num, line in enumerate(f, 1): if args.pattern in line or ( re.search(args.pattern,",
"if args.cl: objsearch = 'ClassDef' elif args.func: objsearch = 'FunctionDef' with open(args.path) as",
"= node # search for pattern for num, line in enumerate(content.splitlines(), 1): if",
"1): if (args.pattern in line or ( args.regexp and re.search(args.pattern, line) )) and",
"line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] added_lines += [ (num, line) for num,",
"else: if regexp is False: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits = string.split(pattern) for",
"content = f.read() results = [] added_lines = [] root = ast.parse(content) for",
"num results.append(curres) if ''.join(results) == '': results = [] return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0]",
"True if arg != args[-1] and args[args.index(arg)+1].isdigit(): self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth",
"pattern_node = find_match_node(results, num, root, args) if pattern_node is None: continue else: while",
"(num, line) for num, line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results",
"guidelines optional arguments: -h show this page -c [depth] show context of the",
"args): if len(args) == 0: return 1 for arg in args: arg =",
"root: top_root = True else: for i in range(args.depth): pattern_node = pattern_node.parent if",
"pattern file file should be python script formatted with pep8 guidelines optional arguments:",
"enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines:",
"ints.append(ch.lineno) return max(ints) def class_parse(args): if args.cl: objsearch = 'ClassDef' elif args.func: objsearch",
")] else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom -",
"line) for num, line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def",
"not in line: print('Error: {} is not a python script'.format(args[-1])) return 1 self.path",
"and \\ child.lineno == num: return child else: if args.pattern in codegen.to_source(child) and",
"for pattern for num, line in enumerate(content.splitlines(), 1): if (args.pattern in line or",
"num, line in enumerate(content.splitlines()[first-1:end], first) ] added_lines += [ (num, line) for num,",
"line) for num, line in enumerate( content.splitlines()[first-1:end], first )] if pattern_node is not",
"-c [depth] show context of the string. -cl show class containing string (ignored",
"first_bottom - end > 1: added_lines += content.splitlines()[ end:first_bottom] end_bottom = get_end(bottom) if",
"'lineno') and \\ child.lineno == num: return child else: if args.pattern in codegen.to_source(child)",
"in string or (regexp is True and re.search(pattern, string)): pass else: pattern =",
"= get_end(bottom) if end_bottom - first_bottom < 3: curres += [ mhighlight( num,",
"in ast.iter_child_nodes(node): if args.regexp: pattern = re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and \\ hasattr(child, 'lineno')",
"results.append(curres) curres = a ln = num results.append(curres) if ''.join(results) == '': results",
"pattern_node = find_match_node(results, num, root, args) if pattern_node is None: continue top_root =",
"elif args.func: objsearch = 'FunctionDef' with open(args.path) as f: content = f.read() results",
"in enumerate( content.splitlines()[first-1:end], first )] if pattern_node is not root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1]",
"args: arg = args[0] if arg == '-re': self.regexp = True args.remove(arg) if",
"pattern_node = pattern_node.parent curres = [] if objsearch in str(pattern_node): first = pattern_node.lineno",
"return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'), )) else: if regexp is",
"resstring + '\\n' class Args: def __init__(self, args): self.context = False self.cl =",
") > 1: print('Error: Only one of -cl, -c, -f can be used",
"num, root, args) if pattern_node is None: continue else: while objsearch not in",
"if arg == '-cl': self.cl = True args.remove(arg) elif arg == '-h': return",
"line in enumerate(content.splitlines()[first-1:end], first) ] added_lines += [ (num, line) for num, line",
"= pattern_node.parent if pattern_node.parent is root: top_root = True break first = pattern_node.lineno",
"first_bottom, end_bottom - first_bottom, content.splitlines()[first_bottom-1] )] else: curres += [ mhighlight( num, line,",
"ast.walk(root): for child in ast.iter_child_nodes(node): if args.regexp: pattern = re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and",
"print('{} is not recognized option'.format(arg)) return 1 if len( [arg for arg in",
"import os from . import codegen def usage(): print(''' usage: pytgrep [-c <depth>",
"in line and 'python' not in line: print('Error: {} is not a python",
"of the string. -cl show class containing string (ignored if no class) -f",
"= re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and \\ hasattr(child, 'lineno') and \\ child.lineno == num:",
"args.pattern, args.regexp) if num == ln + 1: curres += a else: results.append(curres)",
"print('Error: no file {}'.format(args[-1])) return 1 elif not args[-1].endswith('.py'): with open(args[-1]) as f:",
"= '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits = string.split(pattern) for split in splits: resstring += highlight(",
"num, root, args) if pattern_node is None: continue top_root = False if pattern_node.parent",
"= [] root = ast.parse(content) for node in ast.walk(root): for child in ast.iter_child_nodes(node):",
"split, PythonLexer(), TerminalFormatter() ).strip('\\n') if split != splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return",
"= find_match_node(results, num, root, args) if pattern_node is None: continue top_root = False",
"+= [ (num, line) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )]",
"top.lineno end_top = get_end(top) if end_top - first_top < 3: curres += [",
"string. -cl show class containing string (ignored if no class) -f show function",
"TerminalFormatter() ).strip('\\n') if split != splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring +",
"not root.body[0]: top = root.body[root.body.index(pattern_node)-1] first_top = top.lineno end_top = get_end(top) if end_top",
")] added_lines += [ (num, line) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom],",
"-re pattern is regexp Note: only one option (except -re) can be specified",
") for num, line in enumerate(content.splitlines()[first-1:end], first) ] added_lines += [ (num, line)",
"in args: arg = args[0] if arg == '-re': self.regexp = True args.remove(arg)",
"if not os.path.exists(args[-1]): print('Error: no file {}'.format(args[-1])) return 1 elif not args[-1].endswith('.py'): with",
"( args.regexp and re.search(args.pattern, line) )) and (num, line) not in added_lines: pattern_node",
"in ast.walk(node): for ch in ast.iter_child_nodes(child): if hasattr(ch, 'lineno'): ints.append(ch.lineno) return max(ints) def",
"shutil import re import ast import sys import os from . import codegen",
"'lineno') and \\ child.lineno == num: return child def get_end(node): ints = []",
"mhighlight( num, line, args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom],",
"node in ast.walk(root): for child in ast.iter_child_nodes(node): if args.regexp: pattern = re.compile(args.pattern) if",
"resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring += highlight( splits[-1], PythonLexer(), TerminalFormatter() ).strip('\\n') return resstring",
"+ 1: curres += a else: results.append(curres) curres = a ln = num",
"if num == ln + 1: curres += a else: results.append(curres) curres =",
"-f | -re] (optional) pattern file file should be python script formatted with",
"curres = [] if top_root is True: if pattern_node is not root.body[0]: top",
"'\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt = re.compile(pattern) splits = patt.split(string) found = patt.findall(string) for i",
"- first_top, content.splitlines()[first_top-1] )] first = end_top+1 curres += [ mhighlight( num, line,",
"with open(args.path) as f: content = f.read() results = [] added_lines = []",
"pattern_node.lineno end = get_end(pattern_node) curres = [] if top_root is True: if pattern_node",
"first = pattern_node.lineno end = get_end(pattern_node) curres += [ mhighlight( num, line, args.pattern,",
"if args.pattern in line or ( re.search(args.pattern, line) and args.regexp ): a =",
"end_top - first_top, content.splitlines()[first_top-1] )] first = end_top+1 curres += [ mhighlight( num,",
")] added_lines += [ (num, line) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top",
"= None self.regexp = False self.args = self.parseargs(args) def parseargs(self, args): if len(args)",
"content.splitlines()[first_top-1:end_top], first_top )] first = end_top+1 else: curres += [('\\033[1;90m{:0>2}' + ' +--{}",
"None: continue top_root = False if pattern_node.parent is root: top_root = True else:",
"pattern_node.lineno end = get_end(pattern_node) curres += [ mhighlight( num, line, args.pattern, args.regexp )",
"import sys import os from . import codegen def usage(): print(''' usage: pytgrep",
"return child def get_end(node): ints = [] ints.append(node.lineno) for child in ast.walk(node): for",
"(ignored if no function) -re pattern is regexp Note: only one option (except",
"splits = patt.split(string) found = patt.findall(string) for i in range(len(found)): resstring += highlight(",
"re.compile(pattern) splits = patt.split(string) found = patt.findall(string) for i in range(len(found)): resstring +=",
"== '': results = [] return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def main():",
"num, line in enumerate(content.splitlines(), 1): if (args.pattern in line or ( args.regexp and",
"splits[-1]: resstring += '\\033[1;91m{}\\033[0;0m'.format( pattern.strip('\\n')) return resstring + '\\n' else: resstring = '\\033[1;90m{:0>2}\\033[0;0m",
"sys import os from . import codegen def usage(): print(''' usage: pytgrep [-c",
"self.depth = 0 self.path = None self.pattern = None self.regexp = False self.args",
"for arg in args: arg = args[0] if arg == '-re': self.regexp =",
"if no function) -re pattern is regexp Note: only one option (except -re)",
"enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def parse(args): results = [] if",
"enumerate(content.splitlines(), 1): if (args.pattern in line or ( args.regexp and re.search(args.pattern, line) ))",
"num, line, args.pattern, args.regexp ) for num, line in enumerate(content.splitlines()[first-1:end], first) ] added_lines",
"first_top < 3: curres += [ mhighlight( num, line, args.pattern, args.regexp ) for",
"True and re.search(pattern, string)): pass else: pattern = None if not pattern: return",
"end_top+1 else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_top, end_top -",
"self.depth = int(args[args.index(arg)+1]) args.remove(args[args.index(arg)+1]) else: self.depth = 1 args.remove(arg) elif arg == '-f':",
"pattern_node is None: continue top_root = False if pattern_node.parent is root: top_root =",
"[ (num, line) for num, line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return",
"[] if objsearch in str(pattern_node): first = pattern_node.lineno end = get_end(pattern_node) curres +=",
"ints.append(node.lineno) for child in ast.walk(node): for ch in ast.iter_child_nodes(child): if hasattr(ch, 'lineno'): ints.append(ch.lineno)",
"== '-c': self.context = True if arg != args[-1] and args[args.index(arg)+1].isdigit(): self.depth =",
"child in ast.iter_child_nodes(node): if args.regexp: pattern = re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and \\ hasattr(child,",
"\\ hasattr(child, 'lineno') and \\ child.lineno == num: return child else: if args.pattern",
"1 args.remove(arg) elif arg == '-f': self.func = True args.remove(arg) if not os.path.exists(args[-1]):",
"codegen.to_source(child) and \\ hasattr(child, 'lineno') and \\ child.lineno == num: return child def",
"break pattern_node = pattern_node.parent curres = [] if objsearch in str(pattern_node): first =",
"= get_end(pattern_node) curres += [ mhighlight( num, line, args.pattern, args.regexp ) for num,",
"line) and args.regexp ): a = mhighlight(num, line, args.pattern, args.regexp) if num ==",
"be specified at a time. ''') def get_numlines(node): return len(codegen.to_source(node).splitlines()) def mhighlight(num, string,",
"first_bottom )] added_lines += [ (num, line) for num, line in enumerate( content.splitlines()[",
")] first = end_top+1 curres += [ mhighlight( num, line, args.pattern, args.regexp )",
"= mhighlight(num, line, args.pattern, args.regexp) if num == ln + 1: curres +=",
"True args.remove(arg) if not os.path.exists(args[-1]): print('Error: no file {}'.format(args[-1])) return 1 elif not",
"-cl, -c, -f can be used at a time') return 1 return 0",
"for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] else: curres += [('\\033[1;90m{:0>2}'",
"return results def context_parse(args): with open(args.path) as f: content = f.read() results =",
"+= [('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_top, end_top - first_top, content.splitlines()[first_top-1] )]",
"= [] return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def main(): args = Args(sys.argv[1:])",
"1 elif not args[-1].endswith('.py'): with open(args[-1]) as f: line = f.readline(0) if '#!'",
"child.lineno == num: return child else: if args.pattern in codegen.to_source(child) and \\ hasattr(child,",
"= f.read() results = [] added_lines = [] root = ast.parse(content) for node",
"objsearch in str(pattern_node): first = pattern_node.lineno end = get_end(pattern_node) curres += [ mhighlight(",
"+ '\\n' else: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt = re.compile(pattern) splits = patt.split(string)",
"first_top )] added_lines += [ (num, line) for num, line in enumerate( content.splitlines()[first_top-1:end_top],",
"'#!' not in line and 'python' not in line: print('Error: {} is not",
"args.pattern, args.regexp ) for num, line in enumerate(content.splitlines()[first-1:end], first) ] added_lines += [",
"= True args.remove(arg) if arg == '-cl': self.cl = True args.remove(arg) elif arg",
"'\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits = string.split(pattern) for split in splits: resstring += highlight( split,",
"[('\\033[1;90m{:0>2}' + ' +--{} lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom - first_bottom, content.splitlines()[first_bottom-1] )] else:",
"print('Error: there is no search pattern') return 1 if len(args) != 0: print(args)",
"== '-f': self.func = True args.remove(arg) if not os.path.exists(args[-1]): print('Error: no file {}'.format(args[-1]))",
"objsearch not in str(pattern_node): if pattern_node.parent is root: break pattern_node = pattern_node.parent curres",
"pygments.lexers.python import PythonLexer from pygments import highlight from pygments.formatters.terminal import TerminalFormatter import shutil",
"!= 0: print(args) for arg in args: print('{} is not recognized option'.format(arg)) return",
")] else: curres += [ mhighlight( num, line, args.pattern, args.regexp ) for num,",
"resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits = string.split(pattern) for split in splits: resstring +=",
"results.append(curres) if ''.join(results) == '': results = [] return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] +",
"= 0 self.path = None self.pattern = None self.regexp = False self.args =",
"+= [ (num, line) for num, line in enumerate( content.splitlines()[first-1:end], first )] results.append(''.join(curres))",
"PythonLexer(), TerminalFormatter()).strip('\\n'), )) else: if regexp is False: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits",
"[] return ('\\n\\033[1;90m' + '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def main(): args = Args(sys.argv[1:]) if",
"1 self.path = args[-1] args.remove(args[-1]) if len(args) != 0: self.pattern = args[-1] args.remove(args[-1])",
"hasattr(child, 'lineno') and \\ child.lineno == num: return child def get_end(node): ints =",
"if objsearch in str(pattern_node): first = pattern_node.lineno end = get_end(pattern_node) curres += [",
"Args(sys.argv[1:]) if args.args == 1: usage() sys.exit(1) else: print('\\n' + parse(args)) if __name__",
"!= 0: self.pattern = args[-1] args.remove(args[-1]) else: print('Error: there is no search pattern')",
"top_root = False if pattern_node.parent is root: top_root = True else: for i",
"(num, line) for num, line in enumerate( content.splitlines()[first-1:end], first )] if pattern_node is",
"elif arg == '-h': return 1 elif arg == '-c': self.context = True",
"[] added_lines = [] root = ast.parse(content) for node in ast.walk(root): for child",
"= top.lineno end_top = get_end(top) if end_top - first_top < 3: curres +=",
"for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] first = end_top+1 else: curres",
"if args.regexp: pattern = re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and \\ hasattr(child, 'lineno') and \\",
"args.regexp ) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] added_lines +=",
"self.context] if arg is True] ) > 1: print('Error: Only one of -cl,",
"for num, line in enumerate( content.splitlines()[first-1:end], first )] if pattern_node is not root.body[-1]:",
"TerminalFormatter()).strip('\\n'), )) else: if regexp is False: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) splits =",
"not root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno if first_bottom - end >",
"is root: break pattern_node = pattern_node.parent curres = [] if objsearch in str(pattern_node):",
"curres = '' for num, line in enumerate(f, 1): if args.pattern in line",
"i in range(len(found)): resstring += highlight( splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format(",
"results def context_parse(args): with open(args.path) as f: content = f.read() results = []",
"return resstring + '\\n' class Args: def __init__(self, args): self.context = False self.cl",
"break first = pattern_node.lineno end = get_end(pattern_node) curres = [] if top_root is",
"end_bottom - first_bottom, content.splitlines()[first_bottom-1] )] else: curres += [ mhighlight( num, line, args.pattern,",
"True args.remove(arg) elif arg == '-h': return 1 elif arg == '-c': self.context",
"if pattern_node.parent is root: top_root = True else: for i in range(args.depth): pattern_node",
"self.depth = 1 args.remove(arg) elif arg == '-f': self.func = True args.remove(arg) if",
"results = [] added_lines = [] root = ast.parse(content) for node in ast.walk(root):",
"or args.func: results = class_parse(args) elif args.context: results = context_parse(args) else: with open(args.path)",
"for node in ast.walk(root): for child in ast.iter_child_nodes(node): if args.regexp: pattern = re.compile(args.pattern)",
"and args.regexp ): a = mhighlight(num, line, args.pattern, args.regexp) if num == ln",
"args[-1] args.remove(args[-1]) else: print('Error: there is no search pattern') return 1 if len(args)",
"pattern = re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and \\ hasattr(child, 'lineno') and \\ child.lineno ==",
"i in range(args.depth): pattern_node = pattern_node.parent if pattern_node.parent is root: top_root = True",
"pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format( num, highlight( string, PythonLexer(), TerminalFormatter()).strip('\\n'), )) else: if regexp",
"1 for arg in args: arg = args[0] if arg == '-re': self.regexp",
"os from . import codegen def usage(): print(''' usage: pytgrep [-c <depth> |",
"parseargs(self, args): if len(args) == 0: return 1 for arg in args: arg",
"the string. -cl show class containing string (ignored if no class) -f show",
"in line or ( args.regexp and re.search(args.pattern, line) )) and (num, line) not",
"first_top, end_top - first_top, content.splitlines()[first_top-1] )] first = end_top+1 curres += [ mhighlight(",
"content.splitlines()[first-1:end], first )] results.append(''.join(curres)) return results def context_parse(args): with open(args.path) as f: content",
"line: print('Error: {} is not a python script'.format(args[-1])) return 1 self.path = args[-1]",
"in enumerate(content.splitlines(), 1): if (args.pattern in line or ( args.regexp and re.search(args.pattern, line)",
"added_lines += [ (num, line) for num, line in enumerate( content.splitlines()[first-1:end], first )]",
"root: top_root = True break first = pattern_node.lineno end = get_end(pattern_node) curres =",
"if len(args) != 0: self.pattern = args[-1] args.remove(args[-1]) else: print('Error: there is no",
"get_end(bottom) if end_bottom - first_bottom < 3: curres += [ mhighlight( num, line,",
"= root.body[root.body.index(pattern_node)+1] first_bottom = bottom.lineno if first_bottom - end > 1: added_lines +=",
"arg in args: print('{} is not recognized option'.format(arg)) return 1 if len( [arg",
"for num, line in enumerate(content.splitlines(), 1): if (args.pattern in line or ( args.regexp",
"for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] added_lines += [ (num,",
"added_lines += content.splitlines()[ end:first_bottom] end_bottom = get_end(bottom) if end_bottom - first_bottom < 3:",
"top_root is True: if pattern_node is not root.body[0]: top = root.body[root.body.index(pattern_node)-1] first_top =",
"content.splitlines()[ end:first_bottom] end_bottom = get_end(bottom) if end_bottom - first_bottom < 3: curres +=",
"== '-re': self.regexp = True args.remove(arg) if arg == '-cl': self.cl = True",
"def find_match_node(results, num, root, args): for node in ast.walk(root): for child in ast.iter_child_nodes(node):",
"string (ignored if no class) -f show function containing string (ignored if no",
"as f: content = f.read() results = [] added_lines = [] root =",
"and re.search(pattern, string)): pass else: pattern = None if not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m",
"re.search(pattern, string)): pass else: pattern = None if not pattern: return ('\\033[1;90m{:0>2}\\033[0;0m {}\\n'.format(",
"string (ignored if no function) -re pattern is regexp Note: only one option",
"self.args = self.parseargs(args) def parseargs(self, args): if len(args) == 0: return 1 for",
"args.remove(arg) if arg == '-cl': self.cl = True args.remove(arg) elif arg == '-h':",
"added_lines = [] root = ast.parse(content) for node in ast.walk(root): for child in",
"first_bottom, content.splitlines()[first_bottom-1] )] else: curres += [ mhighlight( num, line, args.pattern, args.regexp )",
"+ '='*shutil.get_terminal_size()[0] + '\\033[0;0m\\n\\n').join(results) def main(): args = Args(sys.argv[1:]) if args.args == 1:",
"self.cl = False self.func = False self.depth = 0 self.path = None self.pattern",
"' +--{} lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom - first_bottom, content.splitlines()[first_bottom-1] )] else: curres +=",
"range(len(found)): resstring += highlight( splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring",
"== '-h': return 1 elif arg == '-c': self.context = True if arg",
"str(pattern_node): first = pattern_node.lineno end = get_end(pattern_node) curres += [ mhighlight( num, line,",
"and (num, line) not in added_lines: pattern_node = find_match_node(results, num, root, args) if",
"pattern_node.parent is root: break pattern_node = pattern_node.parent curres = [] if objsearch in",
"is None: continue else: while objsearch not in str(pattern_node): if pattern_node.parent is root:",
"num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )] first = end_top+1 else: curres +=",
"content.splitlines()[first_top-1:end_top], first_top )] added_lines += [ (num, line) for num, line in enumerate(",
"return resstring + '\\n' else: resstring = '\\033[1;90m{:0>2}\\033[0;0m '.format(num) patt = re.compile(pattern) splits",
"in enumerate( content.splitlines()[first_top-1:end_top], first_top )] first = end_top+1 else: curres += [('\\033[1;90m{:0>2}' +",
"TerminalFormatter import shutil import re import ast import sys import os from .",
"def get_numlines(node): return len(codegen.to_source(node).splitlines()) def mhighlight(num, string, pattern, regexp): if pattern in string",
"child def get_end(node): ints = [] ints.append(node.lineno) for child in ast.walk(node): for ch",
"line) )) and (num, line) not in added_lines: pattern_node = find_match_node(results, num, root,",
"get_end(node): ints = [] ints.append(node.lineno) for child in ast.walk(node): for ch in ast.iter_child_nodes(child):",
"enumerate( content.splitlines()[first_top-1:end_top], first_top )] first = end_top+1 else: curres += [('\\033[1;90m{:0>2}' + '",
"num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom )] added_lines += [ (num, line)",
"0: print(args) for arg in args: print('{} is not recognized option'.format(arg)) return 1",
"if no class) -f show function containing string (ignored if no function) -re",
"Note: only one option (except -re) can be specified at a time. ''')",
"end_top = get_end(top) if end_top - first_top < 3: curres += [ mhighlight(",
"line in enumerate( content.splitlines()[first-1:end], first )] if pattern_node is not root.body[-1]: bottom =",
"enumerate( content.splitlines()[first-1:end], first )] if pattern_node is not root.body[-1]: bottom = root.body[root.body.index(pattern_node)+1] first_bottom",
"splits[i], PythonLexer(), TerminalFormatter() ).strip('\\n') resstring += '\\033[1;91m{}\\033[0;0m'.format( found[i].strip('\\n')) resstring += highlight( splits[-1], PythonLexer(),",
"args.pattern in line or ( re.search(args.pattern, line) and args.regexp ): a = mhighlight(num,",
"child.lineno == num: return child def get_end(node): ints = [] ints.append(node.lineno) for child",
"return 1 return 0 def find_match_node(results, num, root, args): for node in ast.walk(root):",
"in ast.iter_child_nodes(child): if hasattr(ch, 'lineno'): ints.append(ch.lineno) return max(ints) def class_parse(args): if args.cl: objsearch",
"> 1: print('Error: Only one of -cl, -c, -f can be used at",
"context_parse(args): with open(args.path) as f: content = f.read() results = [] added_lines =",
"splits = string.split(pattern) for split in splits: resstring += highlight( split, PythonLexer(), TerminalFormatter()",
"if args.pattern in codegen.to_source(child) and \\ hasattr(child, 'lineno') and \\ child.lineno == num:",
"num, line, args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[first_top-1:end_top], first_top )]",
"first_top )] first = end_top+1 else: curres += [('\\033[1;90m{:0>2}' + ' +--{} lines:",
"ast.iter_child_nodes(node): if args.regexp: pattern = re.compile(args.pattern) if pattern.search(codegen.to_source(child)) and \\ hasattr(child, 'lineno') and",
"line = f.readline(0) if '#!' not in line and 'python' not in line:",
"[] if top_root is True: if pattern_node is not root.body[0]: top = root.body[root.body.index(pattern_node)-1]",
"root, args): for node in ast.walk(root): for child in ast.iter_child_nodes(node): if args.regexp: pattern",
"if args.args == 1: usage() sys.exit(1) else: print('\\n' + parse(args)) if __name__ ==",
"+ ' +--{} lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom - first_bottom, content.splitlines()[first_bottom-1] )] else: curres",
"+--{} lines: {}---\\033[0;0m\\n').format( first_bottom, end_bottom - first_bottom, content.splitlines()[first_bottom-1] )] else: curres += [",
"as f: line = f.readline(0) if '#!' not in line and 'python' not",
"num, line, args.pattern, args.regexp ) for num, line in enumerate( content.splitlines()[ first_bottom-1:end_bottom], first_bottom",
"{}---\\033[0;0m\\n').format( first_bottom, end_bottom - first_bottom, content.splitlines()[first_bottom-1] )] else: curres += [ mhighlight( num,"
] |
[
"# See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): # define the",
"# https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): # define the fields for your item",
"for your item here like: # name = scrapy.Field() Name = scrapy.Field() Description",
"= scrapy.Field() Description = scrapy.Field() Language = scrapy.Field() Link = scrapy.Field() Time =",
"your item here like: # name = scrapy.Field() Name = scrapy.Field() Description =",
"documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): # define the fields for",
"here like: # name = scrapy.Field() Name = scrapy.Field() Description = scrapy.Field() Language",
"# # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): # define",
"items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): #",
"Description = scrapy.Field() Language = scrapy.Field() Link = scrapy.Field() Time = scrapy.Field() #pass",
"scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item):",
"https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): # define the fields for your item here",
"= scrapy.Field() Name = scrapy.Field() Description = scrapy.Field() Language = scrapy.Field() Link =",
"<reponame>movingpictures83/PluMA-GUI # Define here the models for your scraped items # # See",
"PlumaItem(scrapy.Item): # define the fields for your item here like: # name =",
"Name = scrapy.Field() Description = scrapy.Field() Language = scrapy.Field() Link = scrapy.Field() Time",
"scrapy.Field() Description = scrapy.Field() Language = scrapy.Field() Link = scrapy.Field() Time = scrapy.Field()",
"# define the fields for your item here like: # name = scrapy.Field()",
"class PlumaItem(scrapy.Item): # define the fields for your item here like: # name",
"your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class",
"# Define here the models for your scraped items # # See documentation",
"define the fields for your item here like: # name = scrapy.Field() Name",
"fields for your item here like: # name = scrapy.Field() Name = scrapy.Field()",
"name = scrapy.Field() Name = scrapy.Field() Description = scrapy.Field() Language = scrapy.Field() Link",
"See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): # define the fields",
"Define here the models for your scraped items # # See documentation in:",
"here the models for your scraped items # # See documentation in: #",
"the fields for your item here like: # name = scrapy.Field() Name =",
"# name = scrapy.Field() Name = scrapy.Field() Description = scrapy.Field() Language = scrapy.Field()",
"import scrapy class PlumaItem(scrapy.Item): # define the fields for your item here like:",
"for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy",
"item here like: # name = scrapy.Field() Name = scrapy.Field() Description = scrapy.Field()",
"models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import",
"the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html",
"scrapy.Field() Name = scrapy.Field() Description = scrapy.Field() Language = scrapy.Field() Link = scrapy.Field()",
"scrapy class PlumaItem(scrapy.Item): # define the fields for your item here like: #",
"like: # name = scrapy.Field() Name = scrapy.Field() Description = scrapy.Field() Language =",
"in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PlumaItem(scrapy.Item): # define the fields for your"
] |
[
"(inputs['frameid'] < pool_start_frm + span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim == 1",
"otherwise passthrough; training set is ever expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff, list): svm_cutoff",
"assert y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y, pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df =",
"video_rows in video_id_grp: print(\"Found {} frames for video {}\".format(video_rows.shape[0], video_id)) count = 0",
"KIND, either express or implied. # See the License for the specific language",
"dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim == 1 max_ind = np.argmax(dnn_scores) imageid =",
"Unless required by applicable law or agreed to in writing, software # distributed",
"= df[df['video_id'] == vid] # accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--') if",
"max(xlabels), 0, 1.0]) # plt.show() if savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None): paths =",
"output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def __init__(self, df, video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__() df =",
"plt from sklearn.metrics import accuracy_score from sklearn.svm import SVC from sklearn.utils import resample",
"50) print(\"Emulating video '{}' w/ DNN cutoff {}, SVM cutoff {}\".format(video_id, dnn_cutoff, svm_cut))",
"SVM accuracy # tuned_params = { # 'C': [1], # 'kernel': ['linear'], #",
"for pool_start_frm in range(min_frm, max_frm + 1, stride_frms): # print(\"Max pooling between frame",
"np.ones_like(y_test) # write out to global prediction and cumulative JIT training set pred_jit",
"specified! Ignoring dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn",
"file and produce a smaller one :param dataset: :param base_dir: :param jit_data_file: :param",
"# feeds leveraging edge servers. # # Copyright (C) 2018-2019 Carnegie Mellon University",
"window (from t to t+delta_t) # print(\"time window {} to {}\".format(t, t +",
"X_test = np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label']) assert X_test.shape[1] == 1024, str(X_test.shape) # Do",
"and np.count_nonzero(y_jit == 0) >= activate_threshold \\ and (augment_positive or np.count_nonzero(y_jit == 1)",
"savefig=None): df = pd.read_csv( input_file, sep=r'\\s+' ) print df xlabels = map(int, df.columns[2:])",
"super(StealPositiveFromVideoEnd, self).__init__() df = df[(df['videoid'] == video_id) & (df['label'].astype(bool))] df = df.sort_values(by=['frameid']) #",
"_split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs * 30) stride_frms =",
"downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def __init__(self, df, video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__() df = df[(df['videoid']",
"paths: print(\"Parsing {}\".format(path)) df1 = pd.read_csv(path, sep=' ') df = df.append(df1, ignore_index=True) print",
"# df = df[df['delta_t'] < 90] video_ids = set(df['video_id']) fig, ax1 = plt.subplots()",
"fig, ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1)) ax2 =",
"= np.ones_like(y_test) # write out to global prediction and cumulative JIT training set",
"result_df.append(rv, ignore_index=True) print result_df if output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10, activate_threshold=5,",
"the License. import glob import fire import matplotlib import numpy as np import",
"'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit, 'label': y, 'video_id': video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True)",
"df_video = df[df['video_id'] == vid] # accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--')",
"same pred_jit = y[:0] # store SVM's prediction on DNN's positive frames clf",
"== 1024 # print(\"Found {} frames in window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now,",
">= activate_threshold): print(\"retraining\") if not np.count_nonzero(y_jit == 1) >= activate_threshold and augment_positive: print(\"Houston,",
"unique_videos: for dnn_cutoff in dnn_cutoff_list: for svm_cut in svm_cutoff: print(\"-\" * 50) print(\"Emulating",
"assert X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train = X_jit",
"sklearn.metrics import accuracy_score from sklearn.svm import SVC from sklearn.utils import resample from jitl_data",
"in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn cutoff list: {}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file) print",
"# print df_test.iloc[:5] if df_test.empty: continue X_test = np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label']) assert",
"this file except in compliance with the License. # You may obtain a",
"df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda",
"have {} images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\") print downsample_df.iloc[::downsample_df.shape[0] / 10] if output_file: downsample_df.to_pickle(output_file)",
"# refit=True) clf = SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train) else: print(\"NOT",
"[1], # 'kernel': ['linear'], # } # clf = GridSearchCV(SVC(random_state=43, # max_iter=100, #",
"for passing early discard filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, # train every 10s activate_threshold=5,",
"X_jit.shape[1] == 1024 # print(\"Found {} frames in window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) #",
"(from t to t+delta_t) # print(\"time window {} to {}\".format(t, t + delta_t))",
"produce a smaller one :param dataset: :param base_dir: :param jit_data_file: :param mp_span_secs: :param",
"class StealPositiveFromVideoEnd(object): def __init__(self, df, video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__() df = df[(df['videoid'] ==",
"set(df['videoid'].tolist()) result_df = pd.DataFrame() for video_id in unique_videos: for dnn_cutoff in dnn_cutoff_list: for",
"0: print(\"DNN fires nothing. Stop\") return None print(\"DNN fires {} frames\".format(len(dnn_fire_index))) df =",
"prediction (DNN says all are positive) predictions = np.ones_like(y_test) # write out to",
"# 'kernel': ['linear'], # } # clf = GridSearchCV(SVC(random_state=43, # max_iter=100, # class_weight='balanced',",
"a new SVM? print(\"JIT training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) > 0 \\",
"# print df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] == 2, dnn_proba.shape dnn_fire =",
"= np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label']) assert X_test.shape[1] == 1024, str(X_test.shape) # Do we",
"y_jit # use grid search to improve SVM accuracy # tuned_params = {",
"SVM, # otherwise passthrough; training set is ever expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff,",
"training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) > 0 \\ and np.count_nonzero(y_jit == 0)",
"df['imageid'].tolist() max_frame = df['frameid'].max() print(\"Max frame ID: {}\".format(max_frame)) X_jit = X[:0] # cumulative,",
"expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff, list): svm_cutoff = [svm_cutoff] if dnn_threshold_input_file is not",
"ANY KIND, either express or implied. # See the License for the specific",
"print(\"loaded dnn cutoff threshold is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list = [0.01 * x for",
"range(min_frm, max_frm + 1, stride_frms): # print(\"Max pooling between frame {} and {}\".format(pool_start_frm,",
"[svm_cutoff] if dnn_threshold_input_file is not None: print(\"Warning: Dnn_threshold_input_file is specified! Ignoring dnn_cutoff_start, dnn_cutoff_end,",
"y_jit = np.append(y_jit, y_test[sent_mask], axis=0) assert X_jit.shape[1] == 1024 # print(\"Found {} frames",
"= [svm_cutoff] if dnn_threshold_input_file is not None: print(\"Warning: Dnn_threshold_input_file is specified! Ignoring dnn_cutoff_start,",
"predictions = clf.predict(X_test) else: # pass-through DNN's prediction (DNN says all are positive)",
"stride_frms)) downsample_df = pd.DataFrame() video_id_grp = df.groupby(['videoid']) for video_id, video_rows in video_id_grp: print(\"Found",
"> 0 \\ and np.count_nonzero(y_jit == 0) >= activate_threshold \\ and (augment_positive or",
"y_test = np.array(df_test['label']) assert X_test.shape[1] == 1024, str(X_test.shape) # Do we have an",
"eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn threshold for passing early discard filter dnn_cutoff_end=100,",
"= None min_frm = inputs['frameid'].min() max_frm = inputs['frameid'].max() for pool_start_frm in range(min_frm, max_frm",
"+= 1 print(\"Sample {}/{} frames from video {}\".format(count, video_rows.shape[0], video_id)) downsample_df = downsample_df.sort_values(by=['imageid'])",
"continue X_test = np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label']) assert X_test.shape[1] == 1024, str(X_test.shape) #",
"== 1) >= activate_threshold and augment_positive: print(\"Houston, we don't have enough TPs.\") augment_pos_X",
"y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y, pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t':",
"'label': y, 'video_id': video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True) print res_df return res_df def plot_frame_accuracy(input_file,",
"{}, SVM cutoff {}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\" * 50) rv = run_once_jit_svm_on_video(df, video_id,",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"frames for video {}\".format(video_rows.shape[0], video_id)) count = 0 gridxy_grp = video_rows.groupby(['grid_x', 'grid_y']) for",
"= df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos =",
"1] >= svm_cutoff) # predictions = clf.predict(X_test) else: # pass-through DNN's prediction (DNN",
"+ span_frms)) pool_images = inputs[(inputs['frameid'] >= pool_start_frm) & (inputs['frameid'] < pool_start_frm + span_frms)]",
"pool_start_frm in range(min_frm, max_frm + 1, stride_frms): # print(\"Max pooling between frame {}",
"= pool_images['imageid'].iloc[max_ind] if imageid != last_sent_imageid: # print(\"sampled image: {}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind],",
"{}\".format(dnn_cutoff_list)) else: dnn_cutoff_list = [0.01 * x for x in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)]",
"(smv_proba[:, 1] >= svm_cutoff) # predictions = clf.predict(X_test) else: # pass-through DNN's prediction",
"print(\"Now you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train = X_jit y_jit_train = y_jit #",
"def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn threshold for passing early discard filter",
"ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1)) ax2 = ax1.twinx() ax2.set_ylabel(\"# frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t'])))",
"_split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms =",
"inputs.sort_values(by=['frameid']) last_sent_imageid = None min_frm = inputs['frameid'].min() max_frm = inputs['frameid'].max() for pool_start_frm in",
"and produce a smaller one :param dataset: :param base_dir: :param jit_data_file: :param mp_span_secs:",
"x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos = set(df['videoid'].tolist()) result_df",
"'{}' w/ DNN cutoff {}, SVM cutoff {}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\" * 50)",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"np.count_nonzero(y_jit == 1) >= activate_threshold): print(\"retraining\") if not np.count_nonzero(y_jit == 1) >= activate_threshold",
"print df # df = df[df['delta_t'] < 90] video_ids = set(df['video_id']) fig, ax1",
"== np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y, pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t': delta_t,",
"np.append(X_jit, augment_pos_X, axis=0) y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now",
"print(\"NOT retraining. Nothing new or not enough positives.\") pass assert y.shape == pred_jit.shape,",
"is ever expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff, list): svm_cutoff = [svm_cutoff] if dnn_threshold_input_file",
"res_df return res_df def plot_frame_accuracy(input_file, savefig=None): df = pd.read_csv( input_file, sep=r'\\s+' ) print",
"= df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs *",
"in video_id_grp: print(\"Found {} frames for video {}\".format(video_rows.shape[0], video_id)) count = 0 gridxy_grp",
"resample from jitl_data import _split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run",
"= resample(self.features, n_samples=n, replace=False) return samples def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn",
"servers. # # Copyright (C) 2018-2019 Carnegie Mellon University # # Licensed under",
"OF ANY KIND, either express or implied. # See the License for the",
"gridxy_grp: inputs = inputs.sort_values(by=['frameid']) last_sent_imageid = None min_frm = inputs['frameid'].min() max_frm = inputs['frameid'].max()",
"live video search on drone video # feeds leveraging edge servers. # #",
"positive) predictions = np.ones_like(y_test) # write out to global prediction and cumulative JIT",
"'-o') plt.axis([0, max(xlabels), 0, 1.0]) # plt.show() if savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None):",
"(re-)train a new SVM? print(\"JIT training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) > 0",
"= df_in[df_in['videoid'] == video_id] # print df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] ==",
"= StealPositiveFromVideoEnd(df_in, video_id) for t in range(0, int(1 + (max_frame / 30)), delta_t):",
"print downsample_df.iloc[::downsample_df.shape[0] / 10] if output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def __init__(self, df, video_id,",
"# # A computer vision pipeline for live video search on drone video",
"needed to train the SVM, # otherwise passthrough; training set is ever expanding;",
"JITL input file and produce a smaller one :param dataset: :param base_dir: :param",
"cutoff list: {}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x))",
"# clf = GridSearchCV(SVC(random_state=43, # max_iter=100, # class_weight='balanced', # probability=True, # verbose=True), #",
"ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1)) ax2 = ax1.twinx() ax2.set_ylabel(\"# frames transmitted\")",
"svm_cut)) print(\"-\" * 50) rv = run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df",
"samples def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn threshold for passing early discard",
"dnn_cutoff_list: for svm_cut in svm_cutoff: print(\"-\" * 50) print(\"Emulating video '{}' w/ DNN",
"pass assert y.shape == pred_jit.shape, \"y: {}, pred_jit: {}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0] ==",
"Do we have an SVM to use? if clf: smv_proba = clf.predict_proba(X_test) predictions",
"pool_start_frm + span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim == 1 max_ind =",
"list): # mp_span_secs = [mp_span_secs] # if not isinstance(mp_stride_secs, list): # mp_stride_secs =",
"import fire import matplotlib import numpy as np import pandas as pd from",
"imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos = set(df['videoid'].tolist()) result_df = pd.DataFrame() for video_id in",
"threshold for passing early discard filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, # train every 10s",
"pred_jit: {}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y, pred_jit) print(\"JIT accuracy:",
"imageid = pool_images['imageid'].iloc[max_ind] if imageid != last_sent_imageid: # print(\"sampled image: {}\".format(imageid)) downsample_df =",
"in total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x']",
"to improve SVM accuracy # tuned_params = { # 'C': [1], # 'kernel':",
"augment_pos_X, axis=0) y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now you",
"1)) ax2 = ax1.twinx() ax2.set_ylabel(\"# frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid in",
"glob import fire import matplotlib import numpy as np import pandas as pd",
"Carnegie Mellon University # # Licensed under the Apache License, Version 2.0 (the",
"video {}\".format(count, video_rows.shape[0], video_id)) downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After max pooling, we have {}",
"dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False): # filter df by video id df =",
"SVM? print(\"JIT training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) > 0 \\ and np.count_nonzero(y_jit",
"not np.count_nonzero(y_jit == 1) >= activate_threshold and augment_positive: print(\"Houston, we don't have enough",
"ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--') if savefig: plt.savefig(savefig) plt.show() if __name__ ==",
"search to improve SVM accuracy # tuned_params = { # 'C': [1], #",
"t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1)) ax2 = ax1.twinx() ax2.set_ylabel(\"# frames transmitted\") #",
"t * 30) & (df['frameid'] < (t + delta_t) * 30)] # print",
"pred_jit.shape, \"y: {}, pred_jit: {}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y,",
"+ span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim == 1 max_ind = np.argmax(dnn_scores)",
">= svm_cutoff) # predictions = clf.predict(X_test) else: # pass-through DNN's prediction (DNN says",
"print(\"Found {} frames in window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now, shall we (re-)train",
"set is ever expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff, list): svm_cutoff = [svm_cutoff] if",
"max pooling on a dataset's JITL input file and produce a smaller one",
"# write out to global prediction and cumulative JIT training set pred_jit =",
"df # df = df[df['delta_t'] < 90] video_ids = set(df['video_id']) fig, ax1 =",
"= X_jit y_jit_train = y_jit # use grid search to improve SVM accuracy",
"positive_supply = StealPositiveFromVideoEnd(df_in, video_id) for t in range(0, int(1 + (max_frame / 30)),",
"Drone Search # # A computer vision pipeline for live video search on",
"training set is ever expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff, list): svm_cutoff = [svm_cutoff]",
"1) >= activate_threshold): print(\"retraining\") if not np.count_nonzero(y_jit == 1) >= activate_threshold and augment_positive:",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"= df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda x:",
"# cumulative, used to train JIT SVM y_jit = y[:0] # same pred_jit",
"or np.count_nonzero(y_jit == 1) >= activate_threshold): print(\"retraining\") if not np.count_nonzero(y_jit == 1) >=",
"dnn_cutoff_list.sort() print(\"loaded dnn cutoff threshold is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list = [0.01 * x",
"def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False): # filter df by video",
"input_file, sep=r'\\s+' ) print df xlabels = map(int, df.columns[2:]) for _, row in",
"pred_jit = y[:0] # store SVM's prediction on DNN's positive frames clf =",
"df.iloc[:5] unique_videos = set(df['videoid'].tolist()) result_df = pd.DataFrame() for video_id in unique_videos: for dnn_cutoff",
"row in df.iterrows(): x = xlabels y = np.array(row[2:]) print x, y plt.plot(xlabels,",
"we don't have enough TPs.\") augment_pos_X = positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit, augment_pos_X, axis=0)",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"= df.groupby(['videoid']) for video_id, video_rows in video_id_grp: print(\"Found {} frames for video {}\".format(video_rows.shape[0],",
"improve SVM accuracy # tuned_params = { # 'C': [1], # 'kernel': ['linear'],",
"== y_jit_train.shape[0] print(\"Now you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train = X_jit y_jit_train =",
"for _, row in df.iterrows(): x = xlabels y = np.array(row[2:]) print x,",
"JIT training set pred_jit = np.append(pred_jit, predictions, axis=0) sent_mask = (predictions == 1)",
"result_df if output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False): #",
"self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5): samples = resample(self.features, n_samples=n, replace=False) return samples",
"SVM y_jit = y[:0] # same pred_jit = y[:0] # store SVM's prediction",
"} # clf = GridSearchCV(SVC(random_state=43, # max_iter=100, # class_weight='balanced', # probability=True, # verbose=True),",
"stride frame={}\".format(span_frms, stride_frms)) downsample_df = pd.DataFrame() video_id_grp = df.groupby(['videoid']) for video_id, video_rows in",
"dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit, 'label': y, 'video_id': video_id, 'svm_cutoff': svm_cutoff},",
"np.array(row[2:]) print x, y plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0, max(xlabels), 0, 1.0]) # plt.show()",
"svm_cutoff: print(\"-\" * 50) print(\"Emulating video '{}' w/ DNN cutoff {}, SVM cutoff",
"df['grid_y'] = df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs * 30) stride_frms = int(mp_stride_secs",
"video id df = df_in[df_in['videoid'] == video_id] # print df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist())",
"plt.show() if savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None): paths = glob.glob(file_glob) df = pd.DataFrame()",
"{}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\" * 50) rv = run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold,",
":param mp_span_secs: :param mp_stride_secs: :return: \"\"\" # if not isinstance(mp_span_secs, list): # mp_span_secs",
"'jitl_prediction': pred_jit, 'label': y, 'video_id': video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True) print res_df return res_df",
"as pd from matplotlib import pyplot as plt from sklearn.metrics import accuracy_score from",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"use? if clf: smv_proba = clf.predict_proba(X_test) predictions = (smv_proba[:, 1] >= svm_cutoff) #",
") print df xlabels = map(int, df.columns[2:]) for _, row in df.iterrows(): x",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"pooling on a dataset's JITL input file and produce a smaller one :param",
":return: \"\"\" # if not isinstance(mp_span_secs, list): # mp_span_secs = [mp_span_secs] # if",
"inputs = inputs.sort_values(by=['frameid']) last_sent_imageid = None min_frm = inputs['frameid'].min() max_frm = inputs['frameid'].max() for",
"max_frame = df['frameid'].max() print(\"Max frame ID: {}\".format(max_frame)) X_jit = X[:0] # cumulative, used",
"(C) 2018-2019 Carnegie Mellon University # # Licensed under the Apache License, Version",
"print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy,",
"{} images in total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda x:",
"augment_pos_X = positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit, augment_pos_X, axis=0) y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0)",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"= set(df['video_id']) fig, ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1))",
"y_jit.shape[0], 'jitl_prediction': pred_jit, 'label': y, 'video_id': video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True) print res_df return",
"inputs in gridxy_grp: inputs = inputs.sort_values(by=['frameid']) last_sent_imageid = None min_frm = inputs['frameid'].min() max_frm",
"for svm_cut in svm_cutoff: print(\"-\" * 50) print(\"Emulating video '{}' w/ DNN cutoff",
"from sklearn.svm import SVC from sklearn.utils import resample from jitl_data import _split_imageid, _get_videoid",
"video_ids = set(df['video_id']) fig, ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0,",
"np.count_nonzero(sent_mask) > 0 \\ and np.count_nonzero(y_jit == 0) >= activate_threshold \\ and (augment_positive",
"dataset's JITL input file and produce a smaller one :param dataset: :param base_dir:",
"last_sent_imageid = imageid count += 1 print(\"Sample {}/{} frames from video {}\".format(count, video_rows.shape[0],",
"required by applicable law or agreed to in writing, software # distributed under",
"np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5): samples = resample(self.features, n_samples=n, replace=False) return samples def eval_jit_svm_on_dataset(jit_data_file,",
"* x for x in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn cutoff list: {}\".format(dnn_cutoff_list))",
"by dnn positive if len(dnn_fire_index) == 0: print(\"DNN fires nothing. Stop\") return None",
"# mp_span_secs = [mp_span_secs] # if not isinstance(mp_stride_secs, list): # mp_stride_secs = [mp_stride_secs]",
"# accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--') if savefig: plt.savefig(savefig) plt.show() if",
"applicable law or agreed to in writing, software # distributed under the License",
"(dnn_proba[:, 1] >= dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0] # filter df by dnn positive",
"the SVM, # otherwise passthrough; training set is ever expanding; svm_cutoff=0.3): if not",
"pool_images['imageid'].iloc[max_ind] if imageid != last_sent_imageid: # print(\"sampled image: {}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True)",
"') df = df.append(df1, ignore_index=True) print df # df = df[df['delta_t'] < 90]",
"from jitl_data import _split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run max",
"dnn_proba.shape[1] == 2, dnn_proba.shape dnn_fire = (dnn_proba[:, 1] >= dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0]",
"y, 'video_id': video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True) print res_df return res_df def plot_frame_accuracy(input_file, savefig=None):",
"print(\"Max pooling between frame {} and {}\".format(pool_start_frm, pool_start_frm + span_frms)) pool_images = inputs[(inputs['frameid']",
"# # Copyright (C) 2018-2019 Carnegie Mellon University # # Licensed under the",
"video_id_grp: print(\"Found {} frames for video {}\".format(video_rows.shape[0], video_id)) count = 0 gridxy_grp =",
"y.shape == pred_jit.shape, \"y: {}, pred_jit: {}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy",
"2018-2019 Carnegie Mellon University # # Licensed under the Apache License, Version 2.0",
"sklearn.svm import SVC from sklearn.utils import resample from jitl_data import _split_imageid, _get_videoid def",
"or agreed to in writing, software # distributed under the License is distributed",
"print x, y plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0, max(xlabels), 0, 1.0]) # plt.show() if",
"# if not isinstance(mp_stride_secs, list): # mp_stride_secs = [mp_stride_secs] df = pd.read_pickle(jit_data_file) print(\"Found",
"df[df['video_id'] == vid] # accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--') if savefig:",
"= np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5): samples = resample(self.features, n_samples=n, replace=False) return samples def",
"if not isinstance(svm_cutoff, list): svm_cutoff = [svm_cutoff] if dnn_threshold_input_file is not None: print(\"Warning:",
"training set pred_jit = np.append(pred_jit, predictions, axis=0) sent_mask = (predictions == 1) X_jit",
"svm_cutoff=0.3): if not isinstance(svm_cutoff, list): svm_cutoff = [svm_cutoff] if dnn_threshold_input_file is not None:",
"DNN cutoff {}, SVM cutoff {}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\" * 50) rv =",
"# now, shall we (re-)train a new SVM? print(\"JIT training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit)))",
"dataset: :param base_dir: :param jit_data_file: :param mp_span_secs: :param mp_stride_secs: :return: \"\"\" # if",
"{} to {}\".format(t, t + delta_t)) df_test = df[(df['frameid'] >= t * 30)",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit, 'label':",
"= np.array(df['feature'].tolist()) y = np.array(df['label'].tolist()) imageids = df['imageid'].tolist() max_frame = df['frameid'].max() print(\"Max frame",
"axis=0) assert X_jit.shape[1] == 1024 # print(\"Found {} frames in window. Sent {}.\".format(y_test.shape[0],",
"video_rows.shape[0], video_id)) downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After max pooling, we have {} images\".format(downsample_df.shape[0])) print(\"Sample",
"print(\"Warning: Dnn_threshold_input_file is specified! Ignoring dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file)",
"verbose=0) clf.fit(X_jit_train, y_jit_train) else: print(\"NOT retraining. Nothing new or not enough positives.\") pass",
"= downsample_df.sort_values(by=['imageid']) print(\"After max pooling, we have {} images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\") print",
"sep=r'\\s+' ) print df xlabels = map(int, df.columns[2:]) for _, row in df.iterrows():",
"np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics",
"== pred_jit.shape, \"y: {}, pred_jit: {}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy =",
"for t in range(0, int(1 + (max_frame / 30)), delta_t): # extract data",
"for path in paths: print(\"Parsing {}\".format(path)) df1 = pd.read_csv(path, sep=' ') df =",
"dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, # train every 10s activate_threshold=5, # min number of examples",
"predictions = (smv_proba[:, 1] >= svm_cutoff) # predictions = clf.predict(X_test) else: # pass-through",
"_split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs * 30) stride_frms = int(mp_stride_secs * 30) print(\"Max pooling",
"X_jit = X[:0] # cumulative, used to train JIT SVM y_jit = y[:0]",
"df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos = set(df['videoid'].tolist()) result_df = pd.DataFrame() for video_id",
"= pd.read_csv( input_file, sep=r'\\s+' ) print df xlabels = map(int, df.columns[2:]) for _,",
"str(X_test.shape) # Do we have an SVM to use? if clf: smv_proba =",
"# verbose=True), # param_grid=tuned_params, # n_jobs=4, # refit=True) clf = SVC(random_state=42, kernel='linear', class_weight='balanced',",
"steal these positives:\") # print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5): samples =",
"df.iloc[:5] df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5]",
"ever expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff, list): svm_cutoff = [svm_cutoff] if dnn_threshold_input_file is",
"print(\"DNN fires {} frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist()) y = np.array(df['label'].tolist())",
"df = df.sort_values(by=['frameid']) # print(\"Will steal these positives:\") # print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist())",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"last_sent_imageid: # print(\"sampled image: {}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid = imageid count",
"video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df = result_df.append(rv, ignore_index=True) print result_df if output_file:",
"ax1.twinx() ax2.set_ylabel(\"# frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid in video_ids: df_video =",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"nothing. Stop\") return None print(\"DNN fires {} frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index] X =",
"Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now, shall we (re-)train a new SVM? print(\"JIT training",
"np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y, pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t': delta_t, 'imageids':",
"path in paths: print(\"Parsing {}\".format(path)) df1 = pd.read_csv(path, sep=' ') df = df.append(df1,",
"a smaller one :param dataset: :param base_dir: :param jit_data_file: :param mp_span_secs: :param mp_stride_secs:",
"print(\"After max pooling, we have {} images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\") print downsample_df.iloc[::downsample_df.shape[0] /",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"# tuned_params = { # 'C': [1], # 'kernel': ['linear'], # } #",
"print res_df return res_df def plot_frame_accuracy(input_file, savefig=None): df = pd.read_csv( input_file, sep=r'\\s+' )",
"video_id] # print df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] == 2, dnn_proba.shape dnn_fire",
"License. # You may obtain a copy of the License at # #",
"result_df = pd.DataFrame() for video_id in unique_videos: for dnn_cutoff in dnn_cutoff_list: for svm_cut",
"use grid search to improve SVM accuracy # tuned_params = { # 'C':",
"permissions and # limitations under the License. import glob import fire import matplotlib",
"'svm_cutoff': svm_cutoff}, ignore_index=True) print res_df return res_df def plot_frame_accuracy(input_file, savefig=None): df = pd.read_csv(",
"df.iterrows(): x = xlabels y = np.array(row[2:]) print x, y plt.plot(xlabels, np.array(row[2:]), '-o')",
"probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train) else: print(\"NOT retraining. Nothing new or not enough positives.\")",
"= df[(df['frameid'] >= t * 30) & (df['frameid'] < (t + delta_t) *",
"self).__init__() df = df[(df['videoid'] == video_id) & (df['label'].astype(bool))] df = df.sort_values(by=['frameid']) # print(\"Will",
"def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run max pooling on a dataset's JITL",
"& (df['frameid'] < (t + delta_t) * 30)] # print df_test.iloc[:5] if df_test.empty:",
"= y[:0] # store SVM's prediction on DNN's positive frames clf = None",
"compliance with the License. # You may obtain a copy of the License",
"vid] # accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--') if savefig: plt.savefig(savefig) plt.show()",
"__init__(self, df, video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__() df = df[(df['videoid'] == video_id) & (df['label'].astype(bool))]",
"sep=' ') df = df.append(df1, ignore_index=True) print df # df = df[df['delta_t'] <",
"= accuracy_score(y, pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids, 'dnn_cutoff':",
"ignore_index=True) last_sent_imageid = imageid count += 1 print(\"Sample {}/{} frames from video {}\".format(count,",
"= clf.predict(X_test) else: # pass-through DNN's prediction (DNN says all are positive) predictions",
"0 \\ and np.count_nonzero(y_jit == 0) >= activate_threshold \\ and (augment_positive or np.count_nonzero(y_jit",
"and (augment_positive or np.count_nonzero(y_jit == 1) >= activate_threshold): print(\"retraining\") if not np.count_nonzero(y_jit ==",
"have an SVM to use? if clf: smv_proba = clf.predict_proba(X_test) predictions = (smv_proba[:,",
"ax2.set_ylabel(\"# frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid in video_ids: df_video = df[df['video_id']",
"print(\"retraining\") if not np.count_nonzero(y_jit == 1) >= activate_threshold and augment_positive: print(\"Houston, we don't",
"+ delta_t) * 30)] # print df_test.iloc[:5] if df_test.empty: continue X_test = np.array(df_test['feature'].tolist())",
"axis=0) y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now you have",
"30) & (df['frameid'] < (t + delta_t) * 30)] # print df_test.iloc[:5] if",
"have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train = X_jit y_jit_train = y_jit # use grid",
"+ 1, stride_frms): # print(\"Max pooling between frame {} and {}\".format(pool_start_frm, pool_start_frm +",
"np.count_nonzero(sent_mask))) # now, shall we (re-)train a new SVM? print(\"JIT training set {}/{}\".format(y_jit.shape[0],",
"for the specific language governing permissions and # limitations under the License. import",
"these positives:\") # print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5): samples = resample(self.features,",
"pred_jit.shape) assert y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y, pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df",
"frames in window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now, shall we (re-)train a new",
"dnn_scores.ndim == 1 max_ind = np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind] if imageid != last_sent_imageid:",
"= SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train) else: print(\"NOT retraining. Nothing new",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"# plt.show() if savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None): paths = glob.glob(file_glob) df =",
"x: _split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs * 30) stride_frms",
"pd.read_pickle(jit_data_file) print(\"Found {} images in total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] =",
"accuracy_score from sklearn.svm import SVC from sklearn.utils import resample from jitl_data import _split_imageid,",
"print(\"Sample 10 rows.\") print downsample_df.iloc[::downsample_df.shape[0] / 10] if output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def",
"print(\"-\" * 50) print(\"Emulating video '{}' w/ DNN cutoff {}, SVM cutoff {}\".format(video_id,",
"matplotlib import numpy as np import pandas as pd from matplotlib import pyplot",
"feeds leveraging edge servers. # # Copyright (C) 2018-2019 Carnegie Mellon University #",
"to {}\".format(t, t + delta_t)) df_test = df[(df['frameid'] >= t * 30) &",
"\"y: {}, pred_jit: {}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y, pred_jit)",
"svm_cut in svm_cutoff: print(\"-\" * 50) print(\"Emulating video '{}' w/ DNN cutoff {},",
"max_iter=100, # class_weight='balanced', # probability=True, # verbose=True), # param_grid=tuned_params, # n_jobs=4, # refit=True)",
"list): # mp_stride_secs = [mp_stride_secs] df = pd.read_pickle(jit_data_file) print(\"Found {} images in total.\".format(df.shape[0]))",
"int(mp_span_secs * 30) stride_frms = int(mp_stride_secs * 30) print(\"Max pooling span frames={}, stride",
"= set(df['videoid'].tolist()) result_df = pd.DataFrame() for video_id in unique_videos: for dnn_cutoff in dnn_cutoff_list:",
"# class_weight='balanced', # probability=True, # verbose=True), # param_grid=tuned_params, # n_jobs=4, # refit=True) clf",
"df_test = df[(df['frameid'] >= t * 30) & (df['frameid'] < (t + delta_t)",
"passing early discard filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, # train every 10s activate_threshold=5, #",
"frame ID: {}\".format(max_frame)) X_jit = X[:0] # cumulative, used to train JIT SVM",
"# Drone Search # # A computer vision pipeline for live video search",
"drone video # feeds leveraging edge servers. # # Copyright (C) 2018-2019 Carnegie",
"= (predictions == 1) X_jit = np.append(X_jit, X_test[sent_mask], axis=0) y_jit = np.append(y_jit, y_test[sent_mask],",
"window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now, shall we (re-)train a new SVM? print(\"JIT",
"{}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y, pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy))",
"10 rows.\") print downsample_df.iloc[::downsample_df.shape[0] / 10] if output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def __init__(self,",
"dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn cutoff list: {}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid']",
"ignore_index=True) print result_df if output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3,",
"print(\"Max frame ID: {}\".format(max_frame)) X_jit = X[:0] # cumulative, used to train JIT",
"min number of examples per class needed to train the SVM, # otherwise",
"for gridxy, inputs in gridxy_grp: inputs = inputs.sort_values(by=['frameid']) last_sent_imageid = None min_frm =",
"per class needed to train the SVM, # otherwise passthrough; training set is",
"1024 # print(\"Found {} frames in window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now, shall",
"downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid = imageid count += 1 print(\"Sample {}/{} frames",
"not use this file except in compliance with the License. # You may",
"(df['label'].astype(bool))] df = df.sort_values(by=['frameid']) # print(\"Will steal these positives:\") # print(df.iloc[-tail:]) self.features =",
"out to global prediction and cumulative JIT training set pred_jit = np.append(pred_jit, predictions,",
"= df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs * 30) stride_frms = int(mp_stride_secs *",
"n=5): samples = resample(self.features, n_samples=n, replace=False) return samples def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80,",
"new SVM? print(\"JIT training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) > 0 \\ and",
"\"dnn_cutoff_step variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn cutoff threshold is: {}\".format(dnn_cutoff_list)) else:",
"< pool_start_frm + span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim == 1 max_ind",
"cutoff {}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\" * 50) rv = run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t,",
"= np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind] if imageid != last_sent_imageid: # print(\"sampled image: {}\".format(imageid))",
"assert X_test.shape[1] == 1024, str(X_test.shape) # Do we have an SVM to use?",
"{}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid = imageid count += 1 print(\"Sample {}/{}",
"1) X_jit = np.append(X_jit, X_test[sent_mask], axis=0) y_jit = np.append(y_jit, y_test[sent_mask], axis=0) assert X_jit.shape[1]",
"x for x in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn cutoff list: {}\".format(dnn_cutoff_list)) df",
"limitations under the License. import glob import fire import matplotlib import numpy as",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"svm_cutoff = [svm_cutoff] if dnn_threshold_input_file is not None: print(\"Warning: Dnn_threshold_input_file is specified! Ignoring",
"[0.01 * x for x in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn cutoff list:",
"dnn cutoff list: {}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid'] = df['imageid'].map(lambda x:",
"_get_videoid(x)) df['frameid'] = df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos = set(df['videoid'].tolist()) result_df =",
"positive if len(dnn_fire_index) == 0: print(\"DNN fires nothing. Stop\") return None print(\"DNN fires",
"pooling span frames={}, stride frame={}\".format(span_frms, stride_frms)) downsample_df = pd.DataFrame() video_id_grp = df.groupby(['videoid']) for",
"have enough TPs.\") augment_pos_X = positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit, augment_pos_X, axis=0) y_jit_train =",
"data within this window (from t to t+delta_t) # print(\"time window {} to",
"video {}\".format(video_rows.shape[0], video_id)) count = 0 gridxy_grp = video_rows.groupby(['grid_x', 'grid_y']) for gridxy, inputs",
"if clf: smv_proba = clf.predict_proba(X_test) predictions = (smv_proba[:, 1] >= svm_cutoff) # predictions",
"= inputs.sort_values(by=['frameid']) last_sent_imageid = None min_frm = inputs['frameid'].min() max_frm = inputs['frameid'].max() for pool_start_frm",
"says all are positive) predictions = np.ones_like(y_test) # write out to global prediction",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"= X[:0] # cumulative, used to train JIT SVM y_jit = y[:0] #",
">= t * 30) & (df['frameid'] < (t + delta_t) * 30)] #",
"mp_stride_secs = [mp_stride_secs] df = pd.read_pickle(jit_data_file) print(\"Found {} images in total.\".format(df.shape[0])) df['videoid'] =",
"x: _split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms",
"filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, # train every 10s activate_threshold=5, # min number of",
"dnn cutoff threshold is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list = [0.01 * x for x",
"result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False): # filter df by",
"np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) > 0 \\ and np.count_nonzero(y_jit == 0) >= activate_threshold \\",
"\\ and (augment_positive or np.count_nonzero(y_jit == 1) >= activate_threshold): print(\"retraining\") if not np.count_nonzero(y_jit",
"= df[df['delta_t'] < 90] video_ids = set(df['video_id']) fig, ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta t$",
"in video_ids: df_video = df[df['video_id'] == vid] # accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'],",
"enough TPs.\") augment_pos_X = positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit, augment_pos_X, axis=0) y_jit_train = np.append(y_jit,",
"= pd.DataFrame() for path in paths: print(\"Parsing {}\".format(path)) df1 = pd.read_csv(path, sep=' ')",
"X_jit_train = X_jit y_jit_train = y_jit # use grid search to improve SVM",
"'video_id': video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True) print res_df return res_df def plot_frame_accuracy(input_file, savefig=None): df",
"# you may not use this file except in compliance with the License.",
"now, shall we (re-)train a new SVM? print(\"JIT training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if",
"imageids = df['imageid'].tolist() max_frame = df['frameid'].max() print(\"Max frame ID: {}\".format(max_frame)) X_jit = X[:0]",
"agreed to in writing, software # distributed under the License is distributed on",
"'-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--') if savefig: plt.savefig(savefig) plt.show() if __name__ == '__main__': fire.Fire()",
"pyplot as plt from sklearn.metrics import accuracy_score from sklearn.svm import SVC from sklearn.utils",
"positive frames clf = None positive_supply = StealPositiveFromVideoEnd(df_in, video_id) for t in range(0,",
"video search on drone video # feeds leveraging edge servers. # # Copyright",
"X_test[sent_mask], axis=0) y_jit = np.append(y_jit, y_test[sent_mask], axis=0) assert X_jit.shape[1] == 1024 # print(\"Found",
"[mp_stride_secs] df = pd.read_pickle(jit_data_file) print(\"Found {} images in total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda x:",
"= [mp_stride_secs] df = pd.read_pickle(jit_data_file) print(\"Found {} images in total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda",
"y_jit_train.shape[0] print(\"Now you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train = X_jit y_jit_train = y_jit",
"imageid count += 1 print(\"Sample {}/{} frames from video {}\".format(count, video_rows.shape[0], video_id)) downsample_df",
"video_rows.groupby(['grid_x', 'grid_y']) for gridxy, inputs in gridxy_grp: inputs = inputs.sort_values(by=['frameid']) last_sent_imageid = None",
"SVM cutoff {}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\" * 50) rv = run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff,",
"# probability=True, # verbose=True), # param_grid=tuned_params, # n_jobs=4, # refit=True) clf = SVC(random_state=42,",
"Nothing new or not enough positives.\") pass assert y.shape == pred_jit.shape, \"y: {},",
"base_dir: :param jit_data_file: :param mp_span_secs: :param mp_stride_secs: :return: \"\"\" # if not isinstance(mp_span_secs,",
"(the \"License\"); # you may not use this file except in compliance with",
":param dataset: :param base_dir: :param jit_data_file: :param mp_span_secs: :param mp_stride_secs: :return: \"\"\" #",
"early discard filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, # train every 10s activate_threshold=5, # min",
"video_id)) count = 0 gridxy_grp = video_rows.groupby(['grid_x', 'grid_y']) for gridxy, inputs in gridxy_grp:",
"= df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos = set(df['videoid'].tolist()) result_df = pd.DataFrame() for",
"if not np.count_nonzero(y_jit == 1) >= activate_threshold and augment_positive: print(\"Houston, we don't have",
"assert dnn_proba.shape[1] == 2, dnn_proba.shape dnn_fire = (dnn_proba[:, 1] >= dnn_cutoff) dnn_fire_index =",
"[mp_span_secs] # if not isinstance(mp_stride_secs, list): # mp_stride_secs = [mp_stride_secs] df = pd.read_pickle(jit_data_file)",
"retraining. Nothing new or not enough positives.\") pass assert y.shape == pred_jit.shape, \"y:",
"predictions = np.ones_like(y_test) # write out to global prediction and cumulative JIT training",
"1] assert dnn_scores.ndim == 1 max_ind = np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind] if imageid",
"class_weight='balanced', # probability=True, # verbose=True), # param_grid=tuned_params, # n_jobs=4, # refit=True) clf =",
"# Unless required by applicable law or agreed to in writing, software #",
"= [0.01 * x for x in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn cutoff",
"fires nothing. Stop\") return None print(\"DNN fires {} frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index] X",
"by applicable law or agreed to in writing, software # distributed under the",
"filter df by video id df = df_in[df_in['videoid'] == video_id] # print df.iloc[0]",
"{} images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\") print downsample_df.iloc[::downsample_df.shape[0] / 10] if output_file: downsample_df.to_pickle(output_file) class",
"of examples per class needed to train the SVM, # otherwise passthrough; training",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now you have {}/{}\".format(y_jit_train.shape[0],",
"print(\"Found {} frames for video {}\".format(video_rows.shape[0], video_id)) count = 0 gridxy_grp = video_rows.groupby(['grid_x',",
"2, dnn_proba.shape dnn_fire = (dnn_proba[:, 1] >= dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0] # filter",
"train every 10s activate_threshold=5, # min number of examples per class needed to",
"sklearn.utils import resample from jitl_data import _split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5):",
"svm_cutoff) # predictions = clf.predict(X_test) else: # pass-through DNN's prediction (DNN says all",
"University # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"stride_frms): # print(\"Max pooling between frame {} and {}\".format(pool_start_frm, pool_start_frm + span_frms)) pool_images",
"df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos",
"if output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False): # filter",
"in svm_cutoff: print(\"-\" * 50) print(\"Emulating video '{}' w/ DNN cutoff {}, SVM",
"df[df['delta_t'] < 90] video_ids = set(df['video_id']) fig, ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\")",
"print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5): samples = resample(self.features, n_samples=n, replace=False) return",
"X = np.array(df['feature'].tolist()) y = np.array(df['label'].tolist()) imageids = df['imageid'].tolist() max_frame = df['frameid'].max() print(\"Max",
"augment_positive: print(\"Houston, we don't have enough TPs.\") augment_pos_X = positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit,",
"video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__() df = df[(df['videoid'] == video_id) & (df['label'].astype(bool))] df =",
"# Copyright (C) 2018-2019 Carnegie Mellon University # # Licensed under the Apache",
"import SVC from sklearn.utils import resample from jitl_data import _split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file,",
"samples = resample(self.features, n_samples=n, replace=False) return samples def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, #",
"file except in compliance with the License. # You may obtain a copy",
"df = pd.read_csv( input_file, sep=r'\\s+' ) print df xlabels = map(int, df.columns[2:]) for",
"= np.nonzero(dnn_fire)[0] # filter df by dnn positive if len(dnn_fire_index) == 0: print(\"DNN",
"import accuracy_score from sklearn.svm import SVC from sklearn.utils import resample from jitl_data import",
"['linear'], # } # clf = GridSearchCV(SVC(random_state=43, # max_iter=100, # class_weight='balanced', # probability=True,",
"= plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1)) ax2 = ax1.twinx() ax2.set_ylabel(\"#",
"frame={}\".format(span_frms, stride_frms)) downsample_df = pd.DataFrame() video_id_grp = df.groupby(['videoid']) for video_id, video_rows in video_id_grp:",
"30) stride_frms = int(mp_stride_secs * 30) print(\"Max pooling span frames={}, stride frame={}\".format(span_frms, stride_frms))",
"Mellon University # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"= np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train)))",
"clf.predict_proba(X_test) predictions = (smv_proba[:, 1] >= svm_cutoff) # predictions = clf.predict(X_test) else: #",
"as plt from sklearn.metrics import accuracy_score from sklearn.svm import SVC from sklearn.utils import",
"0 gridxy_grp = video_rows.groupby(['grid_x', 'grid_y']) for gridxy, inputs in gridxy_grp: inputs = inputs.sort_values(by=['frameid'])",
"else: print(\"NOT retraining. Nothing new or not enough positives.\") pass assert y.shape ==",
"# same pred_jit = y[:0] # store SVM's prediction on DNN's positive frames",
"License for the specific language governing permissions and # limitations under the License.",
"mp_span_secs = [mp_span_secs] # if not isinstance(mp_stride_secs, list): # mp_stride_secs = [mp_stride_secs] df",
"= np.append(y_jit, y_test[sent_mask], axis=0) assert X_jit.shape[1] == 1024 # print(\"Found {} frames in",
"# print(\"sampled image: {}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid = imageid count +=",
"on DNN's positive frames clf = None positive_supply = StealPositiveFromVideoEnd(df_in, video_id) for t",
"accuracy # tuned_params = { # 'C': [1], # 'kernel': ['linear'], # }",
"df_test.iloc[:5] if df_test.empty: continue X_test = np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label']) assert X_test.shape[1] ==",
"activate_threshold): print(\"retraining\") if not np.count_nonzero(y_jit == 1) >= activate_threshold and augment_positive: print(\"Houston, we",
"plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1)) ax2 = ax1.twinx() ax2.set_ylabel(\"# frames",
"to in writing, software # distributed under the License is distributed on an",
"isinstance(mp_span_secs, list): # mp_span_secs = [mp_span_secs] # if not isinstance(mp_stride_secs, list): # mp_stride_secs",
"print df.iloc[:5] df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print",
"cumulative, used to train JIT SVM y_jit = y[:0] # same pred_jit =",
"dnn_cutoff_end, \" \"dnn_cutoff_step variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn cutoff threshold is:",
"implied. # See the License for the specific language governing permissions and #",
"positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit, augment_pos_X, axis=0) y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0]",
"total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x'] =",
"\"License\"); # you may not use this file except in compliance with the",
"df.sort_values(by=['frameid']) # print(\"Will steal these positives:\") # print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self,",
"X_jit y_jit_train = y_jit # use grid search to improve SVM accuracy #",
"y_jit_train = y_jit # use grid search to improve SVM accuracy # tuned_params",
"{}\".format(count, video_rows.shape[0], video_id)) downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After max pooling, we have {} images\".format(downsample_df.shape[0]))",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"glob.glob(file_glob) df = pd.DataFrame() for path in paths: print(\"Parsing {}\".format(path)) df1 = pd.read_csv(path,",
"threshold is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list = [0.01 * x for x in range(dnn_cutoff_start,",
"== 2, dnn_proba.shape dnn_fire = (dnn_proba[:, 1] >= dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0] #",
"# filter df by dnn positive if len(dnn_fire_index) == 0: print(\"DNN fires nothing.",
"{}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) > 0 \\ and np.count_nonzero(y_jit == 0) >= activate_threshold",
"span frames={}, stride frame={}\".format(span_frms, stride_frms)) downsample_df = pd.DataFrame() video_id_grp = df.groupby(['videoid']) for video_id,",
"ignore_index=True) print df # df = df[df['delta_t'] < 90] video_ids = set(df['video_id']) fig,",
"df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int)",
"df, video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__() df = df[(df['videoid'] == video_id) & (df['label'].astype(bool))] df",
"n_jobs=4, # refit=True) clf = SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train) else:",
"np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind] if imageid != last_sent_imageid: # print(\"sampled image: {}\".format(imageid)) downsample_df",
"= clf.predict_proba(X_test) predictions = (smv_proba[:, 1] >= svm_cutoff) # predictions = clf.predict(X_test) else:",
"ID: {}\".format(max_frame)) X_jit = X[:0] # cumulative, used to train JIT SVM y_jit",
"df = df[df['delta_t'] < 90] video_ids = set(df['video_id']) fig, ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta",
"replace=False) return samples def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn threshold for passing",
"dnn_cutoff_step=2, delta_t=10, # train every 10s activate_threshold=5, # min number of examples per",
"= y[:0] # same pred_jit = y[:0] # store SVM's prediction on DNN's",
"clf = None positive_supply = StealPositiveFromVideoEnd(df_in, video_id) for t in range(0, int(1 +",
"to global prediction and cumulative JIT training set pred_jit = np.append(pred_jit, predictions, axis=0)",
"Run max pooling on a dataset's JITL input file and produce a smaller",
"or implied. # See the License for the specific language governing permissions and",
"np.array(row[2:]), '-o') plt.axis([0, max(xlabels), 0, 1.0]) # plt.show() if savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob,",
"pass-through DNN's prediction (DNN says all are positive) predictions = np.ones_like(y_test) # write",
"df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos = set(df['videoid'].tolist())",
"= result_df.append(rv, ignore_index=True) print result_df if output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10,",
"= (smv_proba[:, 1] >= svm_cutoff) # predictions = clf.predict(X_test) else: # pass-through DNN's",
"= inputs['frameid'].max() for pool_start_frm in range(min_frm, max_frm + 1, stride_frms): # print(\"Max pooling",
"for vid in video_ids: df_video = df[df['video_id'] == vid] # accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'],",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"print(\"DNN fires nothing. Stop\") return None print(\"DNN fires {} frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index]",
"numpy as np import pandas as pd from matplotlib import pyplot as plt",
"smaller one :param dataset: :param base_dir: :param jit_data_file: :param mp_span_secs: :param mp_stride_secs: :return:",
"output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn threshold for passing early discard filter dnn_cutoff_end=100, dnn_cutoff_step=2,",
"sorted(set(df['delta_t']))) for vid in video_ids: df_video = df[df['video_id'] == vid] # accuracy ax1.plot(df_video['delta_t'],",
"A computer vision pipeline for live video search on drone video # feeds",
"== 1 max_ind = np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind] if imageid != last_sent_imageid: #",
"x: _split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs * 30) stride_frms = int(mp_stride_secs * 30) print(\"Max",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"delta_t) * 30)] # print df_test.iloc[:5] if df_test.empty: continue X_test = np.array(df_test['feature'].tolist()) y_test",
"{}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0],",
"in writing, software # distributed under the License is distributed on an \"AS",
"= inputs['frameid'].min() max_frm = inputs['frameid'].max() for pool_start_frm in range(min_frm, max_frm + 1, stride_frms):",
"isinstance(svm_cutoff, list): svm_cutoff = [svm_cutoff] if dnn_threshold_input_file is not None: print(\"Warning: Dnn_threshold_input_file is",
"df = pd.read_pickle(jit_data_file) print(\"Found {} images in total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x))",
"variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn cutoff threshold is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list",
"for video_id in unique_videos: for dnn_cutoff in dnn_cutoff_list: for svm_cut in svm_cutoff: print(\"-\"",
"= df['frameid'].max() print(\"Max frame ID: {}\".format(max_frame)) X_jit = X[:0] # cumulative, used to",
"list): svm_cutoff = [svm_cutoff] if dnn_threshold_input_file is not None: print(\"Warning: Dnn_threshold_input_file is specified!",
"30)), delta_t): # extract data within this window (from t to t+delta_t) #",
"this window (from t to t+delta_t) # print(\"time window {} to {}\".format(t, t",
"= inputs[(inputs['frameid'] >= pool_start_frm) & (inputs['frameid'] < pool_start_frm + span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:,",
"# use grid search to improve SVM accuracy # tuned_params = { #",
"in range(min_frm, max_frm + 1, stride_frms): # print(\"Max pooling between frame {} and",
"# } # clf = GridSearchCV(SVC(random_state=43, # max_iter=100, # class_weight='balanced', # probability=True, #",
"df = df.append(df1, ignore_index=True) print df # df = df[df['delta_t'] < 90] video_ids",
"else: X_jit_train = X_jit y_jit_train = y_jit # use grid search to improve",
"Copyright (C) 2018-2019 Carnegie Mellon University # # Licensed under the Apache License,",
"gridxy_grp = video_rows.groupby(['grid_x', 'grid_y']) for gridxy, inputs in gridxy_grp: inputs = inputs.sort_values(by=['frameid']) last_sent_imageid",
"__call__(self, n=5): samples = resample(self.features, n_samples=n, replace=False) return samples def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None,",
"return None print(\"DNN fires {} frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist()) y",
"90] video_ids = set(df['video_id']) fig, ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\")",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"to t+delta_t) # print(\"time window {} to {}\".format(t, t + delta_t)) df_test =",
"cutoff threshold is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list = [0.01 * x for x in",
"video_id in unique_videos: for dnn_cutoff in dnn_cutoff_list: for svm_cut in svm_cutoff: print(\"-\" *",
"not isinstance(mp_stride_secs, list): # mp_stride_secs = [mp_stride_secs] df = pd.read_pickle(jit_data_file) print(\"Found {} images",
"{}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] =",
"activate_threshold and augment_positive: print(\"Houston, we don't have enough TPs.\") augment_pos_X = positive_supply(n=activate_threshold) X_jit_train",
"print(\"Parsing {}\".format(path)) df1 = pd.read_csv(path, sep=' ') df = df.append(df1, ignore_index=True) print df",
"30) print(\"Max pooling span frames={}, stride frame={}\".format(span_frms, stride_frms)) downsample_df = pd.DataFrame() video_id_grp =",
"svm_cutoff}, ignore_index=True) print res_df return res_df def plot_frame_accuracy(input_file, savefig=None): df = pd.read_csv( input_file,",
"max_ind = np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind] if imageid != last_sent_imageid: # print(\"sampled image:",
"we have {} images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\") print downsample_df.iloc[::downsample_df.shape[0] / 10] if output_file:",
"rows.\") print downsample_df.iloc[::downsample_df.shape[0] / 10] if output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def __init__(self, df,",
"{}, pred_jit: {}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0] == np.count_nonzero(pred_jit) jit_accuracy = accuracy_score(y, pred_jit) print(\"JIT",
"computer vision pipeline for live video search on drone video # feeds leveraging",
"= np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim == 1 max_ind = np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind]",
"matplotlib import pyplot as plt from sklearn.metrics import accuracy_score from sklearn.svm import SVC",
"to use? if clf: smv_proba = clf.predict_proba(X_test) predictions = (smv_proba[:, 1] >= svm_cutoff)",
"1.0]) # plt.show() if savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None): paths = glob.glob(file_glob) df",
"in gridxy_grp: inputs = inputs.sort_values(by=['frameid']) last_sent_imageid = None min_frm = inputs['frameid'].min() max_frm =",
"Stop\") return None print(\"DNN fires {} frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist())",
"tuned_params = { # 'C': [1], # 'kernel': ['linear'], # } # clf",
"dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn cutoff threshold",
"Ignoring dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn cutoff",
"\" \"dnn_cutoff_step variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn cutoff threshold is: {}\".format(dnn_cutoff_list))",
"= (dnn_proba[:, 1] >= dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0] # filter df by dnn",
"paths = glob.glob(file_glob) df = pd.DataFrame() for path in paths: print(\"Parsing {}\".format(path)) df1",
"axis=0) assert X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train =",
"else: # pass-through DNN's prediction (DNN says all are positive) predictions = np.ones_like(y_test)",
"X_jit = np.append(X_jit, X_test[sent_mask], axis=0) y_jit = np.append(y_jit, y_test[sent_mask], axis=0) assert X_jit.shape[1] ==",
"search on drone video # feeds leveraging edge servers. # # Copyright (C)",
"np.append(y_jit, y_test[sent_mask], axis=0) assert X_jit.shape[1] == 1024 # print(\"Found {} frames in window.",
"* 50) print(\"Emulating video '{}' w/ DNN cutoff {}, SVM cutoff {}\".format(video_id, dnn_cutoff,",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"if imageid != last_sent_imageid: # print(\"sampled image: {}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid",
"print(\"time window {} to {}\".format(t, t + delta_t)) df_test = df[(df['frameid'] >= t",
"delta_t)) df_test = df[(df['frameid'] >= t * 30) & (df['frameid'] < (t +",
"np.count_nonzero(y_jit == 1) >= activate_threshold and augment_positive: print(\"Houston, we don't have enough TPs.\")",
"you may not use this file except in compliance with the License. #",
"_get_videoid(x)) df['frameid'] = df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y'] =",
"== 0: print(\"DNN fires nothing. Stop\") return None print(\"DNN fires {} frames\".format(len(dnn_fire_index))) df",
"filter df by dnn positive if len(dnn_fire_index) == 0: print(\"DNN fires nothing. Stop\")",
"int(mp_stride_secs * 30) print(\"Max pooling span frames={}, stride frame={}\".format(span_frms, stride_frms)) downsample_df = pd.DataFrame()",
"{}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train = X_jit y_jit_train = y_jit # use grid search",
"import matplotlib import numpy as np import pandas as pd from matplotlib import",
"in unique_videos: for dnn_cutoff in dnn_cutoff_list: for svm_cut in svm_cutoff: print(\"-\" * 50)",
"unique_videos = set(df['videoid'].tolist()) result_df = pd.DataFrame() for video_id in unique_videos: for dnn_cutoff in",
"video_id) & (df['label'].astype(bool))] df = df.sort_values(by=['frameid']) # print(\"Will steal these positives:\") # print(df.iloc[-tail:])",
"return samples def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn threshold for passing early",
"print df.iloc[:5] unique_videos = set(df['videoid'].tolist()) result_df = pd.DataFrame() for video_id in unique_videos: for",
"= pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda imgid:",
"print(\"Found {} images in total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda",
"max_frm = inputs['frameid'].max() for pool_start_frm in range(min_frm, max_frm + 1, stride_frms): # print(\"Max",
"to train the SVM, # otherwise passthrough; training set is ever expanding; svm_cutoff=0.3):",
"{} frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist()) y = np.array(df['label'].tolist()) imageids =",
"input file and produce a smaller one :param dataset: :param base_dir: :param jit_data_file:",
"store SVM's prediction on DNN's positive frames clf = None positive_supply = StealPositiveFromVideoEnd(df_in,",
"for video {}\".format(video_rows.shape[0], video_id)) count = 0 gridxy_grp = video_rows.groupby(['grid_x', 'grid_y']) for gridxy,",
"if not isinstance(mp_stride_secs, list): # mp_stride_secs = [mp_stride_secs] df = pd.read_pickle(jit_data_file) print(\"Found {}",
"not enough positives.\") pass assert y.shape == pred_jit.shape, \"y: {}, pred_jit: {}\".format(y.shape, pred_jit.shape)",
"downsample_df.sort_values(by=['imageid']) print(\"After max pooling, we have {} images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\") print downsample_df.iloc[::downsample_df.shape[0]",
"map(int, df.columns[2:]) for _, row in df.iterrows(): x = xlabels y = np.array(row[2:])",
"0, 1.0]) # plt.show() if savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None): paths = glob.glob(file_glob)",
"== vid] # accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--') if savefig: plt.savefig(savefig)",
"/ 30)), delta_t): # extract data within this window (from t to t+delta_t)",
"# min number of examples per class needed to train the SVM, #",
"if savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None): paths = glob.glob(file_glob) df = pd.DataFrame() for",
"df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--') if savefig: plt.savefig(savefig) plt.show() if __name__ == '__main__':",
"df.groupby(['videoid']) for video_id, video_rows in video_id_grp: print(\"Found {} frames for video {}\".format(video_rows.shape[0], video_id))",
"df1 = pd.read_csv(path, sep=' ') df = df.append(df1, ignore_index=True) print df # df",
"# dnn threshold for passing early discard filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, # train",
"t + delta_t)) df_test = df[(df['frameid'] >= t * 30) & (df['frameid'] <",
"== 1024, str(X_test.shape) # Do we have an SVM to use? if clf:",
"# pass-through DNN's prediction (DNN says all are positive) predictions = np.ones_like(y_test) #",
"refit=True) clf = SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train) else: print(\"NOT retraining.",
"use this file except in compliance with the License. # You may obtain",
"for dnn_cutoff in dnn_cutoff_list: for svm_cut in svm_cutoff: print(\"-\" * 50) print(\"Emulating video",
"jit_accuracy = accuracy_score(y, pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids,",
"pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import accuracy_score",
"if dnn_threshold_input_file is not None: print(\"Warning: Dnn_threshold_input_file is specified! Ignoring dnn_cutoff_start, dnn_cutoff_end, \"",
"mp_span_secs: :param mp_stride_secs: :return: \"\"\" # if not isinstance(mp_span_secs, list): # mp_span_secs =",
"df = pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda",
"on drone video # feeds leveraging edge servers. # # Copyright (C) 2018-2019",
"fires {} frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist()) y = np.array(df['label'].tolist()) imageids",
"/ 10] if output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def __init__(self, df, video_id, tail=10): super(StealPositiveFromVideoEnd,",
"np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label']) assert X_test.shape[1] == 1024, str(X_test.shape) # Do we have",
"= np.append(pred_jit, predictions, axis=0) sent_mask = (predictions == 1) X_jit = np.append(X_jit, X_test[sent_mask],",
"# plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid in video_ids: df_video = df[df['video_id'] == vid] #",
"def __init__(self, df, video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__() df = df[(df['videoid'] == video_id) &",
"in range(0, int(1 + (max_frame / 30)), delta_t): # extract data within this",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid in video_ids: df_video = df[df['video_id'] == vid]",
"under the License. import glob import fire import matplotlib import numpy as np",
"clf: smv_proba = clf.predict_proba(X_test) predictions = (smv_proba[:, 1] >= svm_cutoff) # predictions =",
"examples per class needed to train the SVM, # otherwise passthrough; training set",
"(df['frameid'] < (t + delta_t) * 30)] # print df_test.iloc[:5] if df_test.empty: continue",
"images in total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int)",
"np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] == 2, dnn_proba.shape dnn_fire = (dnn_proba[:, 1] >= dnn_cutoff) dnn_fire_index",
"prediction and cumulative JIT training set pred_jit = np.append(pred_jit, predictions, axis=0) sent_mask =",
"savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None): paths = glob.glob(file_glob) df = pd.DataFrame() for path",
"= imageid count += 1 print(\"Sample {}/{} frames from video {}\".format(count, video_rows.shape[0], video_id))",
"are positive) predictions = np.ones_like(y_test) # write out to global prediction and cumulative",
"axis=0) sent_mask = (predictions == 1) X_jit = np.append(X_jit, X_test[sent_mask], axis=0) y_jit =",
"assert X_jit.shape[1] == 1024 # print(\"Found {} frames in window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask)))",
"np.array(df['label'].tolist()) imageids = df['imageid'].tolist() max_frame = df['frameid'].max() print(\"Max frame ID: {}\".format(max_frame)) X_jit =",
"class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train) else: print(\"NOT retraining. Nothing new or not enough",
"pool_start_frm) & (inputs['frameid'] < pool_start_frm + span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim",
"frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid in video_ids: df_video = df[df['video_id'] ==",
"StealPositiveFromVideoEnd(df_in, video_id) for t in range(0, int(1 + (max_frame / 30)), delta_t): #",
"# A computer vision pipeline for live video search on drone video #",
"frames from video {}\".format(count, video_rows.shape[0], video_id)) downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After max pooling, we",
"last_sent_imageid = None min_frm = inputs['frameid'].min() max_frm = inputs['frameid'].max() for pool_start_frm in range(min_frm,",
"# print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5): samples = resample(self.features, n_samples=n, replace=False)",
"isinstance(mp_stride_secs, list): # mp_stride_secs = [mp_stride_secs] df = pd.read_pickle(jit_data_file) print(\"Found {} images in",
"dnn positive if len(dnn_fire_index) == 0: print(\"DNN fires nothing. Stop\") return None print(\"DNN",
"t to t+delta_t) # print(\"time window {} to {}\".format(t, t + delta_t)) df_test",
"== video_id] # print df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] == 2, dnn_proba.shape",
"= positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit, augment_pos_X, axis=0) y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"# print(\"time window {} to {}\".format(t, t + delta_t)) df_test = df[(df['frameid'] >=",
"== 1) >= activate_threshold): print(\"retraining\") if not np.count_nonzero(y_jit == 1) >= activate_threshold and",
"list: {}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid']",
"= run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df = result_df.append(rv, ignore_index=True) print result_df",
"np.array(df['feature'].tolist()) y = np.array(df['label'].tolist()) imageids = df['imageid'].tolist() max_frame = df['frameid'].max() print(\"Max frame ID:",
"assert y.shape == pred_jit.shape, \"y: {}, pred_jit: {}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0] == np.count_nonzero(pred_jit)",
"plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid in video_ids: df_video = df[df['video_id'] == vid] # accuracy",
":param mp_stride_secs: :return: \"\"\" # if not isinstance(mp_span_secs, list): # mp_span_secs = [mp_span_secs]",
"== 1) X_jit = np.append(X_jit, X_test[sent_mask], axis=0) y_jit = np.append(y_jit, y_test[sent_mask], axis=0) assert",
"sent_mask = (predictions == 1) X_jit = np.append(X_jit, X_test[sent_mask], axis=0) y_jit = np.append(y_jit,",
"print(\"Max pooling span frames={}, stride frame={}\".format(span_frms, stride_frms)) downsample_df = pd.DataFrame() video_id_grp = df.groupby(['videoid'])",
"shall we (re-)train a new SVM? print(\"JIT training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask)",
"= 0 gridxy_grp = video_rows.groupby(['grid_x', 'grid_y']) for gridxy, inputs in gridxy_grp: inputs =",
"svm_cutoff=svm_cut) result_df = result_df.append(rv, ignore_index=True) print result_df if output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id,",
"count = 0 gridxy_grp = video_rows.groupby(['grid_x', 'grid_y']) for gridxy, inputs in gridxy_grp: inputs",
"= df.sort_values(by=['frameid']) # print(\"Will steal these positives:\") # print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def",
"image: {}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid = imageid count += 1 print(\"Sample",
">= dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0] # filter df by dnn positive if len(dnn_fire_index)",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"if df_test.empty: continue X_test = np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label']) assert X_test.shape[1] == 1024,",
"np.count_nonzero(y_jit == 0) >= activate_threshold \\ and (augment_positive or np.count_nonzero(y_jit == 1) >=",
"imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit, 'label': y, 'video_id': video_id,",
"df by dnn positive if len(dnn_fire_index) == 0: print(\"DNN fires nothing. Stop\") return",
"print(\"sampled image: {}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid = imageid count += 1",
"in dnn_cutoff_list: for svm_cut in svm_cutoff: print(\"-\" * 50) print(\"Emulating video '{}' w/",
"mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run max pooling on a dataset's JITL input file and",
"import resample from jitl_data import _split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\"",
"_get_videoid def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run max pooling on a dataset's",
"# # Unless required by applicable law or agreed to in writing, software",
"assert dnn_scores.ndim == 1 max_ind = np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind] if imageid !=",
"pd from matplotlib import pyplot as plt from sklearn.metrics import accuracy_score from sklearn.svm",
"n_samples=n, replace=False) return samples def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn threshold for",
"video_id)) downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After max pooling, we have {} images\".format(downsample_df.shape[0])) print(\"Sample 10",
"& (inputs['frameid'] < pool_start_frm + span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim ==",
"express or implied. # See the License for the specific language governing permissions",
"= pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit,",
"cumulative JIT training set pred_jit = np.append(pred_jit, predictions, axis=0) sent_mask = (predictions ==",
"svm_cutoff=0.3, augment_positive=False): # filter df by video id df = df_in[df_in['videoid'] == video_id]",
"fire import matplotlib import numpy as np import pandas as pd from matplotlib",
"DNN's positive frames clf = None positive_supply = StealPositiveFromVideoEnd(df_in, video_id) for t in",
"for x in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn cutoff list: {}\".format(dnn_cutoff_list)) df =",
"print(\"Sample {}/{} frames from video {}\".format(count, video_rows.shape[0], video_id)) downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After max",
"= np.array(row[2:]) print x, y plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0, max(xlabels), 0, 1.0]) #",
"in df.iterrows(): x = xlabels y = np.array(row[2:]) print x, y plt.plot(xlabels, np.array(row[2:]),",
"np.count_nonzero(y_jit_train))) else: X_jit_train = X_jit y_jit_train = y_jit # use grid search to",
"ignore_index=True) print res_df return res_df def plot_frame_accuracy(input_file, savefig=None): df = pd.read_csv( input_file, sep=r'\\s+'",
"leveraging edge servers. # # Copyright (C) 2018-2019 Carnegie Mellon University # #",
"either express or implied. # See the License for the specific language governing",
"(predictions == 1) X_jit = np.append(X_jit, X_test[sent_mask], axis=0) y_jit = np.append(y_jit, y_test[sent_mask], axis=0)",
"param_grid=tuned_params, # n_jobs=4, # refit=True) clf = SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train,",
"df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs * 30)",
"{} frames in window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now, shall we (re-)train a",
"* 50) rv = run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df = result_df.append(rv,",
"else: dnn_cutoff_list = [0.01 * x for x in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated",
"= df.append(df1, ignore_index=True) print df # df = df[df['delta_t'] < 90] video_ids =",
"kernel='linear', class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train) else: print(\"NOT retraining. Nothing new or not",
"y[:0] # same pred_jit = y[:0] # store SVM's prediction on DNN's positive",
"gridxy, inputs in gridxy_grp: inputs = inputs.sort_values(by=['frameid']) last_sent_imageid = None min_frm = inputs['frameid'].min()",
"activate_threshold=5, svm_cutoff=0.3, augment_positive=False): # filter df by video id df = df_in[df_in['videoid'] ==",
"we (re-)train a new SVM? print(\"JIT training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) >",
"= { # 'C': [1], # 'kernel': ['linear'], # } # clf =",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn cutoff list: {}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file) print df.iloc[:5]",
"# otherwise passthrough; training set is ever expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff, list):",
":param base_dir: :param jit_data_file: :param mp_span_secs: :param mp_stride_secs: :return: \"\"\" # if not",
"pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy':",
"pd.DataFrame() video_id_grp = df.groupby(['videoid']) for video_id, video_rows in video_id_grp: print(\"Found {} frames for",
"max pooling, we have {} images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\") print downsample_df.iloc[::downsample_df.shape[0] / 10]",
"= np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn cutoff threshold is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list = [0.01",
"an SVM to use? if clf: smv_proba = clf.predict_proba(X_test) predictions = (smv_proba[:, 1]",
"if not isinstance(mp_span_secs, list): # mp_span_secs = [mp_span_secs] # if not isinstance(mp_stride_secs, list):",
"inputs['frameid'].min() max_frm = inputs['frameid'].max() for pool_start_frm in range(min_frm, max_frm + 1, stride_frms): #",
"= df['imageid'].tolist() max_frame = df['frameid'].max() print(\"Max frame ID: {}\".format(max_frame)) X_jit = X[:0] #",
"xlabels y = np.array(row[2:]) print x, y plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0, max(xlabels), 0,",
"ax2 = ax1.twinx() ax2.set_ylabel(\"# frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid in video_ids:",
"if output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def __init__(self, df, video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__() df",
"inputs[(inputs['frameid'] >= pool_start_frm) & (inputs['frameid'] < pool_start_frm + span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1]",
"dnn_cutoff, svm_cut)) print(\"-\" * 50) rv = run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut)",
"JIT SVM y_jit = y[:0] # same pred_jit = y[:0] # store SVM's",
"jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit, 'label': y, 'video_id': video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True) print",
"video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True) print res_df return res_df def plot_frame_accuracy(input_file, savefig=None): df =",
"np.nonzero(dnn_fire)[0] # filter df by dnn positive if len(dnn_fire_index) == 0: print(\"DNN fires",
"print df xlabels = map(int, df.columns[2:]) for _, row in df.iterrows(): x =",
"= downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid = imageid count += 1 print(\"Sample {}/{} frames from",
"* 30) print(\"Max pooling span frames={}, stride frame={}\".format(span_frms, stride_frms)) downsample_df = pd.DataFrame() video_id_grp",
"< 90] video_ids = set(df['video_id']) fig, ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame",
"pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int)",
"from video {}\".format(count, video_rows.shape[0], video_id)) downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After max pooling, we have",
"dnn threshold for passing early discard filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, # train every",
"+ (max_frame / 30)), delta_t): # extract data within this window (from t",
"'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit, 'label': y, 'video_id': video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True) print res_df",
"activate_threshold \\ and (augment_positive or np.count_nonzero(y_jit == 1) >= activate_threshold): print(\"retraining\") if not",
"(DNN says all are positive) predictions = np.ones_like(y_test) # write out to global",
"the License. # You may obtain a copy of the License at #",
"import pyplot as plt from sklearn.metrics import accuracy_score from sklearn.svm import SVC from",
"accuracy: {}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples':",
"# predictions = clf.predict(X_test) else: # pass-through DNN's prediction (DNN says all are",
"vid in video_ids: df_video = df[df['video_id'] == vid] # accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-')",
":param jit_data_file: :param mp_span_secs: :param mp_stride_secs: :return: \"\"\" # if not isinstance(mp_span_secs, list):",
"= np.array(df['label'].tolist()) imageids = df['imageid'].tolist() max_frame = df['frameid'].max() print(\"Max frame ID: {}\".format(max_frame)) X_jit",
"predictions, axis=0) sent_mask = (predictions == 1) X_jit = np.append(X_jit, X_test[sent_mask], axis=0) y_jit",
"X_jit_train = np.append(X_jit, augment_pos_X, axis=0) y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0] ==",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"frame {} and {}\".format(pool_start_frm, pool_start_frm + span_frms)) pool_images = inputs[(inputs['frameid'] >= pool_start_frm) &",
"video_id, video_rows in video_id_grp: print(\"Found {} frames for video {}\".format(video_rows.shape[0], video_id)) count =",
"pipeline for live video search on drone video # feeds leveraging edge servers.",
"print(\"Houston, we don't have enough TPs.\") augment_pos_X = positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit, augment_pos_X,",
"clf.predict(X_test) else: # pass-through DNN's prediction (DNN says all are positive) predictions =",
"from matplotlib import pyplot as plt from sklearn.metrics import accuracy_score from sklearn.svm import",
"= int(mp_stride_secs * 30) print(\"Max pooling span frames={}, stride frame={}\".format(span_frms, stride_frms)) downsample_df =",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"= glob.glob(file_glob) df = pd.DataFrame() for path in paths: print(\"Parsing {}\".format(path)) df1 =",
"{} and {}\".format(pool_start_frm, pool_start_frm + span_frms)) pool_images = inputs[(inputs['frameid'] >= pool_start_frm) & (inputs['frameid']",
"df = df[(df['videoid'] == video_id) & (df['label'].astype(bool))] df = df.sort_values(by=['frameid']) # print(\"Will steal",
"count += 1 print(\"Sample {}/{} frames from video {}\".format(count, video_rows.shape[0], video_id)) downsample_df =",
"10s activate_threshold=5, # min number of examples per class needed to train the",
"= pd.DataFrame() for video_id in unique_videos: for dnn_cutoff in dnn_cutoff_list: for svm_cut in",
"probability=True, # verbose=True), # param_grid=tuned_params, # n_jobs=4, # refit=True) clf = SVC(random_state=42, kernel='linear',",
"resample(self.features, n_samples=n, replace=False) return samples def eval_jit_svm_on_dataset(jit_data_file, output_file, dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn threshold",
"<filename>scripts/jitl_test.py # Drone Search # # A computer vision pipeline for live video",
"x: _get_videoid(x)) df['frameid'] = df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y']",
"{} frames for video {}\".format(video_rows.shape[0], video_id)) count = 0 gridxy_grp = video_rows.groupby(['grid_x', 'grid_y'])",
"extract data within this window (from t to t+delta_t) # print(\"time window {}",
"if np.count_nonzero(sent_mask) > 0 \\ and np.count_nonzero(y_jit == 0) >= activate_threshold \\ and",
"pred_jit, 'label': y, 'video_id': video_id, 'svm_cutoff': svm_cutoff}, ignore_index=True) print res_df return res_df def",
"train the SVM, # otherwise passthrough; training set is ever expanding; svm_cutoff=0.3): if",
"X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train = X_jit y_jit_train",
"max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run max pooling on a dataset's JITL input",
"dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn cutoff threshold is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list =",
"= ax1.twinx() ax2.set_ylabel(\"# frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid in video_ids: df_video",
"discard filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, # train every 10s activate_threshold=5, # min number",
"# Do we have an SVM to use? if clf: smv_proba = clf.predict_proba(X_test)",
"\\ and np.count_nonzero(y_jit == 0) >= activate_threshold \\ and (augment_positive or np.count_nonzero(y_jit ==",
"df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist()) y = np.array(df['label'].tolist()) imageids = df['imageid'].tolist() max_frame = df['frameid'].max()",
"min_frm = inputs['frameid'].min() max_frm = inputs['frameid'].max() for pool_start_frm in range(min_frm, max_frm + 1,",
"import _split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run max pooling on",
"np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train",
"# extract data within this window (from t to t+delta_t) # print(\"time window",
"y = np.array(row[2:]) print x, y plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0, max(xlabels), 0, 1.0])",
"# max_iter=100, # class_weight='balanced', # probability=True, # verbose=True), # param_grid=tuned_params, # n_jobs=4, #",
"one :param dataset: :param base_dir: :param jit_data_file: :param mp_span_secs: :param mp_stride_secs: :return: \"\"\"",
"'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit, 'label': y, 'video_id': video_id, 'svm_cutoff':",
"None print(\"DNN fires {} frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist()) y =",
"is not None: print(\"Warning: Dnn_threshold_input_file is specified! Ignoring dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step variable.\")",
"License. import glob import fire import matplotlib import numpy as np import pandas",
"by video id df = df_in[df_in['videoid'] == video_id] # print df.iloc[0] dnn_proba =",
"dnn_proba = np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] == 2, dnn_proba.shape dnn_fire = (dnn_proba[:, 1] >=",
"# store SVM's prediction on DNN's positive frames clf = None positive_supply =",
"< (t + delta_t) * 30)] # print df_test.iloc[:5] if df_test.empty: continue X_test",
"df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs * 30) stride_frms = int(mp_stride_secs * 30)",
"x in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn cutoff list: {}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file)",
"ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1)) ax2 = ax1.twinx()",
"pred_jit = np.append(pred_jit, predictions, axis=0) sent_mask = (predictions == 1) X_jit = np.append(X_jit,",
"& (df['label'].astype(bool))] df = df.sort_values(by=['frameid']) # print(\"Will steal these positives:\") # print(df.iloc[-tail:]) self.features",
"= df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda x:",
"for video_id, video_rows in video_id_grp: print(\"Found {} frames for video {}\".format(video_rows.shape[0], video_id)) count",
"accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'], '--') if savefig: plt.savefig(savefig) plt.show() if __name__",
"= [mp_span_secs] # if not isinstance(mp_stride_secs, list): # mp_stride_secs = [mp_stride_secs] df =",
"1 max_ind = np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind] if imageid != last_sent_imageid: # print(\"sampled",
"with the License. # You may obtain a copy of the License at",
"x, y plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0, max(xlabels), 0, 1.0]) # plt.show() if savefig:",
"{}\".format(t, t + delta_t)) df_test = df[(df['frameid'] >= t * 30) & (df['frameid']",
"or not enough positives.\") pass assert y.shape == pred_jit.shape, \"y: {}, pred_jit: {}\".format(y.shape,",
"accuracy_score(y, pred_jit) print(\"JIT accuracy: {}\".format(jit_accuracy)) res_df = pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids, 'dnn_cutoff': dnn_cutoff,",
"not isinstance(mp_span_secs, list): # mp_span_secs = [mp_span_secs] # if not isinstance(mp_stride_secs, list): #",
"= y_jit # use grid search to improve SVM accuracy # tuned_params =",
"number of examples per class needed to train the SVM, # otherwise passthrough;",
"output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False): # filter df",
"= np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] == 2, dnn_proba.shape dnn_fire = (dnn_proba[:, 1] >= dnn_cutoff)",
"StealPositiveFromVideoEnd(object): def __init__(self, df, video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__() df = df[(df['videoid'] == video_id)",
"grid search to improve SVM accuracy # tuned_params = { # 'C': [1],",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim == 1 max_ind = np.argmax(dnn_scores) imageid = pool_images['imageid'].iloc[max_ind] if",
"delta_t): # extract data within this window (from t to t+delta_t) # print(\"time",
"res_df = pd.DataFrame().append({'delta_t': delta_t, 'imageids': imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction':",
"np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0] == y_jit_train.shape[0] print(\"Now you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else:",
"edge servers. # # Copyright (C) 2018-2019 Carnegie Mellon University # # Licensed",
"video '{}' w/ DNN cutoff {}, SVM cutoff {}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\" *",
"= df[(df['videoid'] == video_id) & (df['label'].astype(bool))] df = df.sort_values(by=['frameid']) # print(\"Will steal these",
"inputs['frameid'].max() for pool_start_frm in range(min_frm, max_frm + 1, stride_frms): # print(\"Max pooling between",
"pd.DataFrame() for video_id in unique_videos: for dnn_cutoff in dnn_cutoff_list: for svm_cut in svm_cutoff:",
"between frame {} and {}\".format(pool_start_frm, pool_start_frm + span_frms)) pool_images = inputs[(inputs['frameid'] >= pool_start_frm)",
"specific language governing permissions and # limitations under the License. import glob import",
"!= last_sent_imageid: # print(\"sampled image: {}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid = imageid",
"from sklearn.utils import resample from jitl_data import _split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0,",
"Search # # A computer vision pipeline for live video search on drone",
"== video_id) & (df['label'].astype(bool))] df = df.sort_values(by=['frameid']) # print(\"Will steal these positives:\") #",
"delta_t=10, # train every 10s activate_threshold=5, # min number of examples per class",
"{}/{} frames from video {}\".format(count, video_rows.shape[0], video_id)) downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After max pooling,",
"np.append(pred_jit, predictions, axis=0) sent_mask = (predictions == 1) X_jit = np.append(X_jit, X_test[sent_mask], axis=0)",
"int(1 + (max_frame / 30)), delta_t): # extract data within this window (from",
"(augment_positive or np.count_nonzero(y_jit == 1) >= activate_threshold): print(\"retraining\") if not np.count_nonzero(y_jit == 1)",
"class needed to train the SVM, # otherwise passthrough; training set is ever",
"set pred_jit = np.append(pred_jit, predictions, axis=0) sent_mask = (predictions == 1) X_jit =",
"'imageids': imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit, 'label': y, 'video_id':",
"span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert dnn_scores.ndim == 1 max_ind = np.argmax(dnn_scores) imageid",
"delta_t, 'imageids': imageids, 'dnn_cutoff': dnn_cutoff, 'jitl_accuracy': jit_accuracy, 'jitl_samples': y_jit.shape[0], 'jitl_prediction': pred_jit, 'label': y,",
"mp_stride_secs: :return: \"\"\" # if not isinstance(mp_span_secs, list): # mp_span_secs = [mp_span_secs] #",
"is specified! Ignoring dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded",
"DNN's prediction (DNN says all are positive) predictions = np.ones_like(y_test) # write out",
"law or agreed to in writing, software # distributed under the License is",
"(t + delta_t) * 30)] # print df_test.iloc[:5] if df_test.empty: continue X_test =",
"and cumulative JIT training set pred_jit = np.append(pred_jit, predictions, axis=0) sent_mask = (predictions",
"the License for the specific language governing permissions and # limitations under the",
"'grid_y']) for gridxy, inputs in gridxy_grp: inputs = inputs.sort_values(by=['frameid']) last_sent_imageid = None min_frm",
"dnn_cutoff_list = [0.01 * x for x in range(dnn_cutoff_start, dnn_cutoff_end, dnn_cutoff_step)] print(\"Generated dnn",
"np.array(df_test['label']) assert X_test.shape[1] == 1024, str(X_test.shape) # Do we have an SVM to",
"result_df = result_df.append(rv, ignore_index=True) print result_df if output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff,",
"res_df def plot_frame_accuracy(input_file, savefig=None): df = pd.read_csv( input_file, sep=r'\\s+' ) print df xlabels",
"not None: print(\"Warning: Dnn_threshold_input_file is specified! Ignoring dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step variable.\") dnn_cutoff_list",
"df xlabels = map(int, df.columns[2:]) for _, row in df.iterrows(): x = xlabels",
"savefig=None): paths = glob.glob(file_glob) df = pd.DataFrame() for path in paths: print(\"Parsing {}\".format(path))",
"y = np.array(df['label'].tolist()) imageids = df['imageid'].tolist() max_frame = df['frameid'].max() print(\"Max frame ID: {}\".format(max_frame))",
"# limitations under the License. import glob import fire import matplotlib import numpy",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"span_frms = int(mp_span_secs * 30) stride_frms = int(mp_stride_secs * 30) print(\"Max pooling span",
"df = df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist()) y = np.array(df['label'].tolist()) imageids = df['imageid'].tolist() max_frame",
"plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0, max(xlabels), 0, 1.0]) # plt.show() if savefig: plt.savefig(savefig) def",
"new or not enough positives.\") pass assert y.shape == pred_jit.shape, \"y: {}, pred_jit:",
"1024, str(X_test.shape) # Do we have an SVM to use? if clf: smv_proba",
"frames={}, stride frame={}\".format(span_frms, stride_frms)) downsample_df = pd.DataFrame() video_id_grp = df.groupby(['videoid']) for video_id, video_rows",
"if len(dnn_fire_index) == 0: print(\"DNN fires nothing. Stop\") return None print(\"DNN fires {}",
"plot_frame_accuracy(input_file, savefig=None): df = pd.read_csv( input_file, sep=r'\\s+' ) print df xlabels = map(int,",
"t in range(0, int(1 + (max_frame / 30)), delta_t): # extract data within",
"in paths: print(\"Parsing {}\".format(path)) df1 = pd.read_csv(path, sep=' ') df = df.append(df1, ignore_index=True)",
"1 print(\"Sample {}/{} frames from video {}\".format(count, video_rows.shape[0], video_id)) downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After",
"pooling between frame {} and {}\".format(pool_start_frm, pool_start_frm + span_frms)) pool_images = inputs[(inputs['frameid'] >=",
"activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df = result_df.append(rv, ignore_index=True) print result_df if output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in,",
"\"\"\" # if not isinstance(mp_span_secs, list): # mp_span_secs = [mp_span_secs] # if not",
"imageid != last_sent_imageid: # print(\"sampled image: {}\".format(imageid)) downsample_df = downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid =",
"= np.append(X_jit, augment_pos_X, axis=0) y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)), axis=0) assert X_jit_train.shape[0] == y_jit_train.shape[0]",
"plt.axis([0, max(xlabels), 0, 1.0]) # plt.show() if savefig: plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None): paths",
"df = df_in[df_in['videoid'] == video_id] # print df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1]",
"used to train JIT SVM y_jit = y[:0] # same pred_jit = y[:0]",
"accuracy\") ax1.set_ylim((0, 1)) ax2 = ax1.twinx() ax2.set_ylabel(\"# frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for",
"y plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0, max(xlabels), 0, 1.0]) # plt.show() if savefig: plt.savefig(savefig)",
"SVM to use? if clf: smv_proba = clf.predict_proba(X_test) predictions = (smv_proba[:, 1] >=",
">= activate_threshold and augment_positive: print(\"Houston, we don't have enough TPs.\") augment_pos_X = positive_supply(n=activate_threshold)",
"dnn_threshold_input_file=None, dnn_cutoff_start=80, # dnn threshold for passing early discard filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10,",
"xlabels = map(int, df.columns[2:]) for _, row in df.iterrows(): x = xlabels y",
"in compliance with the License. # You may obtain a copy of the",
"train JIT SVM y_jit = y[:0] # same pred_jit = y[:0] # store",
"df.append(df1, ignore_index=True) print df # df = df[df['delta_t'] < 90] video_ids = set(df['video_id'])",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"df['frameid'] = df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda",
"= pd.DataFrame() video_id_grp = df.groupby(['videoid']) for video_id, video_rows in video_id_grp: print(\"Found {} frames",
"print(\"JIT training set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) > 0 \\ and np.count_nonzero(y_jit ==",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"mp_stride_secs=0.5): \"\"\" Run max pooling on a dataset's JITL input file and produce",
"run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df = result_df.append(rv, ignore_index=True) print result_df if",
"dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0] # filter df by dnn positive if len(dnn_fire_index) ==",
"jitl_data import _split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run max pooling",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"# print(\"Max pooling between frame {} and {}\".format(pool_start_frm, pool_start_frm + span_frms)) pool_images =",
"# if not isinstance(mp_span_secs, list): # mp_span_secs = [mp_span_secs] # if not isinstance(mp_stride_secs,",
"(max_frame / 30)), delta_t): # extract data within this window (from t to",
"verbose=True), # param_grid=tuned_params, # n_jobs=4, # refit=True) clf = SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True,",
"pd.read_csv( input_file, sep=r'\\s+' ) print df xlabels = map(int, df.columns[2:]) for _, row",
"_split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file, output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run max pooling on a",
"1] >= dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0] # filter df by dnn positive if",
"smv_proba = clf.predict_proba(X_test) predictions = (smv_proba[:, 1] >= svm_cutoff) # predictions = clf.predict(X_test)",
"cutoff {}, SVM cutoff {}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\" * 50) rv = run_once_jit_svm_on_video(df,",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"(sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1)) ax2 = ax1.twinx() ax2.set_ylabel(\"# frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])),",
"delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df = result_df.append(rv, ignore_index=True) print result_df if output_file: result_df.to_pickle(output_file) def",
"window {} to {}\".format(t, t + delta_t)) df_test = df[(df['frameid'] >= t *",
"# param_grid=tuned_params, # n_jobs=4, # refit=True) clf = SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True, verbose=0)",
"* 30) stride_frms = int(mp_stride_secs * 30) print(\"Max pooling span frames={}, stride frame={}\".format(span_frms,",
"# train every 10s activate_threshold=5, # min number of examples per class needed",
"and augment_positive: print(\"Houston, we don't have enough TPs.\") augment_pos_X = positive_supply(n=activate_threshold) X_jit_train =",
"w/ DNN cutoff {}, SVM cutoff {}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\" * 50) rv",
"{}\".format(pool_start_frm, pool_start_frm + span_frms)) pool_images = inputs[(inputs['frameid'] >= pool_start_frm) & (inputs['frameid'] < pool_start_frm",
"pool_start_frm + span_frms)) pool_images = inputs[(inputs['frameid'] >= pool_start_frm) & (inputs['frameid'] < pool_start_frm +",
"10] if output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def __init__(self, df, video_id, tail=10): super(StealPositiveFromVideoEnd, self).__init__()",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"= GridSearchCV(SVC(random_state=43, # max_iter=100, # class_weight='balanced', # probability=True, # verbose=True), # param_grid=tuned_params, #",
"downsample_df.iloc[::downsample_df.shape[0] / 10] if output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object): def __init__(self, df, video_id, tail=10):",
"df = pd.DataFrame() for path in paths: print(\"Parsing {}\".format(path)) df1 = pd.read_csv(path, sep='",
"X[:0] # cumulative, used to train JIT SVM y_jit = y[:0] # same",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"df['frameid'] = df['imageid'].map(lambda imgid: _split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos = set(df['videoid'].tolist()) result_df = pd.DataFrame()",
"y_jit = y[:0] # same pred_jit = y[:0] # store SVM's prediction on",
"{}\".format(video_rows.shape[0], video_id)) count = 0 gridxy_grp = video_rows.groupby(['grid_x', 'grid_y']) for gridxy, inputs in",
"import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import",
"1, stride_frms): # print(\"Max pooling between frame {} and {}\".format(pool_start_frm, pool_start_frm + span_frms))",
"tail=10): super(StealPositiveFromVideoEnd, self).__init__() df = df[(df['videoid'] == video_id) & (df['label'].astype(bool))] df = df.sort_values(by=['frameid'])",
"None: print(\"Warning: Dnn_threshold_input_file is specified! Ignoring dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step variable.\") dnn_cutoff_list =",
"* 30)] # print df_test.iloc[:5] if df_test.empty: continue X_test = np.array(df_test['feature'].tolist()) y_test =",
"run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False): # filter df by video id",
"downsample_df = pd.DataFrame() video_id_grp = df.groupby(['videoid']) for video_id, video_rows in video_id_grp: print(\"Found {}",
"# n_jobs=4, # refit=True) clf = SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train)",
"= pd.read_csv(path, sep=' ') df = df.append(df1, ignore_index=True) print df # df =",
"dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df = result_df.append(rv, ignore_index=True) print result_df if output_file: result_df.to_pickle(output_file)",
"df_in[df_in['videoid'] == video_id] # print df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] == 2,",
"range(0, int(1 + (max_frame / 30)), delta_t): # extract data within this window",
"frames\".format(len(dnn_fire_index))) df = df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist()) y = np.array(df['label'].tolist()) imageids = df['imageid'].tolist()",
"30)] # print df_test.iloc[:5] if df_test.empty: continue X_test = np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label'])",
"y[:0] # store SVM's prediction on DNN's positive frames clf = None positive_supply",
"passthrough; training set is ever expanding; svm_cutoff=0.3): if not isinstance(svm_cutoff, list): svm_cutoff =",
"df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] == 2, dnn_proba.shape dnn_fire = (dnn_proba[:, 1]",
"delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False): # filter df by video id df = df_in[df_in['videoid']",
"{}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now, shall we (re-)train a new SVM? print(\"JIT training set",
"return res_df def plot_frame_accuracy(input_file, savefig=None): df = pd.read_csv( input_file, sep=r'\\s+' ) print df",
"df['frameid'].max() print(\"Max frame ID: {}\".format(max_frame)) X_jit = X[:0] # cumulative, used to train",
">= activate_threshold \\ and (augment_positive or np.count_nonzero(y_jit == 1) >= activate_threshold): print(\"retraining\") if",
"downsample_df = downsample_df.sort_values(by=['imageid']) print(\"After max pooling, we have {} images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\")",
"df['imageid'].map(lambda x: _split_imageid(x)[1]).astype(int) df['grid_x'] = df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int)",
"print(\"-\" * 50) rv = run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df =",
"downsample_df.append(pool_images.iloc[max_ind], ignore_index=True) last_sent_imageid = imageid count += 1 print(\"Sample {}/{} frames from video",
"video_id_grp = df.groupby(['videoid']) for video_id, video_rows in video_id_grp: print(\"Found {} frames for video",
"t+delta_t) # print(\"time window {} to {}\".format(t, t + delta_t)) df_test = df[(df['frameid']",
"X_test.shape[1] == 1024, str(X_test.shape) # Do we have an SVM to use? if",
"id df = df_in[df_in['videoid'] == video_id] # print df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist()) assert",
"# 'C': [1], # 'kernel': ['linear'], # } # clf = GridSearchCV(SVC(random_state=43, #",
"_, row in df.iterrows(): x = xlabels y = np.array(row[2:]) print x, y",
"y_jit_train) else: print(\"NOT retraining. Nothing new or not enough positives.\") pass assert y.shape",
"in window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now, shall we (re-)train a new SVM?",
"SVC from sklearn.utils import resample from jitl_data import _split_imageid, _get_videoid def max_pooling_on_dataset(jit_data_file, output_file,",
"dnn_fire = (dnn_proba[:, 1] >= dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0] # filter df by",
"don't have enough TPs.\") augment_pos_X = positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit, augment_pos_X, axis=0) y_jit_train",
"to train JIT SVM y_jit = y[:0] # same pred_jit = y[:0] #",
"+ delta_t)) df_test = df[(df['frameid'] >= t * 30) & (df['frameid'] < (t",
"print(\"Emulating video '{}' w/ DNN cutoff {}, SVM cutoff {}\".format(video_id, dnn_cutoff, svm_cut)) print(\"-\"",
"max_frm + 1, stride_frms): # print(\"Max pooling between frame {} and {}\".format(pool_start_frm, pool_start_frm",
"is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list = [0.01 * x for x in range(dnn_cutoff_start, dnn_cutoff_end,",
"import glob import fire import matplotlib import numpy as np import pandas as",
"not isinstance(svm_cutoff, list): svm_cutoff = [svm_cutoff] if dnn_threshold_input_file is not None: print(\"Warning: Dnn_threshold_input_file",
"* 30) & (df['frameid'] < (t + delta_t) * 30)] # print df_test.iloc[:5]",
"global prediction and cumulative JIT training set pred_jit = np.append(pred_jit, predictions, axis=0) sent_mask",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"dnn_cutoff in dnn_cutoff_list: for svm_cut in svm_cutoff: print(\"-\" * 50) print(\"Emulating video '{}'",
"stride_frms = int(mp_stride_secs * 30) print(\"Max pooling span frames={}, stride frame={}\".format(span_frms, stride_frms)) downsample_df",
"except in compliance with the License. # You may obtain a copy of",
"you have {}/{}\".format(y_jit_train.shape[0], np.count_nonzero(y_jit_train))) else: X_jit_train = X_jit y_jit_train = y_jit # use",
"def plot_rolling_svm(file_glob, savefig=None): paths = glob.glob(file_glob) df = pd.DataFrame() for path in paths:",
"\"\"\" Run max pooling on a dataset's JITL input file and produce a",
"video_id) for t in range(0, int(1 + (max_frame / 30)), delta_t): # extract",
"dnn_cutoff_start=80, # dnn threshold for passing early discard filter dnn_cutoff_end=100, dnn_cutoff_step=2, delta_t=10, #",
"pd.DataFrame() for path in paths: print(\"Parsing {}\".format(path)) df1 = pd.read_csv(path, sep=' ') df",
"print df_test.iloc[:5] if df_test.empty: continue X_test = np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label']) assert X_test.shape[1]",
"# print(\"Will steal these positives:\") # print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5):",
"= video_rows.groupby(['grid_x', 'grid_y']) for gridxy, inputs in gridxy_grp: inputs = inputs.sort_values(by=['frameid']) last_sent_imageid =",
"pooling, we have {} images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\") print downsample_df.iloc[::downsample_df.shape[0] / 10] if",
"df['grid_x'] = df['imageid'].map(lambda x: _split_imageid(x)[2]).astype(int) df['grid_y'] = df['imageid'].map(lambda x: _split_imageid(x)[3]).astype(int) span_frms = int(mp_span_secs",
"# filter df by video id df = df_in[df_in['videoid'] == video_id] # print",
"dnn_proba.shape dnn_fire = (dnn_proba[:, 1] >= dnn_cutoff) dnn_fire_index = np.nonzero(dnn_fire)[0] # filter df",
"pool_images = inputs[(inputs['frameid'] >= pool_start_frm) & (inputs['frameid'] < pool_start_frm + span_frms)] dnn_scores =",
"every 10s activate_threshold=5, # min number of examples per class needed to train",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"Dnn_threshold_input_file is specified! Ignoring dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step variable.\") dnn_cutoff_list = np.load(dnn_threshold_input_file) dnn_cutoff_list.sort()",
"1) >= activate_threshold and augment_positive: print(\"Houston, we don't have enough TPs.\") augment_pos_X =",
"= int(mp_span_secs * 30) stride_frms = int(mp_stride_secs * 30) print(\"Max pooling span frames={},",
"= map(int, df.columns[2:]) for _, row in df.iterrows(): x = xlabels y =",
"rv = run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df = result_df.append(rv, ignore_index=True) print",
"ax1.set_ylim((0, 1)) ax2 = ax1.twinx() ax2.set_ylabel(\"# frames transmitted\") # plt.xticks(sorted(set(df['delta_t'])), sorted(set(df['delta_t']))) for vid",
"= df.iloc[dnn_fire_index] X = np.array(df['feature'].tolist()) y = np.array(df['label'].tolist()) imageids = df['imageid'].tolist() max_frame =",
"= pd.read_pickle(jit_data_file) print(\"Found {} images in total.\".format(df.shape[0])) df['videoid'] = df['imageid'].map(lambda x: _get_videoid(x)) df['frameid']",
"images\".format(downsample_df.shape[0])) print(\"Sample 10 rows.\") print downsample_df.iloc[::downsample_df.shape[0] / 10] if output_file: downsample_df.to_pickle(output_file) class StealPositiveFromVideoEnd(object):",
"np.append(X_jit, X_test[sent_mask], axis=0) y_jit = np.append(y_jit, y_test[sent_mask], axis=0) assert X_jit.shape[1] == 1024 #",
"None positive_supply = StealPositiveFromVideoEnd(df_in, video_id) for t in range(0, int(1 + (max_frame /",
"plot_rolling_svm(file_glob, savefig=None): paths = glob.glob(file_glob) df = pd.DataFrame() for path in paths: print(\"Parsing",
"pd.read_csv(path, sep=' ') df = df.append(df1, ignore_index=True) print df # df = df[df['delta_t']",
"the specific language governing permissions and # limitations under the License. import glob",
"print df.iloc[0] dnn_proba = np.array(df['prediction_proba'].tolist()) assert dnn_proba.shape[1] == 2, dnn_proba.shape dnn_fire = (dnn_proba[:,",
"print(\"Will steal these positives:\") # print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5): samples",
"for live video search on drone video # feeds leveraging edge servers. #",
"{ # 'C': [1], # 'kernel': ['linear'], # } # clf = GridSearchCV(SVC(random_state=43,",
"clf = GridSearchCV(SVC(random_state=43, # max_iter=100, # class_weight='balanced', # probability=True, # verbose=True), # param_grid=tuned_params,",
"x = xlabels y = np.array(row[2:]) print x, y plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0,",
"activate_threshold=5, # min number of examples per class needed to train the SVM,",
"set(df['video_id']) fig, ax1 = plt.subplots() ax1.set_xlabel(\"$\\Delta t$ (sec)\") ax1.set_ylabel(\"Frame accuracy\") ax1.set_ylim((0, 1)) ax2",
"GridSearchCV(SVC(random_state=43, # max_iter=100, # class_weight='balanced', # probability=True, # verbose=True), # param_grid=tuned_params, # n_jobs=4,",
"and {}\".format(pool_start_frm, pool_start_frm + span_frms)) pool_images = inputs[(inputs['frameid'] >= pool_start_frm) & (inputs['frameid'] <",
"'C': [1], # 'kernel': ['linear'], # } # clf = GridSearchCV(SVC(random_state=43, # max_iter=100,",
"frames clf = None positive_supply = StealPositiveFromVideoEnd(df_in, video_id) for t in range(0, int(1",
"enough positives.\") pass assert y.shape == pred_jit.shape, \"y: {}, pred_jit: {}\".format(y.shape, pred_jit.shape) assert",
"SVM's prediction on DNN's positive frames clf = None positive_supply = StealPositiveFromVideoEnd(df_in, video_id)",
"len(dnn_fire_index) == 0: print(\"DNN fires nothing. Stop\") return None print(\"DNN fires {} frames\".format(len(dnn_fire_index)))",
"within this window (from t to t+delta_t) # print(\"time window {} to {}\".format(t,",
"language governing permissions and # limitations under the License. import glob import fire",
"positives:\") # print(df.iloc[-tail:]) self.features = np.array(df.iloc[-tail:]['feature'].tolist()) def __call__(self, n=5): samples = resample(self.features, n_samples=n,",
"== 0) >= activate_threshold \\ and (augment_positive or np.count_nonzero(y_jit == 1) >= activate_threshold):",
"prediction on DNN's positive frames clf = None positive_supply = StealPositiveFromVideoEnd(df_in, video_id) for",
"a dataset's JITL input file and produce a smaller one :param dataset: :param",
">= pool_start_frm) & (inputs['frameid'] < pool_start_frm + span_frms)] dnn_scores = np.array(pool_images['prediction_proba'].tolist())[:, 1] assert",
"= np.array(df_test['label']) assert X_test.shape[1] == 1024, str(X_test.shape) # Do we have an SVM",
"on a dataset's JITL input file and produce a smaller one :param dataset:",
"{}\".format(path)) df1 = pd.read_csv(path, sep=' ') df = df.append(df1, ignore_index=True) print df #",
"from sklearn.metrics import accuracy_score from sklearn.svm import SVC from sklearn.utils import resample from",
"span_frms)) pool_images = inputs[(inputs['frameid'] >= pool_start_frm) & (inputs['frameid'] < pool_start_frm + span_frms)] dnn_scores",
"df.columns[2:]) for _, row in df.iterrows(): x = xlabels y = np.array(row[2:]) print",
"50) rv = run_once_jit_svm_on_video(df, video_id, dnn_cutoff=dnn_cutoff, delta_t=delta_t, activate_threshold=activate_threshold, svm_cutoff=svm_cut) result_df = result_df.append(rv, ignore_index=True)",
"and # limitations under the License. import glob import fire import matplotlib import",
"None min_frm = inputs['frameid'].min() max_frm = inputs['frameid'].max() for pool_start_frm in range(min_frm, max_frm +",
"df by video id df = df_in[df_in['videoid'] == video_id] # print df.iloc[0] dnn_proba",
"positives.\") pass assert y.shape == pred_jit.shape, \"y: {}, pred_jit: {}\".format(y.shape, pred_jit.shape) assert y_jit.shape[0]",
"video # feeds leveraging edge servers. # # Copyright (C) 2018-2019 Carnegie Mellon",
"dnn_threshold_input_file is not None: print(\"Warning: Dnn_threshold_input_file is specified! Ignoring dnn_cutoff_start, dnn_cutoff_end, \" \"dnn_cutoff_step",
"# print(\"Found {} frames in window. Sent {}.\".format(y_test.shape[0], np.count_nonzero(sent_mask))) # now, shall we",
"all are positive) predictions = np.ones_like(y_test) # write out to global prediction and",
"axis=0) y_jit = np.append(y_jit, y_test[sent_mask], axis=0) assert X_jit.shape[1] == 1024 # print(\"Found {}",
"clf = SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train) else: print(\"NOT retraining. Nothing",
"def plot_frame_accuracy(input_file, savefig=None): df = pd.read_csv( input_file, sep=r'\\s+' ) print df xlabels =",
"clf.fit(X_jit_train, y_jit_train) else: print(\"NOT retraining. Nothing new or not enough positives.\") pass assert",
"as np import pandas as pd from matplotlib import pyplot as plt from",
"plt.savefig(savefig) def plot_rolling_svm(file_glob, savefig=None): paths = glob.glob(file_glob) df = pd.DataFrame() for path in",
"augment_positive=False): # filter df by video id df = df_in[df_in['videoid'] == video_id] #",
"= None positive_supply = StealPositiveFromVideoEnd(df_in, video_id) for t in range(0, int(1 + (max_frame",
"jit_data_file: :param mp_span_secs: :param mp_stride_secs: :return: \"\"\" # if not isinstance(mp_span_secs, list): #",
"= np.append(X_jit, X_test[sent_mask], axis=0) y_jit = np.append(y_jit, y_test[sent_mask], axis=0) assert X_jit.shape[1] == 1024",
"we have an SVM to use? if clf: smv_proba = clf.predict_proba(X_test) predictions =",
"governing permissions and # limitations under the License. import glob import fire import",
"def __call__(self, n=5): samples = resample(self.features, n_samples=n, replace=False) return samples def eval_jit_svm_on_dataset(jit_data_file, output_file,",
"np.load(dnn_threshold_input_file) dnn_cutoff_list.sort() print(\"loaded dnn cutoff threshold is: {}\".format(dnn_cutoff_list)) else: dnn_cutoff_list = [0.01 *",
"output_file, mp_span_secs=1.0, mp_stride_secs=0.5): \"\"\" Run max pooling on a dataset's JITL input file",
"= xlabels y = np.array(row[2:]) print x, y plt.plot(xlabels, np.array(row[2:]), '-o') plt.axis([0, max(xlabels),",
"print result_df if output_file: result_df.to_pickle(output_file) def run_once_jit_svm_on_video(df_in, video_id, dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False):",
"SVC(random_state=42, kernel='linear', class_weight='balanced', probability=True, verbose=0) clf.fit(X_jit_train, y_jit_train) else: print(\"NOT retraining. Nothing new or",
"video_ids: df_video = df[df['video_id'] == vid] # accuracy ax1.plot(df_video['delta_t'], df_video['jit_accuracy'], '-') ax2.plot(df_video['delta_t'], df_video['jit_samples'],",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"print(\"Generated dnn cutoff list: {}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid'] = df['imageid'].map(lambda",
"write out to global prediction and cumulative JIT training set pred_jit = np.append(pred_jit,",
"vision pipeline for live video search on drone video # feeds leveraging edge",
"df[(df['frameid'] >= t * 30) & (df['frameid'] < (t + delta_t) * 30)]",
"{}\".format(max_frame)) X_jit = X[:0] # cumulative, used to train JIT SVM y_jit =",
"y_test[sent_mask], axis=0) assert X_jit.shape[1] == 1024 # print(\"Found {} frames in window. Sent",
"video_id, dnn_cutoff, delta_t=10, activate_threshold=5, svm_cutoff=0.3, augment_positive=False): # filter df by video id df",
"dnn_fire_index = np.nonzero(dnn_fire)[0] # filter df by dnn positive if len(dnn_fire_index) == 0:",
"'kernel': ['linear'], # } # clf = GridSearchCV(SVC(random_state=43, # max_iter=100, # class_weight='balanced', #",
"# mp_stride_secs = [mp_stride_secs] df = pd.read_pickle(jit_data_file) print(\"Found {} images in total.\".format(df.shape[0])) df['videoid']",
"_split_imageid(imgid)[1]).astype(int) print df.iloc[:5] unique_videos = set(df['videoid'].tolist()) result_df = pd.DataFrame() for video_id in unique_videos:",
"0) >= activate_threshold \\ and (augment_positive or np.count_nonzero(y_jit == 1) >= activate_threshold): print(\"retraining\")",
"dnn_cutoff_step)] print(\"Generated dnn cutoff list: {}\".format(dnn_cutoff_list)) df = pd.read_pickle(jit_data_file) print df.iloc[:5] df['videoid'] =",
"import numpy as np import pandas as pd from matplotlib import pyplot as",
"df_test.empty: continue X_test = np.array(df_test['feature'].tolist()) y_test = np.array(df_test['label']) assert X_test.shape[1] == 1024, str(X_test.shape)",
"TPs.\") augment_pos_X = positive_supply(n=activate_threshold) X_jit_train = np.append(X_jit, augment_pos_X, axis=0) y_jit_train = np.append(y_jit, np.ones((augment_pos_X.shape[0],)),",
"df[(df['videoid'] == video_id) & (df['label'].astype(bool))] df = df.sort_values(by=['frameid']) # print(\"Will steal these positives:\")",
"set {}/{}\".format(y_jit.shape[0], np.count_nonzero(y_jit))) if np.count_nonzero(sent_mask) > 0 \\ and np.count_nonzero(y_jit == 0) >="
] |
[
"num_clients self.device = device # update global model def update(self): raise NotImplementedError def",
"global model def update(self): raise NotImplementedError def get_model(self): return copy.deepcopy(self.model) \"\"\"This implements a",
"base class for client.\"\"\" class BaseClient: def __init__(self, id, model, optimizer, optimizer_args, dataloader,",
"dataloader self.device = device # update local model def update(self): raise NotImplementedError def",
"__init__(self, id, model, optimizer, optimizer_args, dataloader, device): self.id = id self.model = model",
"class for client.\"\"\" class BaseClient: def __init__(self, id, model, optimizer, optimizer_args, dataloader, device):",
"model def update(self): raise NotImplementedError def get_model(self): return copy.deepcopy(self.model) \"\"\"This implements a base",
"= optimizer self.optimizer_args = optimizer_args self.dataloader = dataloader self.device = device # update",
"class BaseClient: def __init__(self, id, model, optimizer, optimizer_args, dataloader, device): self.id = id",
"id, model, optimizer, optimizer_args, dataloader, device): self.id = id self.model = model self.optimizer",
"device): self.id = id self.model = model self.optimizer = optimizer self.optimizer_args = optimizer_args",
"num_clients, device): self.model = model self.num_clients = num_clients self.device = device # update",
"id self.model = model self.optimizer = optimizer self.optimizer_args = optimizer_args self.dataloader = dataloader",
"device # update local model def update(self): raise NotImplementedError def get_model(self): return self.model.state_dict()",
"= dataloader self.device = device # update local model def update(self): raise NotImplementedError",
"\"\"\"This implements a base class for server.\"\"\" class BaseServer: def __init__(self, model, num_clients,",
"copy.deepcopy(self.model) \"\"\"This implements a base class for client.\"\"\" class BaseClient: def __init__(self, id,",
"implements a base class for client.\"\"\" class BaseClient: def __init__(self, id, model, optimizer,",
"= model self.num_clients = num_clients self.device = device # update global model def",
"self.model = model self.num_clients = num_clients self.device = device # update global model",
"BaseClient: def __init__(self, id, model, optimizer, optimizer_args, dataloader, device): self.id = id self.model",
"= num_clients self.device = device # update global model def update(self): raise NotImplementedError",
"# update global model def update(self): raise NotImplementedError def get_model(self): return copy.deepcopy(self.model) \"\"\"This",
"copy \"\"\"This implements a base class for server.\"\"\" class BaseServer: def __init__(self, model,",
"optimizer_args self.dataloader = dataloader self.device = device # update local model def update(self):",
"optimizer_args, dataloader, device): self.id = id self.model = model self.optimizer = optimizer self.optimizer_args",
"= optimizer_args self.dataloader = dataloader self.device = device # update local model def",
"def __init__(self, model, num_clients, device): self.model = model self.num_clients = num_clients self.device =",
"def update(self): raise NotImplementedError def get_model(self): return copy.deepcopy(self.model) \"\"\"This implements a base class",
"self.dataloader = dataloader self.device = device # update local model def update(self): raise",
"class for server.\"\"\" class BaseServer: def __init__(self, model, num_clients, device): self.model = model",
"import copy \"\"\"This implements a base class for server.\"\"\" class BaseServer: def __init__(self,",
"model, num_clients, device): self.model = model self.num_clients = num_clients self.device = device #",
"for server.\"\"\" class BaseServer: def __init__(self, model, num_clients, device): self.model = model self.num_clients",
"get_model(self): return copy.deepcopy(self.model) \"\"\"This implements a base class for client.\"\"\" class BaseClient: def",
"raise NotImplementedError def get_model(self): return copy.deepcopy(self.model) \"\"\"This implements a base class for client.\"\"\"",
"\"\"\"This implements a base class for client.\"\"\" class BaseClient: def __init__(self, id, model,",
"def __init__(self, id, model, optimizer, optimizer_args, dataloader, device): self.id = id self.model =",
"self.model = model self.optimizer = optimizer self.optimizer_args = optimizer_args self.dataloader = dataloader self.device",
"self.optimizer = optimizer self.optimizer_args = optimizer_args self.dataloader = dataloader self.device = device #",
"= model self.optimizer = optimizer self.optimizer_args = optimizer_args self.dataloader = dataloader self.device =",
"optimizer self.optimizer_args = optimizer_args self.dataloader = dataloader self.device = device # update local",
"self.device = device # update local model def update(self): raise NotImplementedError def get_model(self):",
"class BaseServer: def __init__(self, model, num_clients, device): self.model = model self.num_clients = num_clients",
"device): self.model = model self.num_clients = num_clients self.device = device # update global",
"= device # update local model def update(self): raise NotImplementedError def get_model(self): return",
"= id self.model = model self.optimizer = optimizer self.optimizer_args = optimizer_args self.dataloader =",
"<reponame>markxiao/APPFL<gh_stars>0 import copy \"\"\"This implements a base class for server.\"\"\" class BaseServer: def",
"model self.num_clients = num_clients self.device = device # update global model def update(self):",
"base class for server.\"\"\" class BaseServer: def __init__(self, model, num_clients, device): self.model =",
"= device # update global model def update(self): raise NotImplementedError def get_model(self): return",
"for client.\"\"\" class BaseClient: def __init__(self, id, model, optimizer, optimizer_args, dataloader, device): self.id",
"self.device = device # update global model def update(self): raise NotImplementedError def get_model(self):",
"update global model def update(self): raise NotImplementedError def get_model(self): return copy.deepcopy(self.model) \"\"\"This implements",
"dataloader, device): self.id = id self.model = model self.optimizer = optimizer self.optimizer_args =",
"self.id = id self.model = model self.optimizer = optimizer self.optimizer_args = optimizer_args self.dataloader",
"server.\"\"\" class BaseServer: def __init__(self, model, num_clients, device): self.model = model self.num_clients =",
"self.num_clients = num_clients self.device = device # update global model def update(self): raise",
"return copy.deepcopy(self.model) \"\"\"This implements a base class for client.\"\"\" class BaseClient: def __init__(self,",
"implements a base class for server.\"\"\" class BaseServer: def __init__(self, model, num_clients, device):",
"model, optimizer, optimizer_args, dataloader, device): self.id = id self.model = model self.optimizer =",
"self.optimizer_args = optimizer_args self.dataloader = dataloader self.device = device # update local model",
"device # update global model def update(self): raise NotImplementedError def get_model(self): return copy.deepcopy(self.model)",
"__init__(self, model, num_clients, device): self.model = model self.num_clients = num_clients self.device = device",
"model self.optimizer = optimizer self.optimizer_args = optimizer_args self.dataloader = dataloader self.device = device",
"NotImplementedError def get_model(self): return copy.deepcopy(self.model) \"\"\"This implements a base class for client.\"\"\" class",
"a base class for server.\"\"\" class BaseServer: def __init__(self, model, num_clients, device): self.model",
"update(self): raise NotImplementedError def get_model(self): return copy.deepcopy(self.model) \"\"\"This implements a base class for",
"a base class for client.\"\"\" class BaseClient: def __init__(self, id, model, optimizer, optimizer_args,",
"optimizer, optimizer_args, dataloader, device): self.id = id self.model = model self.optimizer = optimizer",
"client.\"\"\" class BaseClient: def __init__(self, id, model, optimizer, optimizer_args, dataloader, device): self.id =",
"def get_model(self): return copy.deepcopy(self.model) \"\"\"This implements a base class for client.\"\"\" class BaseClient:",
"BaseServer: def __init__(self, model, num_clients, device): self.model = model self.num_clients = num_clients self.device"
] |
[
"len(a) if(aux==0): print(0) return canta = 0 for i in a: if(i[0]=='a'): canta+=1",
"= [] for i in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb aux",
"print(len(a)//2) lastA,lastB = -1,-1 for i in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(lastA+1,a[i][1]+1)",
"newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb aux = len(a) if(aux==0): print(0) return canta =",
"int(input()) a = SI() b = SI() def solve(n,a,b): d = Counter(a)+Counter(b) for",
"Counter(a)+Counter(b) for i in d: if(d[i]&1): print(-1) return xa = d[a]//2 newa =",
"a,b = newa,newb aux = len(a) if(aux==0): print(0) return canta = 0 for",
"aux = len(a) if(aux==0): print(0) return canta = 0 for i in a:",
"newb.append((b[i],i)) a,b = newa,newb aux = len(a) if(aux==0): print(0) return canta = 0",
"newa = [] newb = [] for i in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i))",
"if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0] else: print(len(a)//2) lastA,lastB = -1,-1 for i",
"print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0] else: print(len(a)//2) lastA,lastB = -1,-1 for i in range(aux):",
"SI = lambda : input() from collections import Counter n = int(input()) a",
"if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0] else: print(len(a)//2) lastA,lastB = -1,-1",
"print(-1) return xa = d[a]//2 newa = [] newb = [] for i",
"= b[0],a[0] else: print(len(a)//2) lastA,lastB = -1,-1 for i in range(aux): if(a[i][0]=='a'): if(lastA==-1):",
"input() from collections import Counter n = int(input()) a = SI() b =",
"= newa,newb aux = len(a) if(aux==0): print(0) return canta = 0 for i",
"range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(lastA+1,a[i][1]+1) lastA=-1 else: if(lastB==-1): lastB=a[i][1] else: print(lastB+1,a[i][1]+1) lastB=-1",
"SI() b = SI() def solve(n,a,b): d = Counter(a)+Counter(b) for i in d:",
"= Counter(a)+Counter(b) for i in d: if(d[i]&1): print(-1) return xa = d[a]//2 newa",
"= lambda : input() from collections import Counter n = int(input()) a =",
"range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb aux = len(a) if(aux==0): print(0) return",
"a: if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0] else: print(len(a)//2) lastA,lastB =",
"d[a]//2 newa = [] newb = [] for i in range(n): if(a[i]!=b[i]): newa.append((a[i],i))",
"newb = [] for i in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb",
"lambda : input() from collections import Counter n = int(input()) a = SI()",
"if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb aux = len(a) if(aux==0): print(0) return canta",
"= int(input()) a = SI() b = SI() def solve(n,a,b): d = Counter(a)+Counter(b)",
"b = SI() def solve(n,a,b): d = Counter(a)+Counter(b) for i in d: if(d[i]&1):",
"i in d: if(d[i]&1): print(-1) return xa = d[a]//2 newa = [] newb",
"a[0],b[0] = b[0],a[0] else: print(len(a)//2) lastA,lastB = -1,-1 for i in range(aux): if(a[i][0]=='a'):",
"xa = d[a]//2 newa = [] newb = [] for i in range(n):",
"= [] newb = [] for i in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b",
": input() from collections import Counter n = int(input()) a = SI() b",
"[] newb = [] for i in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b =",
"in a: if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0] else: print(len(a)//2) lastA,lastB",
"i in a: if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0] else: print(len(a)//2)",
"lastA,lastB = -1,-1 for i in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(lastA+1,a[i][1]+1) lastA=-1",
"def solve(n,a,b): d = Counter(a)+Counter(b) for i in d: if(d[i]&1): print(-1) return xa",
"canta = 0 for i in a: if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0]",
"newa,newb aux = len(a) if(aux==0): print(0) return canta = 0 for i in",
"for i in a: if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0] else:",
"-1,-1 for i in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(lastA+1,a[i][1]+1) lastA=-1 else: if(lastB==-1):",
"Counter n = int(input()) a = SI() b = SI() def solve(n,a,b): d",
"if(d[i]&1): print(-1) return xa = d[a]//2 newa = [] newb = [] for",
"print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0] else: print(len(a)//2) lastA,lastB = -1,-1 for i in",
"in d: if(d[i]&1): print(-1) return xa = d[a]//2 newa = [] newb =",
"n = int(input()) a = SI() b = SI() def solve(n,a,b): d =",
"in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb aux = len(a) if(aux==0): print(0)",
"d = Counter(a)+Counter(b) for i in d: if(d[i]&1): print(-1) return xa = d[a]//2",
"collections import Counter n = int(input()) a = SI() b = SI() def",
"print(0) return canta = 0 for i in a: if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1)",
"canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0] else: print(len(a)//2) lastA,lastB = -1,-1 for",
"= 0 for i in a: if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] =",
"= d[a]//2 newa = [] newb = [] for i in range(n): if(a[i]!=b[i]):",
"= len(a) if(aux==0): print(0) return canta = 0 for i in a: if(i[0]=='a'):",
"for i in d: if(d[i]&1): print(-1) return xa = d[a]//2 newa = []",
"for i in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb aux = len(a)",
"from collections import Counter n = int(input()) a = SI() b = SI()",
"if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(lastA+1,a[i][1]+1) lastA=-1 else: if(lastB==-1): lastB=a[i][1] else: print(lastB+1,a[i][1]+1) lastB=-1 solve(n,a,b)",
"return xa = d[a]//2 newa = [] newb = [] for i in",
"= -1,-1 for i in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(lastA+1,a[i][1]+1) lastA=-1 else:",
"a = SI() b = SI() def solve(n,a,b): d = Counter(a)+Counter(b) for i",
"for i in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(lastA+1,a[i][1]+1) lastA=-1 else: if(lastB==-1): lastB=a[i][1]",
"[] for i in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb aux =",
"if(aux==0): print(0) return canta = 0 for i in a: if(i[0]=='a'): canta+=1 if(canta&1):",
"import Counter n = int(input()) a = SI() b = SI() def solve(n,a,b):",
"= SI() def solve(n,a,b): d = Counter(a)+Counter(b) for i in d: if(d[i]&1): print(-1)",
"solve(n,a,b): d = Counter(a)+Counter(b) for i in d: if(d[i]&1): print(-1) return xa =",
"d: if(d[i]&1): print(-1) return xa = d[a]//2 newa = [] newb = []",
"else: print(len(a)//2) lastA,lastB = -1,-1 for i in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else:",
"SI() def solve(n,a,b): d = Counter(a)+Counter(b) for i in d: if(d[i]&1): print(-1) return",
"0 for i in a: if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1) a[0],b[0] = b[0],a[0]",
"i in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(lastA+1,a[i][1]+1) lastA=-1 else: if(lastB==-1): lastB=a[i][1] else:",
"return canta = 0 for i in a: if(i[0]=='a'): canta+=1 if(canta&1): print(len(a)//2+1) print(a[0][1]+1,a[0][1]+1)",
"= SI() b = SI() def solve(n,a,b): d = Counter(a)+Counter(b) for i in",
"b[0],a[0] else: print(len(a)//2) lastA,lastB = -1,-1 for i in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1]",
"in range(aux): if(a[i][0]=='a'): if(lastA==-1): lastA=a[i][1] else: print(lastA+1,a[i][1]+1) lastA=-1 else: if(lastB==-1): lastB=a[i][1] else: print(lastB+1,a[i][1]+1)",
"i in range(n): if(a[i]!=b[i]): newa.append((a[i],i)) newb.append((b[i],i)) a,b = newa,newb aux = len(a) if(aux==0):"
] |
[
"#datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific'))",
"- birthday print(days_since_birth) tdelta = datetime.timedelta(days=10) print(today + tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d)",
"<gh_stars>0 import datetime import pytz today = datetime.date.today() print(today) birthday = datetime.date(1994,12,19) print(birthday)",
"print(timezones) #taghyire format str format time print(datetime_pacific.strftime('%B %d, %Y')) #taghyire format str parse",
"pytz.all_timezones: print(timezones) #taghyire format str format time print(datetime_pacific.strftime('%B %d, %Y')) #taghyire format str",
"import datetime import pytz today = datetime.date.today() print(today) birthday = datetime.date(1994,12,19) print(birthday) days_since_birth",
"datetime.date(1994,12,19) print(birthday) days_since_birth = today - birthday print(days_since_birth) tdelta = datetime.timedelta(days=10) print(today +",
"hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in pytz.all_timezones: print(timezones) #taghyire format",
"datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in pytz.all_timezones: print(timezones) #taghyire format str",
"= datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in pytz.all_timezones: print(timezones) #taghyire format str format time print(datetime_pacific.strftime('%B",
"= today - birthday print(days_since_birth) tdelta = datetime.timedelta(days=10) print(today + tdelta) print(today.month) print(today.weekday())",
"datetime.timedelta(days=10) print(today + tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10)",
"format str format time print(datetime_pacific.strftime('%B %d, %Y')) #taghyire format str parse time print(datetime.datetime.strptime('march",
"print(today + tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now()",
"%d, %Y')) #taghyire format str parse time print(datetime.datetime.strptime('march 09,2019','%B %d,%Y')) print(repr(datetime.datetime.strptime('march 09,2019','%B %d,%Y')))",
"= datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in",
"= datetime.timedelta(days=10) print(today + tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta =",
"print(today) birthday = datetime.date(1994,12,19) print(birthday) days_since_birth = today - birthday print(days_since_birth) tdelta =",
"pytz today = datetime.date.today() print(today) birthday = datetime.date(1994,12,19) print(birthday) days_since_birth = today -",
"today - birthday print(days_since_birth) tdelta = datetime.timedelta(days=10) print(today + tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15))",
"birthday print(days_since_birth) tdelta = datetime.timedelta(days=10) print(today + tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms)",
"#datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific =",
"#datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for",
"print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific')))",
"hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones",
"datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in pytz.all_timezones: print(timezones) #taghyire format str format time print(datetime_pacific.strftime('%B %d,",
"import pytz today = datetime.date.today() print(today) birthday = datetime.date(1994,12,19) print(birthday) days_since_birth = today",
"print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific",
"today = datetime.date.today() print(today) birthday = datetime.date(1994,12,19) print(birthday) days_since_birth = today - birthday",
"format time print(datetime_pacific.strftime('%B %d, %Y')) #taghyire format str parse time print(datetime.datetime.strptime('march 09,2019','%B %d,%Y'))",
"days_since_birth = today - birthday print(days_since_birth) tdelta = datetime.timedelta(days=10) print(today + tdelta) print(today.month)",
"print(datetime_pacific.strftime('%B %d, %Y')) #taghyire format str parse time print(datetime.datetime.strptime('march 09,2019','%B %d,%Y')) print(repr(datetime.datetime.strptime('march 09,2019','%B",
"for timezones in pytz.all_timezones: print(timezones) #taghyire format str format time print(datetime_pacific.strftime('%B %d, %Y'))",
"birthday = datetime.date(1994,12,19) print(birthday) days_since_birth = today - birthday print(days_since_birth) tdelta = datetime.timedelta(days=10)",
"print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc)",
"tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta)",
"datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in pytz.all_timezones: print(timezones) #taghyire format str format time",
"time print(datetime_pacific.strftime('%B %d, %Y')) #taghyire format str parse time print(datetime.datetime.strptime('march 09,2019','%B %d,%Y')) print(repr(datetime.datetime.strptime('march",
"print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in pytz.all_timezones: print(timezones)",
"timezones in pytz.all_timezones: print(timezones) #taghyire format str format time print(datetime_pacific.strftime('%B %d, %Y')) #taghyire",
"+ hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in pytz.all_timezones: print(timezones) #taghyire",
"datetime import pytz today = datetime.date.today() print(today) birthday = datetime.date(1994,12,19) print(birthday) days_since_birth =",
"= datetime.date(1994,12,19) print(birthday) days_since_birth = today - birthday print(days_since_birth) tdelta = datetime.timedelta(days=10) print(today",
"print(birthday) days_since_birth = today - birthday print(days_since_birth) tdelta = datetime.timedelta(days=10) print(today + tdelta)",
"= datetime.date.today() print(today) birthday = datetime.date(1994,12,19) print(birthday) days_since_birth = today - birthday print(days_since_birth)",
"datetime.timedelta(hours=10) print(datetime.datetime.now() + hour_delta) datetime_today=datetime.datetime.now(tz=pytz.utc) print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in pytz.all_timezones:",
"print(datetime_today.astimezone(pytz.timezone('US/Pacific'))) datetime_pacific = datetime_today.astimezone(pytz.timezone('US/Pacific')) for timezones in pytz.all_timezones: print(timezones) #taghyire format str format",
"+ tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta = datetime.timedelta(hours=10) print(datetime.datetime.now() +",
"print(days_since_birth) tdelta = datetime.timedelta(days=10) print(today + tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms)",
"#taghyire format str format time print(datetime_pacific.strftime('%B %d, %Y')) #taghyire format str parse time",
"datetime.date.today() print(today) birthday = datetime.date(1994,12,19) print(birthday) days_since_birth = today - birthday print(days_since_birth) tdelta",
"in pytz.all_timezones: print(timezones) #taghyire format str format time print(datetime_pacific.strftime('%B %d, %Y')) #taghyire format",
"tdelta = datetime.timedelta(days=10) print(today + tdelta) print(today.month) print(today.weekday()) print(datetime.time(7,2,20,15)) #datetime.date(y,m,d) #datetime.time(h,m,s,ms) #datetime.datetime(y,m,d,h,m,s,ms) hour_delta",
"str format time print(datetime_pacific.strftime('%B %d, %Y')) #taghyire format str parse time print(datetime.datetime.strptime('march 09,2019','%B"
] |
[] |
[
"\"\"\" if 'match_id' in kwargs and kwargs['match_id'] in match_library: return match_library[kwargs['match_id']] match =",
"else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info = MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row",
"display_text async def delete_match(match_id: int) -> None: await matchdb.delete_match(match_id=match_id) if match_id in match_library:",
"int) -> None: await matchdb.delete_match(match_id=match_id) if match_id in match_library: del match_library[match_id] async def",
"of the cawmentator for this match. sheet_id: int The sheetID of the worksheet",
"{0} in close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id)) return await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None) async",
"# noinspection PyIncorrectDocstring async def make_match(*args, register=False, **kwargs) -> Match: \"\"\"Create a Match",
"room for an unregistered match.') return channel_id = match.channel_id channel = server.find_channel(channel_id=channel_id) if",
"async def get_match_from_id(match_id: int) -> Match or None: \"\"\"Get a match object from",
"of all Matches that have associated channels on the server featuring the specified",
"matchdb.delete_match(match_id=match_id) if match_id in match_library: del match_library[match_id] async def make_match_from_raw_db_data(row: list) -> Match:",
"sheet_id: int The sheetID of the worksheet the match was created from, if",
"server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is not None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make the actual",
"new_room async def close_match_room(match: Match) -> None: \"\"\"Close the discord.Channel corresponding to the",
"actual RaceRoom and initialize it match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room) await",
"this match. cawmentator_id: int The DB unique ID of the cawmentator for this",
"= None) -> list: \"\"\" Parameters ---------- racer: NecroUser The racer to find",
"match = await make_match_from_raw_db_data(row=row) if match.suggested_time is None: console.warning('Found match object {} has",
"corresponding MatchRoom for the given Match. Parameters ---------- match: Match The Match to",
"w2=max_r2_len ) if match.suggested_time - utcnow < datetime.timedelta(minutes=0): schedule_text += 'Right now!' else:",
"all match channels from the server. Parameters ---------- log: bool If True, the",
"\\nUpcoming matches: \\n' for match in matches: if len(schedule_text) > 1800: break schedule_text",
"match async def get_match_from_id(match_id: int) -> Match or None: \"\"\"Get a match object",
"[] if racer is not None: raw_data = await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id",
"max_races; otherwise, the match is just repeating max_races.) match_id: int The DB unique",
"---------- racer: NecroUser The racer to find channels for. If None, finds all",
"= Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]),",
"\"\"\" if not match.is_registered: console.warning('Trying to close the room for an unregistered match.')",
"directly; use matchutil.make_match instead, since this needs to interact with the database. Parameters",
"utcnow, punctuate=True)) match_cawmentator = await match.get_cawmentator() if match_cawmentator is not None: display_text +=",
"match channel.') return None # Put the match channel in the matches category",
"**kwargs) -> Match: \"\"\"Create a Match object. There should be no need to",
"deletion. completed_only: bool If True, will only find completed matches. \"\"\" for row",
"and a corresponding MatchRoom for the given Match. Parameters ---------- match: Match The",
"match_channel = server.find_channel(channel_id=channel_id) if channel_id is not None else None # If we",
"to register the match in the database. Returns --------- Match The created match.",
"new_match async def get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches = await get_upcoming_and_current() max_r1_len =",
"match is suggested for. If no tzinfo, UTC is assumed. r1_confirmed: bool Whether",
"import matchdb, racedb from necrobot.util import console, timestr, writechannel, strutil, rtmputil from necrobot.botbase.necrobot",
"Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12],",
"import pytz from necrobot.botbase import server, discordutil from necrobot.database import matchdb, racedb from",
"will register the Match in the database. Returns ------- Optional[MatchRoom] The created room",
"time.'.format(repr(match))) continue if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room = Necrobot().get_bot_channel(channel) if match_room",
"sheet_info = MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row = row[15] new_match = Match( commit_fn=matchdb.write_match,",
"MatchRoom for an unregistered Match ({0}).'.format(match.matchroom_name)) return None # Check to see if",
"int(row[0]) channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) delete_this = True if channel is",
"to unconfirm the match time. r2_unconfirmed: bool Whether the second racer wishes to",
"If None, finds all channeled matches. Returns ------- list[Match] A list of all",
"row[13] is not None else None if channel_id is not None: channel =",
"else: display_text = 'Next match: \\n' for match in match_list: # noinspection PyUnresolvedReferences",
"if racer.member is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make a channel for the",
"------- str The name of the channel. \"\"\" name_prefix = match.matchroom_name cut_length =",
"since this needs to interact with the database. Parameters ---------- racer_1_id: int The",
"channel = server.find_channel(channel_id=channel_id) if channel is not None: match = await make_match_from_raw_db_data(row=row) if",
"racer_id=racer.user_id ) else: raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row in raw_data: channel_id",
"v {r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if match.suggested_time - utcnow",
"match_id = int(row[0]) if match_id in match_library: return match_library[match_id] match_info = MatchInfo( race_info=await",
"Necrobot().get_bot_channel(channel) if match_room is None or not match_room.played_all_races: delete_this = False if delete_this:",
"a log file before deletion. completed_only: bool If True, will only find completed",
"noinspection PyUnresolvedReferences match_channel = await server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions,",
"is None: # Create permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions =",
"ID of the cawmentator for this match. sheet_id: int The sheetID of the",
"= False for channel in server.server.channels: if channel.name.startswith(name_prefix): found = True try: val",
"if match.suggested_time - utcnow < datetime.timedelta(minutes=0): schedule_text += 'Right now!' else: schedule_text +=",
"def get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches = await get_upcoming_and_current() max_r1_len = 0 max_r2_len",
"all Matches that have associated channels on the server featuring the specified racer.",
"str: utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) > 1: display_text = 'Upcoming matches: \\n'",
"first racer. racer_2_id: int The DB user ID of the second racer. max_races:",
"# Check to see if we already have the match channel channel_id =",
"make_match_from_raw_db_data(row=row) if match.suggested_time is None: console.warning('Found match object {} has no suggested time.'.format(repr(match)))",
"len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text = '``` \\nUpcoming matches: \\n' for match",
"matches async def get_matches_with_channels(racer: NecroUser = None) -> list: \"\"\" Parameters ---------- racer:",
"delete_this = False if delete_this: if log: await writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name)",
"if channel.name.startswith(name_prefix): found = True try: val = int(channel.name[cut_length:]) largest_postfix = max(largest_postfix, val)",
"match_library[match_id] async def make_match_from_raw_db_data(row: list) -> Match: match_id = int(row[0]) if match_id in",
"= True if channel is not None: if completed_only: match_room = Necrobot().get_bot_channel(channel) if",
"racer has confirmed the match time. r1_unconfirmed: bool Whether the first racer wishes",
"user ID of the first racer. racer_2_id: int The DB user ID of",
"if len(match_list) > 1: display_text = 'Upcoming matches: \\n' else: display_text = 'Next",
"(If is_best_of is True, then the match is a best of max_races; otherwise,",
"matches. Returns ------- list[Match] A list of all Matches that have associated channels",
"---------- match: Match The match whose info determines the name. Returns ------- str",
"None: match = await make_match_from_raw_db_data(row=row) if match.suggested_time is None: console.warning('Found match object {}",
"racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if row[13] is",
"max_races: int The maximum number of races this match can be. (If is_best_of",
"channels from the server. Parameters ---------- log: bool If True, the channel text",
"await new_match.initialize() match_library[new_match.match_id] = new_match return new_match async def get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow())",
"The match found, if any. \"\"\" if match_id is None: return None if",
"def get_nextrace_displaytext(match_list: list) -> str: utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) > 1: display_text",
"- utcnow, punctuate=True)) match_cawmentator = await match.get_cawmentator() if match_cawmentator is not None: display_text",
"no need to call this directly; use matchutil.make_match instead, since this needs to",
"' Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) # display_text += ' RTMP: {}",
"if channel is not None: if completed_only: match_room = Necrobot().get_bot_channel(channel) if match_room is",
"the room for an unregistered match.') return channel_id = match.channel_id channel = server.find_channel(channel_id=channel_id)",
"pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) > 1: display_text = 'Upcoming matches: \\n' else: display_text =",
"\"\"\"Delete all match channels from the server. Parameters ---------- log: bool If True,",
"register: bool Whether to register the match in the database. Returns --------- Match",
"if match_channel is None: console.warning('Failed to make a match channel.') return None #",
"match = Match(*args, commit_fn=matchdb.write_match, **kwargs) await match.initialize() if register: await match.commit() match_library[match.match_id] =",
"gsheet_info=sheet_info ) await new_match.initialize() match_library[new_match.match_id] = new_match return new_match async def get_schedule_infotext(): utcnow",
"this directly; use matchutil.make_match instead, since this needs to interact with the database.",
"match_library[match_id] match_info = MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1] is not None else RaceInfo(),",
"match.match_id)) return await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None) async def get_nextrace_displaytext(match_list: list) -> str:",
"no tzinfo, UTC is assumed. r1_confirmed: bool Whether the first racer has confirmed",
"+= ' Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) # display_text += ' RTMP:",
"for this match. sheet_id: int The sheetID of the worksheet the match was",
"if not match.is_registered: if register: await match.commit() else: console.warning('Tried to make a MatchRoom",
"datetime import discord import pytz from necrobot.botbase import server, discordutil from necrobot.database import",
"unregistered match.') return channel_id = match.channel_id channel = server.find_channel(channel_id=channel_id) if channel is None:",
"None: # Create permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions = []",
"the match channel in the matches category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is",
"not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make a channel for the room # noinspection",
"async def delete_match(match_id: int) -> None: await matchdb.delete_match(match_id=match_id) if match_id in match_library: del",
"= int(row[13]) channel = server.find_channel(channel_id=channel_id) delete_this = True if channel is not None:",
"is not None: match = await make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found Match with channel",
"pass return name_prefix if not found else '{0}-{1}'.format(name_prefix, largest_postfix + 1) async def",
"in the matches category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is not None: await",
"has confirmed the match time. r1_unconfirmed: bool Whether the first racer wishes to",
"completed_only: bool If True, will only find completed matches. \"\"\" for row in",
"Check to see if we already have the match channel channel_id = match.channel_id",
"if log: await writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) ) await server.client.delete_channel(channel) if delete_this:",
"a corresponding MatchRoom for the given Match. Parameters ---------- match: Match The Match",
"all channeled matches. Returns ------- list[Match] A list of all Matches that have",
"bool Whether the second racer has confirmed the match time. r1_unconfirmed: bool Whether",
"display_text = 'Upcoming matches: \\n' else: display_text = 'Next match: \\n' for match",
"# Create permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions = [] for",
"if completed_only: match_room = Necrobot().get_bot_channel(channel) if match_room is None or not match_room.played_all_races: delete_this",
"time. match_info: MatchInfo The types of races to be run in this match.",
"match. \"\"\" if 'match_id' in kwargs and kwargs['match_id'] in match_library: return match_library[kwargs['match_id']] match",
"= server.find_channel(channel_id=channel_id) if channel is None: console.warning('Coudn\\'t find channel with id {0} in",
"now!' else: schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text += '\\n' schedule_text += '```' return schedule_text",
"in match_list: # noinspection PyUnresolvedReferences display_text += '\\N{BULLET} **{0}** - **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name)",
"sheet_info.wks_id = row[14] sheet_info.row = row[15] new_match = Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]),",
"int The DB unique ID of the cawmentator for this match. sheet_id: int",
"name corresponding to the match. Parameters ---------- match: Match The match whose info",
"= await server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if match_channel",
"in kwargs and kwargs['match_id'] in match_library: return match_library[kwargs['match_id']] match = Match(*args, commit_fn=matchdb.write_match, **kwargs)",
"# If we couldn't find the channel or it didn't exist, make a",
"bool If True, will register the Match in the database. Returns ------- Optional[MatchRoom]",
"assumed. r1_confirmed: bool Whether the first racer has confirmed the match time. r2_confirmed:",
"ValueError: pass return name_prefix if not found else '{0}-{1}'.format(name_prefix, largest_postfix + 1) async",
"kwargs['match_id'] in match_library: return match_library[kwargs['match_id']] match = Match(*args, commit_fn=matchdb.write_match, **kwargs) await match.initialize() if",
"in server.server.channels: if channel.name.startswith(name_prefix): found = True try: val = int(channel.name[cut_length:]) largest_postfix =",
"'match_id' in kwargs and kwargs['match_id'] in match_library: return match_library[kwargs['match_id']] match = Match(*args, commit_fn=matchdb.write_match,",
"writechannel, strutil, rtmputil from necrobot.botbase.necrobot import Necrobot from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from necrobot.match.match",
"channel.'.format(channel_id)) return matches async def delete_all_match_channels(log=False, completed_only=False) -> None: \"\"\"Delete all match channels",
"get_matches_with_channels(racer: NecroUser = None) -> list: \"\"\" Parameters ---------- racer: NecroUser The racer",
"cawmentator_id=row[12], channel_id=int(row[13]) if row[13] is not None else None, gsheet_info=sheet_info ) await new_match.initialize()",
"The DB unique ID of the cawmentator for this match. sheet_id: int The",
"or it didn't exist, make a new one if match_channel is None: #",
"discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions = [] for racer in match.racers: if racer.member",
"# Put the match channel in the matches category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if",
"new_match return new_match async def get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches = await get_upcoming_and_current()",
"None) async def make_match_room(match: Match, register=False) -> MatchRoom or None: \"\"\"Create a discord.Channel",
"match_library: del match_library[match_id] async def make_match_from_raw_db_data(row: list) -> Match: match_id = int(row[0]) if",
"{r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if match.suggested_time - utcnow <",
"to the Match, if any. Parameters ---------- match: Match The Match to close",
"async def get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches = await get_upcoming_and_current() max_r1_len = 0",
"not None else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info = MatchGSheetInfo() sheet_info.wks_id =",
"necrobot.database import matchdb, racedb from necrobot.util import console, timestr, writechannel, strutil, rtmputil from",
"if racer is not None: raw_data = await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id )",
"close_match_room(match: Match) -> None: \"\"\"Close the discord.Channel corresponding to the Match, if any.",
"True try: val = int(channel.name[cut_length:]) largest_postfix = max(largest_postfix, val) except ValueError: pass return",
"channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) ) await server.client.delete_channel(channel) if delete_this: await matchdb.register_match_channel(match_id, None) async def",
"races to be run in this match. cawmentator_id: int The DB unique ID",
"races this match can be. (If is_best_of is True, then the match is",
"match.suggested_time is None: console.warning('Found match object {} has no suggested time.'.format(repr(match))) continue if",
"len(strutil.tickless(match.racer_2.display_name))) schedule_text = '``` \\nUpcoming matches: \\n' for match in matches: if len(schedule_text)",
"The DB user ID of the second racer. max_races: int The maximum number",
"None and match.racer_2.twitch_name is not None: display_text += ' Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name,",
"del match_library[match_id] async def make_match_from_raw_db_data(row: list) -> Match: match_id = int(row[0]) if match_id",
"elif match.racer_1.twitch_name is not None and match.racer_2.twitch_name is not None: display_text += '",
"and kwargs['match_id'] in match_library: return match_library[kwargs['match_id']] match = Match(*args, commit_fn=matchdb.write_match, **kwargs) await match.initialize()",
"match_room = Necrobot().get_bot_channel(channel) if match_room is None or not match_room.played_all_races: delete_this = False",
"match_room.played_all_races: delete_this = False if delete_this: if log: await writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id,",
"match. cawmentator_id: int The DB unique ID of the cawmentator for this match.",
"None: display_text += '\\n' continue display_text += ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True))",
"r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if row[13] is not None else None, gsheet_info=sheet_info",
"+= '\\N{BULLET} **{0}** - **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time is None: display_text +=",
"is not None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make the actual RaceRoom and initialize",
"is not None: channel = server.find_channel(channel_id=channel_id) if channel is not None: match =",
"racer: NecroUser The racer to find channels for. If None, finds all channeled",
"> 1800: break schedule_text += '{r1:>{w1}} v {r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name),",
"= Match(*args, commit_fn=matchdb.write_match, **kwargs) await match.initialize() if register: await match.commit() match_library[match.match_id] = match",
"match_id: int The databse ID of the match. Returns ------- Optional[Match] The match",
"else None if channel_id is not None: channel = server.find_channel(channel_id=channel_id) if channel is",
"not None and await match_room.during_races(): matches.append(match) return matches async def get_matches_with_channels(racer: NecroUser =",
"match can be. (If is_best_of is True, then the match is a best",
"the given Match. Parameters ---------- match: Match The Match to create a room",
"necrobot.botbase import server, discordutil from necrobot.database import matchdb, racedb from necrobot.util import console,",
"server, discordutil from necrobot.database import matchdb, racedb from necrobot.util import console, timestr, writechannel,",
"len(match_list) > 1: display_text = 'Upcoming matches: \\n' else: display_text = 'Next match:",
"async def make_match_from_raw_db_data(row: list) -> Match: match_id = int(row[0]) if match_id in match_library:",
"number of races this match can be. (If is_best_of is True, then the",
"NecroUser The racer to find channels for. If None, finds all channeled matches.",
"bool If True, the channel text will be written to a log file",
"found = False for channel in server.server.channels: if channel.name.startswith(name_prefix): found = True try:",
"repeating max_races.) match_id: int The DB unique ID of this match. suggested_time: datetime.datetime",
": '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if match.suggested_time - utcnow < datetime.timedelta(minutes=0):",
"int(row[13]) channel = server.find_channel(channel_id=channel_id) if channel is not None: match = await make_match_from_raw_db_data(row=row)",
"match time. r1_unconfirmed: bool Whether the first racer wishes to unconfirm the match",
"= MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row = row[15] new_match = Match( commit_fn=matchdb.write_match, match_id=match_id,",
"necrobot.race.raceinfo import RaceInfo from necrobot.user.necrouser import NecroUser from necrobot.config import Config match_library =",
"specified racer. \"\"\" matches = [] if racer is not None: raw_data =",
"if match_room is None or not match_room.played_all_races: delete_this = False if delete_this: if",
"match.suggested_time - utcnow < datetime.timedelta(minutes=0): schedule_text += 'Right now!' else: schedule_text += timestr.str_full_24h(match.suggested_time)",
"the second racer wishes to unconfirm the match time. match_info: MatchInfo The types",
"row[13] is not None else None, gsheet_info=sheet_info ) await new_match.initialize() match_library[new_match.match_id] = new_match",
"------- Optional[Match] The match found, if any. \"\"\" if match_id is None: return",
"return match async def get_match_from_id(match_id: int) -> Match or None: \"\"\"Get a match",
"int) -> Match or None: \"\"\"Get a match object from its DB unique",
"= await make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found Match with channel {0}, but couldn\\'t find",
"category=match_channel_category) # Make the actual RaceRoom and initialize it match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel,",
"make_match_from_raw_db_data(row: list) -> Match: match_id = int(row[0]) if match_id in match_library: return match_library[match_id]",
"channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) if channel is not None: match =",
"int(row[13]) if row[13] is not None else None if channel_id is not None:",
"Match The Match to close the channel for. \"\"\" if not match.is_registered: console.warning('Trying",
"def get_matches_with_channels(racer: NecroUser = None) -> list: \"\"\" Parameters ---------- racer: NecroUser The",
"Matches that have associated channels on the server featuring the specified racer. \"\"\"",
"matches. \"\"\" for row in await matchdb.get_channeled_matches_raw_data(): match_id = int(row[0]) channel_id = int(row[13])",
"channel_id = match.channel_id channel = server.find_channel(channel_id=channel_id) if channel is None: console.warning('Coudn\\'t find channel",
"if channel is not None: match = await make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found Match",
"= server.find_channel(channel_id=channel_id) if channel_id is not None else None # If we couldn't",
"client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) ) await server.client.delete_channel(channel) if delete_this: await matchdb.register_match_channel(match_id, None) async",
"is not None and match.racer_2.twitch_name is not None: display_text += ' Kadgar: {}",
"associated channels on the server featuring the specified racer. \"\"\" matches = []",
"one if match_channel is None: # Create permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read =",
"unconfirm the match time. match_info: MatchInfo The types of races to be run",
"list: \"\"\" Returns ------- list[Match] A list of all upcoming and ongoing matches,",
"the match. Parameters ---------- match: Match The match whose info determines the name.",
"commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13])",
"didn't exist, make a new one if match_channel is None: # Create permissions",
"in close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id)) return await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None) async def",
"+ 1 largest_postfix = 1 found = False for channel in server.server.channels: if",
"r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if row[13] is not None else None,",
"return matches async def get_matches_with_channels(racer: NecroUser = None) -> list: \"\"\" Parameters ----------",
"match = await make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found Match with channel {0}, but couldn\\'t",
"MatchRoom from necrobot.race.raceinfo import RaceInfo from necrobot.user.necrouser import NecroUser from necrobot.config import Config",
"all upcoming and ongoing matches, in order. \"\"\" matches = [] for row",
"-> None: \"\"\"Delete all match channels from the server. Parameters ---------- log: bool",
"channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) delete_this = True if channel is not",
"# Make a channel for the room # noinspection PyUnresolvedReferences match_channel = await",
"match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if row[13]",
"\"\"\" for row in await matchdb.get_channeled_matches_raw_data(): match_id = int(row[0]) channel_id = int(row[13]) channel",
"matches: max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text = '``` \\nUpcoming",
"time. r1_unconfirmed: bool Whether the first racer wishes to unconfirm the match time.",
"match_id is None: return None if match_id in match_library: return match_library[match_id] raw_data =",
"= await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id ) else: raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False)",
"from necrobot.database import matchdb, racedb from necrobot.util import console, timestr, writechannel, strutil, rtmputil",
"None: return None if match_id in match_library: return match_library[match_id] raw_data = await matchdb.get_raw_match_data(match_id)",
"server.find_channel(channel_id=channel_id) if channel_id is not None else None # If we couldn't find",
"- utcnow < datetime.timedelta(minutes=0): schedule_text += 'Right now!' else: schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text",
"match: Match The Match to close the channel for. \"\"\" if not match.is_registered:",
"for the given Match. Parameters ---------- match: Match The Match to create a",
"completed matches. \"\"\" for row in await matchdb.get_channeled_matches_raw_data(): match_id = int(row[0]) channel_id =",
"to the match. Parameters ---------- match: Match The match whose info determines the",
"exist, make a new one if match_channel is None: # Create permissions deny_read",
"r1_confirmed: bool Whether the first racer has confirmed the match time. r2_confirmed: bool",
"the first racer has confirmed the match time. r2_confirmed: bool Whether the second",
"def make_match(*args, register=False, **kwargs) -> Match: \"\"\"Create a Match object. There should be",
"racer_2_id: int The DB user ID of the second racer. max_races: int The",
"console.warning('Found match object {} has no suggested time.'.format(repr(match))) continue if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()):",
"its DB unique ID. Parameters ---------- match_id: int The databse ID of the",
"matches.append(match) else: console.warning('Found Match with channel {0}, but couldn\\'t find this channel.'.format(channel_id)) return",
"Match The created match. \"\"\" if 'match_id' in kwargs and kwargs['match_id'] in match_library:",
"is None or not match_room.played_all_races: delete_this = False if delete_this: if log: await",
"to call this directly; use matchutil.make_match instead, since this needs to interact with",
"raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row in raw_data: channel_id = int(row[13]) channel",
"databse ID of the match. Returns ------- Optional[Match] The match found, if any.",
"object {} has no suggested time.'.format(repr(match))) continue if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else:",
"if match_room is not None and await match_room.during_races(): matches.append(match) return matches async def",
"'(match_id={1}).'.format(channel_id, match.match_id)) return await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None) async def get_nextrace_displaytext(match_list: list) ->",
"return None # Put the match channel in the matches category match_channel_category =",
"delete_this: await matchdb.register_match_channel(match_id, None) async def make_match_room(match: Match, register=False) -> MatchRoom or None:",
"punctuate=True)) match_cawmentator = await match.get_cawmentator() if match_cawmentator is not None: display_text += '",
"None and await match_room.during_races(): matches.append(match) return matches async def get_matches_with_channels(racer: NecroUser = None)",
"ID of this match. suggested_time: datetime.datetime The time the match is suggested for.",
"channel = server.find_channel(channel_id=channel_id) delete_this = True if channel is not None: if completed_only:",
"for. If None, finds all channeled matches. Returns ------- list[Match] A list of",
"match.suggested_time is None: display_text += '\\n' continue display_text += ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time -",
"match_room = Necrobot().get_bot_channel(channel) if match_room is not None and await match_room.during_races(): matches.append(match) return",
"None # Check to see if we already have the match channel channel_id",
"overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if match_channel is None: console.warning('Failed to make a",
"{0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True)) match_cawmentator = await match.get_cawmentator() if match_cawmentator is not",
"database. Returns --------- Match The created match. \"\"\" if 'match_id' in kwargs and",
"of this match. suggested_time: datetime.datetime The time the match is suggested for. If",
") await new_match.initialize() match_library[new_match.match_id] = new_match return new_match async def get_schedule_infotext(): utcnow =",
"console, timestr, writechannel, strutil, rtmputil from necrobot.botbase.necrobot import Necrobot from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo",
"first racer wishes to unconfirm the match time. r2_unconfirmed: bool Whether the second",
"Whether the first racer wishes to unconfirm the match time. r2_unconfirmed: bool Whether",
"finds all channeled matches. Returns ------- list[Match] A list of all Matches that",
"category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is not None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) #",
"unique ID. Parameters ---------- match_id: int The databse ID of the match. Returns",
"Match: \"\"\"Create a Match object. There should be no need to call this",
"\"\"\" matches = [] for row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id = int(row[13])",
"largest_postfix = max(largest_postfix, val) except ValueError: pass return name_prefix if not found else",
"register: await match.commit() match_library[match.match_id] = match return match async def get_match_from_id(match_id: int) ->",
"necrobot.match.matchinfo import MatchInfo from necrobot.match.matchroom import MatchRoom from necrobot.race.raceinfo import RaceInfo from necrobot.user.necrouser",
"if 'match_id' in kwargs and kwargs['match_id'] in match_library: return match_library[kwargs['match_id']] match = Match(*args,",
"= discord.PermissionOverwrite(read_messages=True) racer_permissions = [] for racer in match.racers: if racer.member is not",
"the match time. match_info: MatchInfo The types of races to be run in",
"has no suggested time.'.format(repr(match))) continue if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room =",
"the first racer wishes to unconfirm the match time. r2_unconfirmed: bool Whether the",
"for row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id = int(row[13]) if row[13] is not",
"bool Whether the second racer wishes to unconfirm the match time. match_info: MatchInfo",
"given Match. Parameters ---------- match: Match The Match to create a room for.",
"in match_library: return match_library[kwargs['match_id']] match = Match(*args, commit_fn=matchdb.write_match, **kwargs) await match.initialize() if register:",
"worksheet the match was created from, if any. register: bool Whether to register",
"new one if match_channel is None: # Create permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read",
"*racer_permissions, type=discord.ChannelType.text) if match_channel is None: console.warning('Failed to make a match channel.') return",
"str: \"\"\"Get a new unique channel name corresponding to the match. Parameters ----------",
"server.find_channel(channel_id=channel_id) delete_this = True if channel is not None: if completed_only: match_room =",
"get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if match_channel is None: console.warning('Failed to",
"corresponding to the match. Parameters ---------- match: Match The match whose info determines",
"False if delete_this: if log: await writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) ) await",
"raw_data is not None: return await make_match_from_raw_db_data(raw_data) else: return None def get_matchroom_name(match: Match)",
"is None: console.warning('Found match object {} has no suggested time.'.format(repr(match))) continue if match.suggested_time",
"from necrobot.match.matchroom import MatchRoom from necrobot.race.raceinfo import RaceInfo from necrobot.user.necrouser import NecroUser from",
"max_races.) match_id: int The DB unique ID of this match. suggested_time: datetime.datetime The",
"= False if delete_this: if log: await writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) )",
"r2_confirmed: bool Whether the second racer has confirmed the match time. r1_unconfirmed: bool",
"if match_id in match_library: return match_library[match_id] match_info = MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1]",
"MatchRoom for the given Match. Parameters ---------- match: Match The Match to create",
"channel with id {0} in close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id)) return await Necrobot().unregister_bot_channel(channel) await",
"' RTMP: {} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # ) display_text += '\\nFull schedule:",
"{} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) # display_text += ' RTMP: {} \\n'.format( #",
"Create permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions = [] for racer",
"match_id in match_library: del match_library[match_id] async def make_match_from_raw_db_data(row: list) -> Match: match_id =",
"import NecroUser from necrobot.config import Config match_library = {} # noinspection PyIncorrectDocstring async",
"get_match_from_id(match_id: int) -> Match or None: \"\"\"Get a match object from its DB",
"-> None: await matchdb.delete_match(match_id=match_id) if match_id in match_library: del match_library[match_id] async def make_match_from_raw_db_data(row:",
"def get_match_from_id(match_id: int) -> Match or None: \"\"\"Get a match object from its",
"commit_fn=matchdb.write_match, **kwargs) await match.initialize() if register: await match.commit() match_library[match.match_id] = match return match",
"use matchutil.make_match instead, since this needs to interact with the database. Parameters ----------",
"[] for racer in match.racers: if racer.member is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) #",
"run in this match. cawmentator_id: int The DB unique ID of the cawmentator",
"sheetID of the worksheet the match was created from, if any. register: bool",
"name of the channel. \"\"\" name_prefix = match.matchroom_name cut_length = len(name_prefix) + 1",
"is None: display_text += '\\n' continue display_text += ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow,",
"see the match is registered if not match.is_registered: if register: await match.commit() else:",
"race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1] is not None else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) )",
"None else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info = MatchGSheetInfo() sheet_info.wks_id = row[14]",
"match object {} has no suggested time.'.format(repr(match))) continue if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match)",
"list: \"\"\" Parameters ---------- racer: NecroUser The racer to find channels for. If",
"'\\n' continue display_text += ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True)) match_cawmentator = await",
"NecroUser from necrobot.config import Config match_library = {} # noinspection PyIncorrectDocstring async def",
"if register: await match.commit() match_library[match.match_id] = match return match async def get_match_from_id(match_id: int)",
"necrobot.match.matchroom import MatchRoom from necrobot.race.raceinfo import RaceInfo from necrobot.user.necrouser import NecroUser from necrobot.config",
"\"\"\" matches = [] if racer is not None: raw_data = await matchdb.get_channeled_matches_raw_data(",
"upcoming and ongoing matches, in order. \"\"\" matches = [] for row in",
"noinspection PyUnresolvedReferences display_text += '\\N{BULLET} **{0}** - **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time is",
"file before deletion. completed_only: bool If True, will only find completed matches. \"\"\"",
"of the match. Returns ------- Optional[Match] The match found, if any. \"\"\" if",
"val) except ValueError: pass return name_prefix if not found else '{0}-{1}'.format(name_prefix, largest_postfix +",
"is not None: raw_data = await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id ) else: raw_data",
"kwargs and kwargs['match_id'] in match_library: return match_library[kwargs['match_id']] match = Match(*args, commit_fn=matchdb.write_match, **kwargs) await",
"match is a best of max_races; otherwise, the match is just repeating max_races.)",
"get_matchroom_name(match: Match) -> str: \"\"\"Get a new unique channel name corresponding to the",
"------- list[Match] A list of all Matches that have associated channels on the",
"of the first racer. racer_2_id: int The DB user ID of the second",
"is None: console.warning('Coudn\\'t find channel with id {0} in close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id))",
"max_r1_len = 0 max_r2_len = 0 for match in matches: max_r1_len = max(max_r1_len,",
"int(row[13]) channel = server.find_channel(channel_id=channel_id) delete_this = True if channel is not None: if",
"+= ' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is not None and match.racer_2.twitch_name is",
"unique channel name corresponding to the match. Parameters ---------- match: Match The match",
"register=False) -> MatchRoom or None: \"\"\"Create a discord.Channel and a corresponding MatchRoom for",
"the room # noinspection PyUnresolvedReferences match_channel = await server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read),",
"a best of max_races; otherwise, the match is just repeating max_races.) match_id: int",
"this match can be. (If is_best_of is True, then the match is a",
"channel_id is not None else None # If we couldn't find the channel",
"pytz.utc.localize(datetime.datetime.utcnow()) matches = await get_upcoming_and_current() max_r1_len = 0 max_r2_len = 0 for match",
"the discord.Channel corresponding to the Match, if any. Parameters ---------- match: Match The",
"---------- log: bool If True, the channel text will be written to a",
"True, will register the Match in the database. Returns ------- Optional[MatchRoom] The created",
"match.racer_2.twitch_name is not None: display_text += ' Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) )",
"delete_this = True if channel is not None: if completed_only: match_room = Necrobot().get_bot_channel(channel)",
"{0}, but couldn\\'t find this channel.'.format(channel_id)) return matches async def delete_all_match_channels(log=False, completed_only=False) ->",
"else None # If we couldn't find the channel or it didn't exist,",
"from necrobot.user.necrouser import NecroUser from necrobot.config import Config match_library = {} # noinspection",
"channel_id=int(row[13]) if row[13] is not None else None, gsheet_info=sheet_info ) await new_match.initialize() match_library[new_match.match_id]",
"is_best_of is True, then the match is a best of max_races; otherwise, the",
"match time. match_info: MatchInfo The types of races to be run in this",
"necrobot.match.match import Match from necrobot.match.matchinfo import MatchInfo from necrobot.match.matchroom import MatchRoom from necrobot.race.raceinfo",
"= await get_upcoming_and_current() max_r1_len = 0 max_r2_len = 0 for match in matches:",
"= Necrobot().get_bot_channel(channel) if match_room is not None and await match_room.during_races(): matches.append(match) return matches",
"just repeating max_races.) match_id: int The DB unique ID of this match. suggested_time:",
"await match.get_cawmentator() if match_cawmentator is not None: display_text += ' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name)",
"not match.is_registered: console.warning('Trying to close the room for an unregistered match.') return channel_id",
"= server.find_channel(channel_id=channel_id) if channel is not None: match = await make_match_from_raw_db_data(row=row) matches.append(match) else:",
"None: raw_data = await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id ) else: raw_data = await",
"discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make the actual RaceRoom and initialize it match.set_channel_id(int(match_channel.id)) new_room =",
"the match. Returns ------- Optional[Match] The match found, if any. \"\"\" if match_id",
"None else None if channel_id is not None: channel = server.find_channel(channel_id=channel_id) if channel",
"largest_postfix = 1 found = False for channel in server.server.channels: if channel.name.startswith(name_prefix): found",
"await get_upcoming_and_current() max_r1_len = 0 max_r2_len = 0 for match in matches: max_r1_len",
"log file before deletion. completed_only: bool If True, will only find completed matches.",
"id {0} in close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id)) return await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None)",
"= match.channel_id channel = server.find_channel(channel_id=channel_id) if channel is None: console.warning('Coudn\\'t find channel with",
"match.initialize() if register: await match.commit() match_library[match.match_id] = match return match async def get_match_from_id(match_id:",
"time. r2_confirmed: bool Whether the second racer has confirmed the match time. r1_unconfirmed:",
"object. \"\"\" # Check to see the match is registered if not match.is_registered:",
"any. \"\"\" if match_id is None: return None if match_id in match_library: return",
"the actual RaceRoom and initialize it match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room)",
"await matchdb.delete_match(match_id=match_id) if match_id in match_library: del match_library[match_id] async def make_match_from_raw_db_data(row: list) ->",
"match_id in match_library: return match_library[match_id] match_info = MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1] is",
"channel or it didn't exist, make a new one if match_channel is None:",
"max(largest_postfix, val) except ValueError: pass return name_prefix if not found else '{0}-{1}'.format(name_prefix, largest_postfix",
"-> Match or None: \"\"\"Get a match object from its DB unique ID.",
"server.find_channel(channel_id=channel_id) if channel is not None: match = await make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found",
"{} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # ) display_text += '\\nFull schedule: <https://condor.host/schedule>' return",
"match_channel is None: console.warning('Failed to make a match channel.') return None # Put",
"Match: match_id = int(row[0]) if match_id in match_library: return match_library[match_id] match_info = MatchInfo(",
"if any. register: bool Whether to register the match in the database. Returns",
"\"\"\"Get a new unique channel name corresponding to the match. Parameters ---------- match:",
"room object. \"\"\" # Check to see the match is registered if not",
"tzinfo, UTC is assumed. r1_confirmed: bool Whether the first racer has confirmed the",
"MatchGSheetInfo from necrobot.match.match import Match from necrobot.match.matchinfo import MatchInfo from necrobot.match.matchroom import MatchRoom",
"else '{0}-{1}'.format(name_prefix, largest_postfix + 1) async def get_upcoming_and_current() -> list: \"\"\" Returns -------",
"RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info = MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row =",
"'Upcoming matches: \\n' else: display_text = 'Next match: \\n' for match in match_list:",
"necrobot.config import Config match_library = {} # noinspection PyIncorrectDocstring async def make_match(*args, register=False,",
"in match.racers: if racer.member is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make a channel",
"A list of all Matches that have associated channels on the server featuring",
"racer. racer_2_id: int The DB user ID of the second racer. max_races: int",
"import MatchInfo from necrobot.match.matchroom import MatchRoom from necrobot.race.raceinfo import RaceInfo from necrobot.user.necrouser import",
"or None: \"\"\"Get a match object from its DB unique ID. Parameters ----------",
"time the match is suggested for. If no tzinfo, UTC is assumed. r1_confirmed:",
"match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time is None: display_text += '\\n' continue display_text += ':",
"The databse ID of the match. Returns ------- Optional[Match] The match found, if",
"matchdb.get_raw_match_data(match_id) if raw_data is not None: return await make_match_from_raw_db_data(raw_data) else: return None def",
"await match_room.during_races(): matches.append(match) return matches async def get_matches_with_channels(racer: NecroUser = None) -> list:",
"match whose info determines the name. Returns ------- str The name of the",
"matches = [] for row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id = int(row[13]) if",
"permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions = [] for racer in match.racers: if racer.member is",
"suggested time.'.format(repr(match))) continue if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room = Necrobot().get_bot_channel(channel) if",
"best of max_races; otherwise, the match is just repeating max_races.) match_id: int The",
"= await make_match_from_raw_db_data(row=row) if match.suggested_time is None: console.warning('Found match object {} has no",
"type=discord.ChannelType.text) if match_channel is None: console.warning('Failed to make a match channel.') return None",
"is not None else None, gsheet_info=sheet_info ) await new_match.initialize() match_library[new_match.match_id] = new_match return",
"matches: \\n' else: display_text = 'Next match: \\n' for match in match_list: #",
"\\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) # display_text += ' RTMP: {} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name,",
"otherwise, the match is just repeating max_races.) match_id: int The DB unique ID",
"= discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions = [] for racer in match.racers: if",
"The Match to close the channel for. \"\"\" if not match.is_registered: console.warning('Trying to",
"channel is not None: match = await make_match_from_raw_db_data(row=row) if match.suggested_time is None: console.warning('Found",
"'{r1:>{w1}} v {r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if match.suggested_time -",
"racer to find channels for. If None, finds all channeled matches. Returns -------",
"discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if match_channel is None: console.warning('Failed to make",
"RaceInfo from necrobot.user.necrouser import NecroUser from necrobot.config import Config match_library = {} #",
"for match in match_list: # noinspection PyUnresolvedReferences display_text += '\\N{BULLET} **{0}** - **{1}**'.format(",
"return match_library[match_id] raw_data = await matchdb.get_raw_match_data(match_id) if raw_data is not None: return await",
"the matches category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is not None: await discordutil.set_channel_category(channel=match_channel,",
"console.warning('Trying to close the room for an unregistered match.') return channel_id = match.channel_id",
") if match.suggested_time - utcnow < datetime.timedelta(minutes=0): schedule_text += 'Right now!' else: schedule_text",
"racer wishes to unconfirm the match time. match_info: MatchInfo The types of races",
"make_match(*args, register=False, **kwargs) -> Match: \"\"\"Create a Match object. There should be no",
"None if channel_id is not None: channel = server.find_channel(channel_id=channel_id) if channel is not",
"1: display_text = 'Upcoming matches: \\n' else: display_text = 'Next match: \\n' for",
"'``` \\nUpcoming matches: \\n' for match in matches: if len(schedule_text) > 1800: break",
"second racer wishes to unconfirm the match time. match_info: MatchInfo The types of",
"None: \"\"\"Create a discord.Channel and a corresponding MatchRoom for the given Match. Parameters",
"= len(name_prefix) + 1 largest_postfix = 1 found = False for channel in",
"match. Parameters ---------- match: Match The match whose info determines the name. Returns",
"created from, if any. register: bool Whether to register the match in the",
"is None: console.warning('Failed to make a match channel.') return None # Put the",
"channel name corresponding to the match. Parameters ---------- match: Match The match whose",
"<http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is not None and match.racer_2.twitch_name is not None: display_text",
"permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions = [] for racer in",
"matchutil.make_match instead, since this needs to interact with the database. Parameters ---------- racer_1_id:",
"bool If True, will only find completed matches. \"\"\" for row in await",
"await make_match_from_raw_db_data(raw_data) else: return None def get_matchroom_name(match: Match) -> str: \"\"\"Get a new",
"display_text += ' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is not None and match.racer_2.twitch_name",
"None: console.warning('Failed to make a match channel.') return None # Put the match",
"strutil, rtmputil from necrobot.botbase.necrobot import Necrobot from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from necrobot.match.match import",
"import RaceInfo from necrobot.user.necrouser import NecroUser from necrobot.config import Config match_library = {}",
"\"\"\" Returns ------- list[Match] A list of all upcoming and ongoing matches, in",
"= int(row[0]) if match_id in match_library: return match_library[match_id] match_info = MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1]))",
"not None: match = await make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found Match with channel {0},",
"import server, discordutil from necrobot.database import matchdb, racedb from necrobot.util import console, timestr,",
"to make a match channel.') return None # Put the match channel in",
"text will be written to a log file before deletion. completed_only: bool If",
"matches: \\n' for match in matches: if len(schedule_text) > 1800: break schedule_text +=",
"schedule_text += '{r1:>{w1}} v {r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if",
"matches async def delete_all_match_channels(log=False, completed_only=False) -> None: \"\"\"Delete all match channels from the",
"= server.find_channel(channel_id=channel_id) if channel is not None: match = await make_match_from_raw_db_data(row=row) if match.suggested_time",
"max_races=int(row[11]) ) sheet_info = MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row = row[15] new_match =",
"match channel channel_id = match.channel_id match_channel = server.find_channel(channel_id=channel_id) if channel_id is not None",
"racer has confirmed the match time. r2_confirmed: bool Whether the second racer has",
"Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None) async def get_nextrace_displaytext(match_list: list) -> str: utcnow = pytz.utc.localize(datetime.datetime.utcnow())",
"\\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is not None and match.racer_2.twitch_name is not None: display_text +=",
"not None: return await make_match_from_raw_db_data(raw_data) else: return None def get_matchroom_name(match: Match) -> str:",
"def make_match_room(match: Match, register=False) -> MatchRoom or None: \"\"\"Create a discord.Channel and a",
"list) -> str: utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) > 1: display_text = 'Upcoming",
"try: val = int(channel.name[cut_length:]) largest_postfix = max(largest_postfix, val) except ValueError: pass return name_prefix",
"= 0 max_r2_len = 0 for match in matches: max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name)))",
"console.warning('Tried to make a MatchRoom for an unregistered Match ({0}).'.format(match.matchroom_name)) return None #",
"import MatchRoom from necrobot.race.raceinfo import RaceInfo from necrobot.user.necrouser import NecroUser from necrobot.config import",
"return await make_match_from_raw_db_data(raw_data) else: return None def get_matchroom_name(match: Match) -> str: \"\"\"Get a",
"= match.matchroom_name cut_length = len(name_prefix) + 1 largest_postfix = 1 found = False",
"this needs to interact with the database. Parameters ---------- racer_1_id: int The DB",
"match in the database. Returns --------- Match The created match. \"\"\" if 'match_id'",
"None, gsheet_info=sheet_info ) await new_match.initialize() match_library[new_match.match_id] = new_match return new_match async def get_schedule_infotext():",
"an unregistered Match ({0}).'.format(match.matchroom_name)) return None # Check to see if we already",
"import console, timestr, writechannel, strutil, rtmputil from necrobot.botbase.necrobot import Necrobot from necrobot.gsheet.matchgsheetinfo import",
"necrobot.util import console, timestr, writechannel, strutil, rtmputil from necrobot.botbase.necrobot import Necrobot from necrobot.gsheet.matchgsheetinfo",
"row[1] is not None else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info = MatchGSheetInfo()",
"{} has no suggested time.'.format(repr(match))) continue if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room",
"order_by_time=True): channel_id = int(row[13]) if row[13] is not None else None if channel_id",
"if match_id in match_library: del match_library[match_id] async def make_match_from_raw_db_data(row: list) -> Match: match_id",
"Match in the database. Returns ------- Optional[MatchRoom] The created room object. \"\"\" #",
"close the channel for. \"\"\" if not match.is_registered: console.warning('Trying to close the room",
"= '``` \\nUpcoming matches: \\n' for match in matches: if len(schedule_text) > 1800:",
"row[14] sheet_info.row = row[15] new_match = Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4],",
"a MatchRoom for an unregistered Match ({0}).'.format(match.matchroom_name)) return None # Check to see",
"initialize it match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize() return new_room",
"r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if row[13] is not None else None, gsheet_info=sheet_info )",
"not None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make the actual RaceRoom and initialize it",
"first racer has confirmed the match time. r2_confirmed: bool Whether the second racer",
"len(schedule_text) > 1800: break schedule_text += '{r1:>{w1}} v {r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len,",
"the match is suggested for. If no tzinfo, UTC is assumed. r1_confirmed: bool",
"new_room) await new_room.initialize() return new_room async def close_match_room(match: Match) -> None: \"\"\"Close the",
"If no tzinfo, UTC is assumed. r1_confirmed: bool Whether the first racer has",
"If True, the channel text will be written to a log file before",
"async def make_match(*args, register=False, **kwargs) -> Match: \"\"\"Create a Match object. There should",
"Parameters ---------- racer: NecroUser The racer to find channels for. If None, finds",
"await server.client.delete_channel(channel) match.set_channel_id(None) async def get_nextrace_displaytext(match_list: list) -> str: utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if",
"racedb from necrobot.util import console, timestr, writechannel, strutil, rtmputil from necrobot.botbase.necrobot import Necrobot",
"schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text += '\\n' schedule_text += '```' return schedule_text async def",
"find the channel or it didn't exist, make a new one if match_channel",
"in the database. Returns ------- Optional[MatchRoom] The created room object. \"\"\" # Check",
"log: await writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) ) await server.client.delete_channel(channel) if delete_this: await",
"None else None, gsheet_info=sheet_info ) await new_match.initialize() match_library[new_match.match_id] = new_match return new_match async",
") # display_text += ' RTMP: {} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # )",
"to be run in this match. cawmentator_id: int The DB unique ID of",
"server. Parameters ---------- log: bool If True, the channel text will be written",
"discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if match_channel is None: console.warning('Failed to make a match",
"it match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize() return new_room async",
"else None, gsheet_info=sheet_info ) await new_match.initialize() match_library[new_match.match_id] = new_match return new_match async def",
"or None: \"\"\"Create a discord.Channel and a corresponding MatchRoom for the given Match.",
"= int(channel.name[cut_length:]) largest_postfix = max(largest_postfix, val) except ValueError: pass return name_prefix if not",
"raw_data = await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id ) else: raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False,",
"ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info = MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row = row[15]",
"RTMP: {} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # ) display_text += '\\nFull schedule: <https://condor.host/schedule>'",
"True, then the match is a best of max_races; otherwise, the match is",
"row in raw_data: channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) if channel is not",
"the match time. r2_unconfirmed: bool Whether the second racer wishes to unconfirm the",
"make a MatchRoom for an unregistered Match ({0}).'.format(match.matchroom_name)) return None # Check to",
"is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info = MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row = row[15] new_match",
"channel_id is not None: channel = server.find_channel(channel_id=channel_id) if channel is not None: match",
"if match_channel is None: # Create permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True)",
"any. register: bool Whether to register the match in the database. Returns ---------",
"The DB user ID of the first racer. racer_2_id: int The DB user",
"\"\"\"Get a match object from its DB unique ID. Parameters ---------- match_id: int",
"Match) -> None: \"\"\"Close the discord.Channel corresponding to the Match, if any. Parameters",
"'Right now!' else: schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text += '\\n' schedule_text += '```' return",
"return None # Check to see if we already have the match channel",
"server featuring the specified racer. \"\"\" matches = [] if racer is not",
"call this directly; use matchutil.make_match instead, since this needs to interact with the",
"int The maximum number of races this match can be. (If is_best_of is",
"'\\nFull schedule: <https://condor.host/schedule>' return display_text async def delete_match(match_id: int) -> None: await matchdb.delete_match(match_id=match_id)",
"get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches = await get_upcoming_and_current() max_r1_len = 0 max_r2_len =",
"Match object. There should be no need to call this directly; use matchutil.make_match",
"await matchdb.get_channeled_matches_raw_data(): match_id = int(row[0]) channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) delete_this =",
"The Match to create a room for. register: bool If True, will register",
"time. r2_unconfirmed: bool Whether the second racer wishes to unconfirm the match time.",
"await match.commit() else: console.warning('Tried to make a MatchRoom for an unregistered Match ({0}).'.format(match.matchroom_name))",
"else: match_room = Necrobot().get_bot_channel(channel) if match_room is not None and await match_room.during_races(): matches.append(match)",
"and await match_room.during_races(): matches.append(match) return matches async def get_matches_with_channels(racer: NecroUser = None) ->",
"match_channel is None: # Create permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions",
"schedule: <https://condor.host/schedule>' return display_text async def delete_match(match_id: int) -> None: await matchdb.delete_match(match_id=match_id) if",
"max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text = '``` \\nUpcoming matches: \\n' for match in",
"register=False, **kwargs) -> Match: \"\"\"Create a Match object. There should be no need",
"return name_prefix if not found else '{0}-{1}'.format(name_prefix, largest_postfix + 1) async def get_upcoming_and_current()",
"\\n' else: display_text = 'Next match: \\n' for match in match_list: # noinspection",
"get_upcoming_and_current() max_r1_len = 0 max_r2_len = 0 for match in matches: max_r1_len =",
"suggested for. If no tzinfo, UTC is assumed. r1_confirmed: bool Whether the first",
"channel_id = int(row[13]) if row[13] is not None else None if channel_id is",
"None else None # If we couldn't find the channel or it didn't",
"server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if match_channel is None:",
"overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if match_channel is None: console.warning('Failed to make a match channel.')",
"delete_this: if log: await writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) ) await server.client.delete_channel(channel) if",
"---------- racer_1_id: int The DB user ID of the first racer. racer_2_id: int",
"server.server.channels: if channel.name.startswith(name_prefix): found = True try: val = int(channel.name[cut_length:]) largest_postfix = max(largest_postfix,",
"need to call this directly; use matchutil.make_match instead, since this needs to interact",
"Parameters ---------- match: Match The match whose info determines the name. Returns -------",
"ID. Parameters ---------- match_id: int The databse ID of the match. Returns -------",
"None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make a channel for the room # noinspection PyUnresolvedReferences",
"is suggested for. If no tzinfo, UTC is assumed. r1_confirmed: bool Whether the",
"match is just repeating max_races.) match_id: int The DB unique ID of this",
"new_room = MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize() return new_room async def close_match_room(match:",
"channel_id = match.channel_id match_channel = server.find_channel(channel_id=channel_id) if channel_id is not None else None",
"match_id = int(row[0]) channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) delete_this = True if",
"' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is not None and match.racer_2.twitch_name is not",
"else: return None def get_matchroom_name(match: Match) -> str: \"\"\"Get a new unique channel",
"writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) ) await server.client.delete_channel(channel) if delete_this: await matchdb.register_match_channel(match_id, None)",
"make_match_from_raw_db_data(raw_data) else: return None def get_matchroom_name(match: Match) -> str: \"\"\"Get a new unique",
"-> None: \"\"\"Close the discord.Channel corresponding to the Match, if any. Parameters ----------",
"this match. suggested_time: datetime.datetime The time the match is suggested for. If no",
"console.warning('Coudn\\'t find channel with id {0} in close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id)) return await",
"finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if row[13] is not None else",
"Match The match whose info determines the name. Returns ------- str The name",
"channel {0}, but couldn\\'t find this channel.'.format(channel_id)) return matches async def delete_all_match_channels(log=False, completed_only=False)",
"match was created from, if any. register: bool Whether to register the match",
"is just repeating max_races.) match_id: int The DB unique ID of this match.",
"int(channel.name[cut_length:]) largest_postfix = max(largest_postfix, val) except ValueError: pass return name_prefix if not found",
"see if we already have the match channel channel_id = match.channel_id match_channel =",
"channel channel_id = match.channel_id match_channel = server.find_channel(channel_id=channel_id) if channel_id is not None else",
"completed_only: match_room = Necrobot().get_bot_channel(channel) if match_room is None or not match_room.played_all_races: delete_this =",
"max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text = '``` \\nUpcoming matches:",
"channel text will be written to a log file before deletion. completed_only: bool",
"Parameters ---------- racer_1_id: int The DB user ID of the first racer. racer_2_id:",
"already have the match channel channel_id = match.channel_id match_channel = server.find_channel(channel_id=channel_id) if channel_id",
"match_id in match_library: return match_library[match_id] raw_data = await matchdb.get_raw_match_data(match_id) if raw_data is not",
"for. register: bool If True, will register the Match in the database. Returns",
"Match from necrobot.match.matchinfo import MatchInfo from necrobot.match.matchroom import MatchRoom from necrobot.race.raceinfo import RaceInfo",
"not None else None # If we couldn't find the channel or it",
"= 0 for match in matches: max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len,",
"= row[15] new_match = Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]),",
"match_channel_category is not None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make the actual RaceRoom and",
"import MatchGSheetInfo from necrobot.match.match import Match from necrobot.match.matchinfo import MatchInfo from necrobot.match.matchroom import",
"of the worksheet the match was created from, if any. register: bool Whether",
") await server.client.delete_channel(channel) if delete_this: await matchdb.register_match_channel(match_id, None) async def make_match_room(match: Match, register=False)",
"if not found else '{0}-{1}'.format(name_prefix, largest_postfix + 1) async def get_upcoming_and_current() -> list:",
"match in matches: if len(schedule_text) > 1800: break schedule_text += '{r1:>{w1}} v {r2:<{w2}}",
"> pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room = Necrobot().get_bot_channel(channel) if match_room is not None and",
"for the room # noinspection PyUnresolvedReferences match_channel = await server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role,",
"maximum number of races this match can be. (If is_best_of is True, then",
"None: \"\"\"Get a match object from its DB unique ID. Parameters ---------- match_id:",
"Match with channel {0}, but couldn\\'t find this channel.'.format(channel_id)) return matches async def",
"Config match_library = {} # noinspection PyIncorrectDocstring async def make_match(*args, register=False, **kwargs) ->",
"to unconfirm the match time. match_info: MatchInfo The types of races to be",
"if len(schedule_text) > 1800: break schedule_text += '{r1:>{w1}} v {r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name),",
"'\\n' schedule_text += '```' return schedule_text async def get_race_data(match: Match): return await matchdb.get_match_race_data(match.match_id)",
"None def get_matchroom_name(match: Match) -> str: \"\"\"Get a new unique channel name corresponding",
"matches.append(match) return matches async def get_matches_with_channels(racer: NecroUser = None) -> list: \"\"\" Parameters",
"The racer to find channels for. If None, finds all channeled matches. Returns",
"server.client.delete_channel(channel) if delete_this: await matchdb.register_match_channel(match_id, None) async def make_match_room(match: Match, register=False) -> MatchRoom",
"match.commit() else: console.warning('Tried to make a MatchRoom for an unregistered Match ({0}).'.format(match.matchroom_name)) return",
"return match_library[match_id] match_info = MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1] is not None else",
"MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1] is not None else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11])",
"the cawmentator for this match. sheet_id: int The sheetID of the worksheet the",
"if row[1] is not None else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info =",
"rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) # display_text += ' RTMP: {} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name)",
"in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id = int(row[13]) if row[13] is not None else",
"= server.find_channel(channel_id=channel_id) delete_this = True if channel is not None: if completed_only: match_room",
"match: \\n' for match in match_list: # noinspection PyUnresolvedReferences display_text += '\\N{BULLET} **{0}**",
"datetime.datetime The time the match is suggested for. If no tzinfo, UTC is",
"None # If we couldn't find the channel or it didn't exist, make",
"None: \"\"\"Close the discord.Channel corresponding to the Match, if any. Parameters ---------- match:",
"The maximum number of races this match can be. (If is_best_of is True,",
"return None def get_matchroom_name(match: Match) -> str: \"\"\"Get a new unique channel name",
"a discord.Channel and a corresponding MatchRoom for the given Match. Parameters ---------- match:",
"int The DB user ID of the second racer. max_races: int The maximum",
"and ongoing matches, in order. \"\"\" matches = [] for row in await",
"no suggested time.'.format(repr(match))) continue if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room = Necrobot().get_bot_channel(channel)",
"with the database. Parameters ---------- racer_1_id: int The DB user ID of the",
"discord.PermissionOverwrite(read_messages=True) racer_permissions = [] for racer in match.racers: if racer.member is not None:",
"channel is not None: match = await make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found Match with",
"cawmentator_id: int The DB unique ID of the cawmentator for this match. sheet_id:",
"find completed matches. \"\"\" for row in await matchdb.get_channeled_matches_raw_data(): match_id = int(row[0]) channel_id",
"1 found = False for channel in server.server.channels: if channel.name.startswith(name_prefix): found = True",
"for. If no tzinfo, UTC is assumed. r1_confirmed: bool Whether the first racer",
"if match_cawmentator is not None: display_text += ' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name",
"console.warning('Failed to make a match channel.') return None # Put the match channel",
"match in match_list: # noinspection PyUnresolvedReferences display_text += '\\N{BULLET} **{0}** - **{1}**'.format( match.racer_1.display_name,",
"def delete_match(match_id: int) -> None: await matchdb.delete_match(match_id=match_id) if match_id in match_library: del match_library[match_id]",
"interact with the database. Parameters ---------- racer_1_id: int The DB user ID of",
"Match to close the channel for. \"\"\" if not match.is_registered: console.warning('Trying to close",
"if delete_this: await matchdb.register_match_channel(match_id, None) async def make_match_room(match: Match, register=False) -> MatchRoom or",
"await matchdb.register_match_channel(match_id, None) async def make_match_room(match: Match, register=False) -> MatchRoom or None: \"\"\"Create",
"match.set_channel_id(None) async def get_nextrace_displaytext(match_list: list) -> str: utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) >",
"await server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if match_channel is",
"Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is not None and match.racer_2.twitch_name is not None:",
"is not None else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info = MatchGSheetInfo() sheet_info.wks_id",
"to close the room for an unregistered match.') return channel_id = match.channel_id channel",
"name. Returns ------- str The name of the channel. \"\"\" name_prefix = match.matchroom_name",
"get_upcoming_and_current() -> list: \"\"\" Returns ------- list[Match] A list of all upcoming and",
"DB unique ID of this match. suggested_time: datetime.datetime The time the match is",
"ongoing matches, in order. \"\"\" matches = [] for row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True,",
"= match return match async def get_match_from_id(match_id: int) -> Match or None: \"\"\"Get",
"None: display_text += ' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is not None and",
"match_id: int The DB unique ID of this match. suggested_time: datetime.datetime The time",
"list[Match] A list of all Matches that have associated channels on the server",
"Match The Match to create a room for. register: bool If True, will",
") display_text += '\\nFull schedule: <https://condor.host/schedule>' return display_text async def delete_match(match_id: int) ->",
"len(name_prefix) + 1 largest_postfix = 1 found = False for channel in server.server.channels:",
"async def make_match_room(match: Match, register=False) -> MatchRoom or None: \"\"\"Create a discord.Channel and",
"match=match) Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize() return new_room async def close_match_room(match: Match) -> None:",
"unique ID of the cawmentator for this match. sheet_id: int The sheetID of",
"is registered if not match.is_registered: if register: await match.commit() else: console.warning('Tried to make",
"display_text += '\\N{BULLET} **{0}** - **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time is None: display_text",
"True, the channel text will be written to a log file before deletion.",
"match_room is not None and await match_room.during_races(): matches.append(match) return matches async def get_matches_with_channels(racer:",
"an unregistered match.') return channel_id = match.channel_id channel = server.find_channel(channel_id=channel_id) if channel is",
"\"\"\" if match_id is None: return None if match_id in match_library: return match_library[match_id]",
"be. (If is_best_of is True, then the match is a best of max_races;",
"if channel is not None: match = await make_match_from_raw_db_data(row=row) if match.suggested_time is None:",
"in await matchdb.get_channeled_matches_raw_data(): match_id = int(row[0]) channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) delete_this",
"needs to interact with the database. Parameters ---------- racer_1_id: int The DB user",
"is True, then the match is a best of max_races; otherwise, the match",
"match object from its DB unique ID. Parameters ---------- match_id: int The databse",
"wishes to unconfirm the match time. match_info: MatchInfo The types of races to",
"is None: return None if match_id in match_library: return match_library[match_id] raw_data = await",
"the database. Parameters ---------- racer_1_id: int The DB user ID of the first",
"should be no need to call this directly; use matchutil.make_match instead, since this",
"DB user ID of the second racer. max_races: int The maximum number of",
"If True, will only find completed matches. \"\"\" for row in await matchdb.get_channeled_matches_raw_data():",
"name_prefix = match.matchroom_name cut_length = len(name_prefix) + 1 largest_postfix = 1 found =",
"+= timestr.str_full_24h(match.suggested_time) schedule_text += '\\n' schedule_text += '```' return schedule_text async def get_race_data(match:",
"not None: channel = server.find_channel(channel_id=channel_id) if channel is not None: match = await",
"raw_data: channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) if channel is not None: match",
"= server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is not None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make the",
"True if channel is not None: if completed_only: match_room = Necrobot().get_bot_channel(channel) if match_room",
"the Match in the database. Returns ------- Optional[MatchRoom] The created room object. \"\"\"",
"pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room = Necrobot().get_bot_channel(channel) if match_room is not None and await",
"delete_match(match_id: int) -> None: await matchdb.delete_match(match_id=match_id) if match_id in match_library: del match_library[match_id] async",
"the match time. r1_unconfirmed: bool Whether the first racer wishes to unconfirm the",
"completed_only=False) -> None: \"\"\"Delete all match channels from the server. Parameters ---------- log:",
"match.channel_id channel = server.find_channel(channel_id=channel_id) if channel is None: console.warning('Coudn\\'t find channel with id",
"Match(*args, commit_fn=matchdb.write_match, **kwargs) await match.initialize() if register: await match.commit() match_library[match.match_id] = match return",
") else: raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row in raw_data: channel_id =",
"return channel_id = match.channel_id channel = server.find_channel(channel_id=channel_id) if channel is None: console.warning('Coudn\\'t find",
"was created from, if any. register: bool Whether to register the match in",
"+= ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True)) match_cawmentator = await match.get_cawmentator() if match_cawmentator",
"list) -> Match: match_id = int(row[0]) if match_id in match_library: return match_library[match_id] match_info",
"match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize() return new_room async def",
"written to a log file before deletion. completed_only: bool If True, will only",
"if match_id in match_library: return match_library[match_id] raw_data = await matchdb.get_raw_match_data(match_id) if raw_data is",
"discord.Channel and a corresponding MatchRoom for the given Match. Parameters ---------- match: Match",
"is not None else None # If we couldn't find the channel or",
"channel in the matches category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is not None:",
"register: bool If True, will register the Match in the database. Returns -------",
"else: console.warning('Found Match with channel {0}, but couldn\\'t find this channel.'.format(channel_id)) return matches",
"# noinspection PyUnresolvedReferences display_text += '\\N{BULLET} **{0}** - **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time",
"display_text += ' Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) # display_text += '",
"schedule_text = '``` \\nUpcoming matches: \\n' for match in matches: if len(schedule_text) >",
"confirmed the match time. r1_unconfirmed: bool Whether the first racer wishes to unconfirm",
"'{0}-{1}'.format(name_prefix, largest_postfix + 1) async def get_upcoming_and_current() -> list: \"\"\" Returns ------- list[Match]",
"list of all upcoming and ongoing matches, in order. \"\"\" matches = []",
"matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id = int(row[13]) if row[13] is not None else None if",
"Check to see the match is registered if not match.is_registered: if register: await",
"new unique channel name corresponding to the match. Parameters ---------- match: Match The",
"= int(row[13]) channel = server.find_channel(channel_id=channel_id) if channel is not None: match = await",
"get_nextrace_displaytext(match_list: list) -> str: utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) > 1: display_text =",
"else: schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text += '\\n' schedule_text += '```' return schedule_text async",
"match_library[match_id] raw_data = await matchdb.get_raw_match_data(match_id) if raw_data is not None: return await make_match_from_raw_db_data(raw_data)",
"# Check to see the match is registered if not match.is_registered: if register:",
"this channel.'.format(channel_id)) return matches async def delete_all_match_channels(log=False, completed_only=False) -> None: \"\"\"Delete all match",
"match.racer_1.twitch_name is not None and match.racer_2.twitch_name is not None: display_text += ' Kadgar:",
"object. There should be no need to call this directly; use matchutil.make_match instead,",
"None or not match_room.played_all_races: delete_this = False if delete_this: if log: await writechannel.write_channel(",
"from the server. Parameters ---------- log: bool If True, the channel text will",
"matches.append(match) else: match_room = Necrobot().get_bot_channel(channel) if match_room is not None and await match_room.during_races():",
"close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id)) return await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None) async def get_nextrace_displaytext(match_list:",
"Make a channel for the room # noinspection PyUnresolvedReferences match_channel = await server.client.create_channel(",
"None: match = await make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found Match with channel {0}, but",
"match channel in the matches category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is not",
"user ID of the second racer. max_races: int The maximum number of races",
"a new unique channel name corresponding to the match. Parameters ---------- match: Match",
"await match.initialize() if register: await match.commit() match_library[match.match_id] = match return match async def",
"match_info = MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1] is not None else RaceInfo(), ranked=bool(row[9]),",
"await matchdb.get_raw_match_data(match_id) if raw_data is not None: return await make_match_from_raw_db_data(raw_data) else: return None",
"match_library: return match_library[match_id] match_info = MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1] is not None",
"server.find_channel(channel_id=channel_id) if channel is not None: match = await make_match_from_raw_db_data(row=row) if match.suggested_time is",
"in match_library: return match_library[match_id] raw_data = await matchdb.get_raw_match_data(match_id) if raw_data is not None:",
"\"\"\"Create a Match object. There should be no need to call this directly;",
"instead, since this needs to interact with the database. Parameters ---------- racer_1_id: int",
"<https://condor.host/schedule>' return display_text async def delete_match(match_id: int) -> None: await matchdb.delete_match(match_id=match_id) if match_id",
"not None else None, gsheet_info=sheet_info ) await new_match.initialize() match_library[new_match.match_id] = new_match return new_match",
"Match to create a room for. register: bool If True, will register the",
"break schedule_text += '{r1:>{w1}} v {r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len )",
"match_room is None or not match_room.played_all_races: delete_this = False if delete_this: if log:",
"Optional[MatchRoom] The created room object. \"\"\" # Check to see the match is",
"is not None: display_text += ' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is not",
"+= '\\n' schedule_text += '```' return schedule_text async def get_race_data(match: Match): return await",
"a new one if match_channel is None: # Create permissions deny_read = discord.PermissionOverwrite(read_messages=False)",
"console.warning('Found Match with channel {0}, but couldn\\'t find this channel.'.format(channel_id)) return matches async",
"{} # noinspection PyIncorrectDocstring async def make_match(*args, register=False, **kwargs) -> Match: \"\"\"Create a",
"sheet_info.row = row[15] new_match = Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16],",
"---------- match_id: int The databse ID of the match. Returns ------- Optional[Match] The",
"display_text = 'Next match: \\n' for match in match_list: # noinspection PyUnresolvedReferences display_text",
"from necrobot.botbase import server, discordutil from necrobot.database import matchdb, racedb from necrobot.util import",
"matches category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is not None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category)",
"ID of the first racer. racer_2_id: int The DB user ID of the",
"max_r2_len = 0 for match in matches: max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len =",
"name_prefix if not found else '{0}-{1}'.format(name_prefix, largest_postfix + 1) async def get_upcoming_and_current() ->",
"racer wishes to unconfirm the match time. r2_unconfirmed: bool Whether the second racer",
"for an unregistered Match ({0}).'.format(match.matchroom_name)) return None # Check to see if we",
"match.racer_2.display_name) if match.suggested_time is None: display_text += '\\n' continue display_text += ': {0}",
"RaceRoom and initialize it match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize()",
"display_text += ' RTMP: {} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # ) display_text +=",
"-> str: \"\"\"Get a new unique channel name corresponding to the match. Parameters",
"in matches: max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text = '```",
"timestr.str_full_24h(match.suggested_time) schedule_text += '\\n' schedule_text += '```' return schedule_text async def get_race_data(match: Match):",
"if channel is None: console.warning('Coudn\\'t find channel with id {0} in close_match_room '",
"A list of all upcoming and ongoing matches, in order. \"\"\" matches =",
"from necrobot.match.match import Match from necrobot.match.matchinfo import MatchInfo from necrobot.match.matchroom import MatchRoom from",
"matches = await get_upcoming_and_current() max_r1_len = 0 max_r2_len = 0 for match in",
"= int(row[0]) channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) delete_this = True if channel",
"matchdb.get_channeled_matches_raw_data(): match_id = int(row[0]) channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) delete_this = True",
"match_library: return match_library[kwargs['match_id']] match = Match(*args, commit_fn=matchdb.write_match, **kwargs) await match.initialize() if register: await",
"MatchInfo The types of races to be run in this match. cawmentator_id: int",
"but couldn\\'t find this channel.'.format(channel_id)) return matches async def delete_all_match_channels(log=False, completed_only=False) -> None:",
"this match. sheet_id: int The sheetID of the worksheet the match was created",
"for an unregistered match.') return channel_id = match.channel_id channel = server.find_channel(channel_id=channel_id) if channel",
"couldn\\'t find this channel.'.format(channel_id)) return matches async def delete_all_match_channels(log=False, completed_only=False) -> None: \"\"\"Delete",
"match.racer_2.twitch_name) ) # display_text += ' RTMP: {} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) #",
"the second racer has confirmed the match time. r1_unconfirmed: bool Whether the first",
"of races this match can be. (If is_best_of is True, then the match",
"row in await matchdb.get_channeled_matches_raw_data(): match_id = int(row[0]) channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id)",
"the match in the database. Returns --------- Match The created match. \"\"\" if",
"of races to be run in this match. cawmentator_id: int The DB unique",
"order. \"\"\" matches = [] for row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id =",
"list[Match] A list of all upcoming and ongoing matches, in order. \"\"\" matches",
"channel is not None: if completed_only: match_room = Necrobot().get_bot_channel(channel) if match_room is None",
"matchdb, racedb from necrobot.util import console, timestr, writechannel, strutil, rtmputil from necrobot.botbase.necrobot import",
"created match. \"\"\" if 'match_id' in kwargs and kwargs['match_id'] in match_library: return match_library[kwargs['match_id']]",
"': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True)) match_cawmentator = await match.get_cawmentator() if match_cawmentator is",
"+= 'Right now!' else: schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text += '\\n' schedule_text += '```'",
"for row in await matchdb.get_channeled_matches_raw_data(): match_id = int(row[0]) channel_id = int(row[13]) channel =",
"await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row in raw_data: channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id)",
"suggested_time: datetime.datetime The time the match is suggested for. If no tzinfo, UTC",
"Returns ------- Optional[MatchRoom] The created room object. \"\"\" # Check to see the",
"Returns ------- str The name of the channel. \"\"\" name_prefix = match.matchroom_name cut_length",
"a Match object. There should be no need to call this directly; use",
"matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row in raw_data: channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) if",
"\"\"\"Create a discord.Channel and a corresponding MatchRoom for the given Match. Parameters ----------",
"Returns ------- list[Match] A list of all upcoming and ongoing matches, in order.",
"the name. Returns ------- str The name of the channel. \"\"\" name_prefix =",
"unregistered Match ({0}).'.format(match.matchroom_name)) return None # Check to see if we already have",
"in this match. cawmentator_id: int The DB unique ID of the cawmentator for",
"and initialize it match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize() return",
"({0}).'.format(match.matchroom_name)) return None # Check to see if we already have the match",
"ID of the match. Returns ------- Optional[Match] The match found, if any. \"\"\"",
"the match time. r2_confirmed: bool Whether the second racer has confirmed the match",
"not None: raw_data = await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id ) else: raw_data =",
"channeled matches. Returns ------- list[Match] A list of all Matches that have associated",
"the match is just repeating max_races.) match_id: int The DB unique ID of",
"match is registered if not match.is_registered: if register: await match.commit() else: console.warning('Tried to",
"int The DB unique ID of this match. suggested_time: datetime.datetime The time the",
"database. Parameters ---------- racer_1_id: int The DB user ID of the first racer.",
"datetime.timedelta(minutes=0): schedule_text += 'Right now!' else: schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text += '\\n' schedule_text",
"NecroUser = None) -> list: \"\"\" Parameters ---------- racer: NecroUser The racer to",
"with id {0} in close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id)) return await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel)",
"not None: display_text += ' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is not None",
"Returns ------- Optional[Match] The match found, if any. \"\"\" if match_id is None:",
"+= ' RTMP: {} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # ) display_text += '\\nFull",
"-> Match: match_id = int(row[0]) if match_id in match_library: return match_library[match_id] match_info =",
"await new_room.initialize() return new_room async def close_match_room(match: Match) -> None: \"\"\"Close the discord.Channel",
"utcnow < datetime.timedelta(minutes=0): schedule_text += 'Right now!' else: schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text +=",
"row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id = int(row[13]) if row[13] is not None",
"make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found Match with channel {0}, but couldn\\'t find this channel.'.format(channel_id))",
"match_library[new_match.match_id] = new_match return new_match async def get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches =",
"match.racers: if racer.member is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make a channel for",
"that have associated channels on the server featuring the specified racer. \"\"\" matches",
"async def get_nextrace_displaytext(match_list: list) -> str: utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) > 1:",
"if match.suggested_time is None: display_text += '\\n' continue display_text += ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time",
"= 1 found = False for channel in server.server.channels: if channel.name.startswith(name_prefix): found =",
"= await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row in raw_data: channel_id = int(row[13]) channel =",
"with channel {0}, but couldn\\'t find this channel.'.format(channel_id)) return matches async def delete_all_match_channels(log=False,",
"channel for. \"\"\" if not match.is_registered: console.warning('Trying to close the room for an",
"= [] if racer is not None: raw_data = await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False,",
"MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row = row[15] new_match = Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info,",
"a room for. register: bool If True, will register the Match in the",
"new_match = Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]),",
"r1_unconfirmed: bool Whether the first racer wishes to unconfirm the match time. r2_unconfirmed:",
"to see if we already have the match channel channel_id = match.channel_id match_channel",
"discordutil from necrobot.database import matchdb, racedb from necrobot.util import console, timestr, writechannel, strutil,",
"cawmentator for this match. sheet_id: int The sheetID of the worksheet the match",
"if row[13] is not None else None if channel_id is not None: channel",
"and match.racer_2.twitch_name is not None: display_text += ' Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name)",
"in raw_data: channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) if channel is not None:",
"If True, will register the Match in the database. Returns ------- Optional[MatchRoom] The",
"if match.suggested_time is None: console.warning('Found match object {} has no suggested time.'.format(repr(match))) continue",
"+= '\\n' continue display_text += ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True)) match_cawmentator =",
"MatchRoom or None: \"\"\"Create a discord.Channel and a corresponding MatchRoom for the given",
"async def get_upcoming_and_current() -> list: \"\"\" Returns ------- list[Match] A list of all",
"racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if row[13] is not",
"None # Put the match channel in the matches category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME)",
"= pytz.utc.localize(datetime.datetime.utcnow()) matches = await get_upcoming_and_current() max_r1_len = 0 max_r2_len = 0 for",
"to find channels for. If None, finds all channeled matches. Returns ------- list[Match]",
"match.matchroom_name cut_length = len(name_prefix) + 1 largest_postfix = 1 found = False for",
"racer_1_id: int The DB user ID of the first racer. racer_2_id: int The",
"Parameters ---------- match_id: int The databse ID of the match. Returns ------- Optional[Match]",
"# display_text += ' RTMP: {} \\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # ) display_text",
"# ) display_text += '\\nFull schedule: <https://condor.host/schedule>' return display_text async def delete_match(match_id: int)",
"determines the name. Returns ------- str The name of the channel. \"\"\" name_prefix",
"server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if match_channel is None: console.warning('Failed",
"match return match async def get_match_from_id(match_id: int) -> Match or None: \"\"\"Get a",
"in the database. Returns --------- Match The created match. \"\"\" if 'match_id' in",
"utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) > 1: display_text = 'Upcoming matches: \\n' else:",
"new_match.initialize() match_library[new_match.match_id] = new_match return new_match async def get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches",
"import Match from necrobot.match.matchinfo import MatchInfo from necrobot.match.matchroom import MatchRoom from necrobot.race.raceinfo import",
"int The DB user ID of the first racer. racer_2_id: int The DB",
"matchdb.register_match_channel(match_id, None) async def make_match_room(match: Match, register=False) -> MatchRoom or None: \"\"\"Create a",
") sheet_info = MatchGSheetInfo() sheet_info.wks_id = row[14] sheet_info.row = row[15] new_match = Match(",
"= [] for row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id = int(row[13]) if row[13]",
"featuring the specified racer. \"\"\" matches = [] if racer is not None:",
"await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id = int(row[13]) if row[13] is not None else None",
"has confirmed the match time. r2_confirmed: bool Whether the second racer has confirmed",
"match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if",
"the server. Parameters ---------- log: bool If True, the channel text will be",
"register: await match.commit() else: console.warning('Tried to make a MatchRoom for an unregistered Match",
"noinspection PyIncorrectDocstring async def make_match(*args, register=False, **kwargs) -> Match: \"\"\"Create a Match object.",
"Match) -> str: \"\"\"Get a new unique channel name corresponding to the match.",
"-> str: utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) > 1: display_text = 'Upcoming matches:",
"is not None: display_text += ' Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) #",
"channels for. If None, finds all channeled matches. Returns ------- list[Match] A list",
"\"\"\"Close the discord.Channel corresponding to the Match, if any. Parameters ---------- match: Match",
"second racer has confirmed the match time. r1_unconfirmed: bool Whether the first racer",
"is a best of max_races; otherwise, the match is just repeating max_races.) match_id:",
"match_library[match.match_id] = match return match async def get_match_from_id(match_id: int) -> Match or None:",
"match.commit() match_library[match.match_id] = match return match async def get_match_from_id(match_id: int) -> Match or",
"will only find completed matches. \"\"\" for row in await matchdb.get_channeled_matches_raw_data(): match_id =",
"if register: await match.commit() else: console.warning('Tried to make a MatchRoom for an unregistered",
"in matches: if len(schedule_text) > 1800: break schedule_text += '{r1:>{w1}} v {r2:<{w2}} :",
"UTC is assumed. r1_confirmed: bool Whether the first racer has confirmed the match",
"match_channel = await server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text) if",
"-> list: \"\"\" Parameters ---------- racer: NecroUser The racer to find channels for.",
"make a new one if match_channel is None: # Create permissions deny_read =",
"channel.name) ) await server.client.delete_channel(channel) if delete_this: await matchdb.register_match_channel(match_id, None) async def make_match_room(match: Match,",
"racer. \"\"\" matches = [] if racer is not None: raw_data = await",
"Whether the second racer wishes to unconfirm the match time. match_info: MatchInfo The",
"if not match.is_registered: console.warning('Trying to close the room for an unregistered match.') return",
"Match ({0}).'.format(match.matchroom_name)) return None # Check to see if we already have the",
"overwrite=permit_read)) # Make a channel for the room # noinspection PyUnresolvedReferences match_channel =",
"outfile_name='{0}-{1}'.format(match_id, channel.name) ) await server.client.delete_channel(channel) if delete_this: await matchdb.register_match_channel(match_id, None) async def make_match_room(match:",
"**{0}** - **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time is None: display_text += '\\n' continue",
"channel.name.startswith(name_prefix): found = True try: val = int(channel.name[cut_length:]) largest_postfix = max(largest_postfix, val) except",
"Parameters ---------- log: bool If True, the channel text will be written to",
"not match_room.played_all_races: delete_this = False if delete_this: if log: await writechannel.write_channel( client=server.client, channel=channel,",
"racer. max_races: int The maximum number of races this match can be. (If",
"> 1: display_text = 'Upcoming matches: \\n' else: display_text = 'Next match: \\n'",
"await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id ) else: raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for",
"racer is not None: raw_data = await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id ) else:",
"= Necrobot().get_bot_channel(channel) if match_room is None or not match_room.played_all_races: delete_this = False if",
"The created match. \"\"\" if 'match_id' in kwargs and kwargs['match_id'] in match_library: return",
"for racer in match.racers: if racer.member is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make",
"register the Match in the database. Returns ------- Optional[MatchRoom] The created room object.",
"\\n'.format( # rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # ) display_text += '\\nFull schedule: <https://condor.host/schedule>' return display_text",
"object from its DB unique ID. Parameters ---------- match_id: int The databse ID",
"PyUnresolvedReferences match_channel = await server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), *racer_permissions, type=discord.ChannelType.text)",
"---------- match: Match The Match to close the channel for. \"\"\" if not",
"in match_library: del match_library[match_id] async def make_match_from_raw_db_data(row: list) -> Match: match_id = int(row[0])",
"cut_length = len(name_prefix) + 1 largest_postfix = 1 found = False for channel",
"a channel for the room # noinspection PyUnresolvedReferences match_channel = await server.client.create_channel( server.server,",
"\"\"\" # Check to see the match is registered if not match.is_registered: if",
"before deletion. completed_only: bool If True, will only find completed matches. \"\"\" for",
"not None: match = await make_match_from_raw_db_data(row=row) if match.suggested_time is None: console.warning('Found match object",
"if delete_this: if log: await writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) ) await server.client.delete_channel(channel)",
"= await matchdb.get_raw_match_data(match_id) if raw_data is not None: return await make_match_from_raw_db_data(raw_data) else: return",
"schedule_text += 'Right now!' else: schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text += '\\n' schedule_text +=",
"channels on the server featuring the specified racer. \"\"\" matches = [] if",
"None: console.warning('Found match object {} has no suggested time.'.format(repr(match))) continue if match.suggested_time >",
"bool Whether to register the match in the database. Returns --------- Match The",
"utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches = await get_upcoming_and_current() max_r1_len = 0 max_r2_len = 0",
"wishes to unconfirm the match time. r2_unconfirmed: bool Whether the second racer wishes",
"= MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize() return new_room async def close_match_room(match: Match)",
"Parameters ---------- match: Match The Match to close the channel for. \"\"\" if",
"# rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # ) display_text += '\\nFull schedule: <https://condor.host/schedule>' return display_text async",
"if channel_id is not None: channel = server.find_channel(channel_id=channel_id) if channel is not None:",
"Returns --------- Match The created match. \"\"\" if 'match_id' in kwargs and kwargs['match_id']",
"= await match.get_cawmentator() if match_cawmentator is not None: display_text += ' Cawmentary: <http://www.twitch.tv/{0}>",
"= pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list) > 1: display_text = 'Upcoming matches: \\n' else: display_text",
"the match is registered if not match.is_registered: if register: await match.commit() else: console.warning('Tried",
"= 'Upcoming matches: \\n' else: display_text = 'Next match: \\n' for match in",
"unconfirm the match time. r2_unconfirmed: bool Whether the second racer wishes to unconfirm",
"if we already have the match channel channel_id = match.channel_id match_channel = server.find_channel(channel_id=channel_id)",
"a match channel.') return None # Put the match channel in the matches",
"The sheetID of the worksheet the match was created from, if any. register:",
"deny_read = discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) racer_permissions = [] for racer in match.racers:",
"'\\N{BULLET} **{0}** - **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time is None: display_text += '\\n'",
"1 largest_postfix = 1 found = False for channel in server.server.channels: if channel.name.startswith(name_prefix):",
"will be written to a log file before deletion. completed_only: bool If True,",
"= match.channel_id match_channel = server.find_channel(channel_id=channel_id) if channel_id is not None else None #",
"r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if row[13] is not None else None, gsheet_info=sheet_info ) await",
"Returns ------- list[Match] A list of all Matches that have associated channels on",
"the specified racer. \"\"\" matches = [] if racer is not None: raw_data",
"None: \"\"\"Delete all match channels from the server. Parameters ---------- log: bool If",
"channel is None: console.warning('Coudn\\'t find channel with id {0} in close_match_room ' '(match_id={1}).'.format(channel_id,",
"\\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True)) match_cawmentator = await match.get_cawmentator() if match_cawmentator is not None:",
"Match or None: \"\"\"Get a match object from its DB unique ID. Parameters",
"None: channel = server.find_channel(channel_id=channel_id) if channel is not None: match = await make_match_from_raw_db_data(row=row)",
"the database. Returns ------- Optional[MatchRoom] The created room object. \"\"\" # Check to",
"-> list: \"\"\" Returns ------- list[Match] A list of all upcoming and ongoing",
"find channel with id {0} in close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id)) return await Necrobot().unregister_bot_channel(channel)",
"match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room = Necrobot().get_bot_channel(channel) if match_room is not None",
"The DB unique ID of this match. suggested_time: datetime.datetime The time the match",
"r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if match.suggested_time - utcnow < datetime.timedelta(minutes=0): schedule_text +=",
"be no need to call this directly; use matchutil.make_match instead, since this needs",
"--------- Match The created match. \"\"\" if 'match_id' in kwargs and kwargs['match_id'] in",
"found, if any. \"\"\" if match_id is None: return None if match_id in",
"match.is_registered: console.warning('Trying to close the room for an unregistered match.') return channel_id =",
"match_info: MatchInfo The types of races to be run in this match. cawmentator_id:",
"if any. \"\"\" if match_id is None: return None if match_id in match_library:",
"The time the match is suggested for. If no tzinfo, UTC is assumed.",
"DB unique ID. Parameters ---------- match_id: int The databse ID of the match.",
"Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize() return new_room async def close_match_room(match: Match) -> None: \"\"\"Close",
"not None: if completed_only: match_room = Necrobot().get_bot_channel(channel) if match_room is None or not",
"is assumed. r1_confirmed: bool Whether the first racer has confirmed the match time.",
"ID of the second racer. max_races: int The maximum number of races this",
"log: bool If True, the channel text will be written to a log",
"Put the match channel in the matches category match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category",
"found else '{0}-{1}'.format(name_prefix, largest_postfix + 1) async def get_upcoming_and_current() -> list: \"\"\" Returns",
"not found else '{0}-{1}'.format(name_prefix, largest_postfix + 1) async def get_upcoming_and_current() -> list: \"\"\"",
"is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make a channel for the room #",
"return new_room async def close_match_room(match: Match) -> None: \"\"\"Close the discord.Channel corresponding to",
"\"\"\" name_prefix = match.matchroom_name cut_length = len(name_prefix) + 1 largest_postfix = 1 found",
"await make_match_from_raw_db_data(row=row) matches.append(match) else: console.warning('Found Match with channel {0}, but couldn\\'t find this",
"\\n' for match in matches: if len(schedule_text) > 1800: break schedule_text += '{r1:>{w1}}",
"None, finds all channeled matches. Returns ------- list[Match] A list of all Matches",
"-> Match: \"\"\"Create a Match object. There should be no need to call",
"'.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if match.suggested_time - utcnow < datetime.timedelta(minutes=0): schedule_text",
"await match.commit() match_library[match.match_id] = match return match async def get_match_from_id(match_id: int) -> Match",
"match_cawmentator = await match.get_cawmentator() if match_cawmentator is not None: display_text += ' Cawmentary:",
"if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room = Necrobot().get_bot_channel(channel) if match_room is not",
"the channel text will be written to a log file before deletion. completed_only:",
"info determines the name. Returns ------- str The name of the channel. \"\"\"",
"the match was created from, if any. register: bool Whether to register the",
"channel.') return None # Put the match channel in the matches category match_channel_category",
"channel = server.find_channel(channel_id=channel_id) if channel is None: console.warning('Coudn\\'t find channel with id {0}",
"match_channel_category = server.find_channel(channel_name=Config.MATCH_CHANNEL_CATEGORY_NAME) if match_channel_category is not None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make",
"corresponding to the Match, if any. Parameters ---------- match: Match The Match to",
"await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make the actual RaceRoom and initialize it match.set_channel_id(int(match_channel.id)) new_room",
"DB unique ID of the cawmentator for this match. sheet_id: int The sheetID",
"The created room object. \"\"\" # Check to see the match is registered",
"bool Whether the first racer has confirmed the match time. r2_confirmed: bool Whether",
"for row in raw_data: channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) if channel is",
"------- Optional[MatchRoom] The created room object. \"\"\" # Check to see the match",
"# Make the actual RaceRoom and initialize it match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel, match=match)",
"Whether to register the match in the database. Returns --------- Match The created",
"we couldn't find the channel or it didn't exist, make a new one",
"on the server featuring the specified racer. \"\"\" matches = [] if racer",
"match_library[kwargs['match_id']] match = Match(*args, commit_fn=matchdb.write_match, **kwargs) await match.initialize() if register: await match.commit() match_library[match.match_id]",
"the match is a best of max_races; otherwise, the match is just repeating",
"The types of races to be run in this match. cawmentator_id: int The",
"couldn't find the channel or it didn't exist, make a new one if",
"necrobot.botbase.necrobot import Necrobot from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from necrobot.match.match import Match from necrobot.match.matchinfo",
"str The name of the channel. \"\"\" name_prefix = match.matchroom_name cut_length = len(name_prefix)",
"= new_match return new_match async def get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches = await",
"1) async def get_upcoming_and_current() -> list: \"\"\" Returns ------- list[Match] A list of",
"racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make a channel for the room # noinspection PyUnresolvedReferences match_channel",
"we already have the match channel channel_id = match.channel_id match_channel = server.find_channel(channel_id=channel_id) if",
"new_room.initialize() return new_room async def close_match_room(match: Match) -> None: \"\"\"Close the discord.Channel corresponding",
"the server featuring the specified racer. \"\"\" matches = [] if racer is",
"racer in match.racers: if racer.member is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make a",
"display_text += ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True)) match_cawmentator = await match.get_cawmentator() if",
"max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text = '``` \\nUpcoming matches: \\n' for",
"await writechannel.write_channel( client=server.client, channel=channel, outfile_name='{0}-{1}'.format(match_id, channel.name) ) await server.client.delete_channel(channel) if delete_this: await matchdb.register_match_channel(match_id,",
"'Next match: \\n' for match in match_list: # noinspection PyUnresolvedReferences display_text += '\\N{BULLET}",
"can be. (If is_best_of is True, then the match is a best of",
"Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) # display_text += ' RTMP: {} \\n'.format(",
"MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel, new_room) await new_room.initialize() return new_room async def close_match_room(match: Match) ->",
"from necrobot.botbase.necrobot import Necrobot from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from necrobot.match.match import Match from",
"None: return await make_match_from_raw_db_data(raw_data) else: return None def get_matchroom_name(match: Match) -> str: \"\"\"Get",
"of max_races; otherwise, the match is just repeating max_races.) match_id: int The DB",
"False for channel in server.server.channels: if channel.name.startswith(name_prefix): found = True try: val =",
"be written to a log file before deletion. completed_only: bool If True, will",
"r2_unconfirmed: bool Whether the second racer wishes to unconfirm the match time. match_info:",
"find channels for. If None, finds all channeled matches. Returns ------- list[Match] A",
"largest_postfix + 1) async def get_upcoming_and_current() -> list: \"\"\" Returns ------- list[Match] A",
"except ValueError: pass return name_prefix if not found else '{0}-{1}'.format(name_prefix, largest_postfix + 1)",
"None if match_id in match_library: return match_library[match_id] raw_data = await matchdb.get_raw_match_data(match_id) if raw_data",
"import Necrobot from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from necrobot.match.match import Match from necrobot.match.matchinfo import",
"return display_text async def delete_match(match_id: int) -> None: await matchdb.delete_match(match_id=match_id) if match_id in",
"Optional[Match] The match found, if any. \"\"\" if match_id is None: return None",
"None) -> list: \"\"\" Parameters ---------- racer: NecroUser The racer to find channels",
"room for. register: bool If True, will register the Match in the database.",
"of all upcoming and ongoing matches, in order. \"\"\" matches = [] for",
"not match.is_registered: if register: await match.commit() else: console.warning('Tried to make a MatchRoom for",
"is not None: if completed_only: match_room = Necrobot().get_bot_channel(channel) if match_room is None or",
"import Config match_library = {} # noinspection PyIncorrectDocstring async def make_match(*args, register=False, **kwargs)",
"\\n' for match in match_list: # noinspection PyUnresolvedReferences display_text += '\\N{BULLET} **{0}** -",
"for channel in server.server.channels: if channel.name.startswith(name_prefix): found = True try: val = int(channel.name[cut_length:])",
"types of races to be run in this match. cawmentator_id: int The DB",
"await make_match_from_raw_db_data(row=row) if match.suggested_time is None: console.warning('Found match object {} has no suggested",
"match_room.during_races(): matches.append(match) return matches async def get_matches_with_channels(racer: NecroUser = None) -> list: \"\"\"",
"any. Parameters ---------- match: Match The Match to close the channel for. \"\"\"",
"---------- match: Match The Match to create a room for. register: bool If",
"match_cawmentator is not None: display_text += ' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif match.racer_1.twitch_name is",
"close the room for an unregistered match.') return channel_id = match.channel_id channel =",
"database. Returns ------- Optional[MatchRoom] The created room object. \"\"\" # Check to see",
"the worksheet the match was created from, if any. register: bool Whether to",
"continue if match.suggested_time > pytz.utc.localize(datetime.datetime.utcnow()): matches.append(match) else: match_room = Necrobot().get_bot_channel(channel) if match_room is",
"necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from necrobot.match.match import Match from necrobot.match.matchinfo import MatchInfo from necrobot.match.matchroom",
"match in matches: max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text =",
"timestr, writechannel, strutil, rtmputil from necrobot.botbase.necrobot import Necrobot from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from",
"make_match_room(match: Match, register=False) -> MatchRoom or None: \"\"\"Create a discord.Channel and a corresponding",
"= row[14] sheet_info.row = row[15] new_match = Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]),",
"None: display_text += ' Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) # display_text +=",
"w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if match.suggested_time - utcnow < datetime.timedelta(minutes=0): schedule_text += 'Right",
"matchdb.get_channeled_matches_raw_data( must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id ) else: raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row",
"the second racer. max_races: int The maximum number of races this match can",
"match time. r2_confirmed: bool Whether the second racer has confirmed the match time.",
"if row[13] is not None else None, gsheet_info=sheet_info ) await new_match.initialize() match_library[new_match.match_id] =",
"racedb.get_race_info_from_type_id(int(row[1])) if row[1] is not None else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]), max_races=int(row[11]) ) sheet_info",
"match.get_cawmentator() if match_cawmentator is not None: display_text += ' Cawmentary: <http://www.twitch.tv/{0}> \\n'.format(match_cawmentator.twitch_name) elif",
"await server.client.delete_channel(channel) if delete_this: await matchdb.register_match_channel(match_id, None) async def make_match_room(match: Match, register=False) ->",
"0 max_r2_len = 0 for match in matches: max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len",
"bool Whether the first racer wishes to unconfirm the match time. r2_unconfirmed: bool",
"not None: display_text += ' Kadgar: {} \\n'.format( rtmputil.kadgar_link(match.racer_1.twitch_name, match.racer_2.twitch_name) ) # display_text",
"raw_data = await matchdb.get_raw_match_data(match_id) if raw_data is not None: return await make_match_from_raw_db_data(raw_data) else:",
"= int(row[13]) if row[13] is not None else None if channel_id is not",
"int The sheetID of the worksheet the match was created from, if any.",
"match: Match The match whose info determines the name. Returns ------- str The",
"channel in server.server.channels: if channel.name.startswith(name_prefix): found = True try: val = int(channel.name[cut_length:]) largest_postfix",
"= max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text = '``` \\nUpcoming matches: \\n' for match in matches:",
"import discord import pytz from necrobot.botbase import server, discordutil from necrobot.database import matchdb,",
"[] for row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id = int(row[13]) if row[13] is",
"a match object from its DB unique ID. Parameters ---------- match_id: int The",
"r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if match.suggested_time - utcnow < datetime.timedelta(minutes=0): schedule_text += 'Right now!'",
"match.racer_2.rtmp_name) # ) display_text += '\\nFull schedule: <https://condor.host/schedule>' return display_text async def delete_match(match_id:",
"The name of the channel. \"\"\" name_prefix = match.matchroom_name cut_length = len(name_prefix) +",
"MatchInfo from necrobot.match.matchroom import MatchRoom from necrobot.race.raceinfo import RaceInfo from necrobot.user.necrouser import NecroUser",
"the first racer. racer_2_id: int The DB user ID of the second racer.",
"if match_id is None: return None if match_id in match_library: return match_library[match_id] raw_data",
"The match whose info determines the name. Returns ------- str The name of",
"from necrobot.match.matchinfo import MatchInfo from necrobot.match.matchroom import MatchRoom from necrobot.race.raceinfo import RaceInfo from",
"to see the match is registered if not match.is_registered: if register: await match.commit()",
"it didn't exist, make a new one if match_channel is None: # Create",
"Whether the second racer has confirmed the match time. r1_unconfirmed: bool Whether the",
"match time. r2_unconfirmed: bool Whether the second racer wishes to unconfirm the match",
"discord.Channel corresponding to the Match, if any. Parameters ---------- match: Match The Match",
"must_be_scheduled=False, order_by_time=False, racer_id=racer.user_id ) else: raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row in",
"# noinspection PyUnresolvedReferences match_channel = await server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read),",
"if raw_data is not None: return await make_match_from_raw_db_data(raw_data) else: return None def get_matchroom_name(match:",
"val = int(channel.name[cut_length:]) largest_postfix = max(largest_postfix, val) except ValueError: pass return name_prefix if",
"+ 1) async def get_upcoming_and_current() -> list: \"\"\" Returns ------- list[Match] A list",
"not None and match.racer_2.twitch_name is not None: display_text += ' Kadgar: {} \\n'.format(",
"not None else None if channel_id is not None: channel = server.find_channel(channel_id=channel_id) if",
"Necrobot().get_bot_channel(channel) if match_room is not None and await match_room.during_races(): matches.append(match) return matches async",
"the match channel channel_id = match.channel_id match_channel = server.find_channel(channel_id=channel_id) if channel_id is not",
"have associated channels on the server featuring the specified racer. \"\"\" matches =",
"match_list: # noinspection PyUnresolvedReferences display_text += '\\N{BULLET} **{0}** - **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if",
"= 'Next match: \\n' for match in match_list: # noinspection PyUnresolvedReferences display_text +=",
"return new_match async def get_schedule_infotext(): utcnow = pytz.utc.localize(datetime.datetime.utcnow()) matches = await get_upcoming_and_current() max_r1_len",
"order_by_time=False) for row in raw_data: channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) if channel",
"def get_matchroom_name(match: Match) -> str: \"\"\"Get a new unique channel name corresponding to",
"if any. Parameters ---------- match: Match The Match to close the channel for.",
"0 for match in matches: max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name)))",
"int(row[0]) if match_id in match_library: return match_library[match_id] match_info = MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if",
"max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text = '``` \\nUpcoming matches: \\n' for match in matches: if",
"to make a MatchRoom for an unregistered Match ({0}).'.format(match.matchroom_name)) return None # Check",
"to interact with the database. Parameters ---------- racer_1_id: int The DB user ID",
"second racer. max_races: int The maximum number of races this match can be.",
"create a room for. register: bool If True, will register the Match in",
"match_library: return match_library[match_id] raw_data = await matchdb.get_raw_match_data(match_id) if raw_data is not None: return",
"racer.member is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read)) # Make a channel for the room",
"PyIncorrectDocstring async def make_match(*args, register=False, **kwargs) -> Match: \"\"\"Create a Match object. There",
"display_text += '\\n' continue display_text += ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True)) match_cawmentator",
"' '(match_id={1}).'.format(channel_id, match.match_id)) return await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None) async def get_nextrace_displaytext(match_list: list)",
"None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make the actual RaceRoom and initialize it match.set_channel_id(int(match_channel.id))",
"None: if completed_only: match_room = Necrobot().get_bot_channel(channel) if match_room is None or not match_room.played_all_races:",
"match_library = {} # noinspection PyIncorrectDocstring async def make_match(*args, register=False, **kwargs) -> Match:",
"order_by_time=False, racer_id=racer.user_id ) else: raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row in raw_data:",
"Match, if any. Parameters ---------- match: Match The Match to close the channel",
"is not None: return await make_match_from_raw_db_data(raw_data) else: return None def get_matchroom_name(match: Match) ->",
"of the second racer. max_races: int The maximum number of races this match",
"else: raw_data = await matchdb.get_channeled_matches_raw_data(must_be_scheduled=False, order_by_time=False) for row in raw_data: channel_id = int(row[13])",
"import datetime import discord import pytz from necrobot.botbase import server, discordutil from necrobot.database",
"the channel for. \"\"\" if not match.is_registered: console.warning('Trying to close the room for",
"matches = [] if racer is not None: raw_data = await matchdb.get_channeled_matches_raw_data( must_be_scheduled=False,",
"= {} # noinspection PyIncorrectDocstring async def make_match(*args, register=False, **kwargs) -> Match: \"\"\"Create",
"def get_upcoming_and_current() -> list: \"\"\" Returns ------- list[Match] A list of all upcoming",
"def close_match_room(match: Match) -> None: \"\"\"Close the discord.Channel corresponding to the Match, if",
"return await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None) async def get_nextrace_displaytext(match_list: list) -> str: utcnow",
"Whether the first racer has confirmed the match time. r2_confirmed: bool Whether the",
"await Necrobot().unregister_bot_channel(channel) await server.client.delete_channel(channel) match.set_channel_id(None) async def get_nextrace_displaytext(match_list: list) -> str: utcnow =",
"= [] for racer in match.racers: if racer.member is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member, overwrite=permit_read))",
"if channel_id is not None else None # If we couldn't find the",
"= max(largest_postfix, val) except ValueError: pass return name_prefix if not found else '{0}-{1}'.format(name_prefix,",
"+= '\\nFull schedule: <https://condor.host/schedule>' return display_text async def delete_match(match_id: int) -> None: await",
"confirmed the match time. r2_confirmed: bool Whether the second racer has confirmed the",
"Make the actual RaceRoom and initialize it match.set_channel_id(int(match_channel.id)) new_room = MatchRoom(match_discord_channel=match_channel, match=match) Necrobot().register_bot_channel(match_channel,",
"then the match is a best of max_races; otherwise, the match is just",
"async def close_match_room(match: Match) -> None: \"\"\"Close the discord.Channel corresponding to the Match,",
"def make_match_from_raw_db_data(row: list) -> Match: match_id = int(row[0]) if match_id in match_library: return",
"registered if not match.is_registered: if register: await match.commit() else: console.warning('Tried to make a",
"pytz from necrobot.botbase import server, discordutil from necrobot.database import matchdb, racedb from necrobot.util",
"the database. Returns --------- Match The created match. \"\"\" if 'match_id' in kwargs",
"in order. \"\"\" matches = [] for row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True): channel_id",
"from, if any. register: bool Whether to register the match in the database.",
"PyUnresolvedReferences display_text += '\\N{BULLET} **{0}** - **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time is None:",
"in match_library: return match_library[match_id] match_info = MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1] is not",
"+= '{r1:>{w1}} v {r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len ) if match.suggested_time",
"return match_library[kwargs['match_id']] match = Match(*args, commit_fn=matchdb.write_match, **kwargs) await match.initialize() if register: await match.commit()",
"only find completed matches. \"\"\" for row in await matchdb.get_channeled_matches_raw_data(): match_id = int(row[0])",
"match.channel_id match_channel = server.find_channel(channel_id=channel_id) if channel_id is not None else None # If",
"suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]), r1_unconfirmed=bool(row[7]), r2_unconfirmed=bool(row[8]), cawmentator_id=row[12], channel_id=int(row[13]) if row[13] is not None",
"= MatchInfo( race_info=await racedb.get_race_info_from_type_id(int(row[1])) if row[1] is not None else RaceInfo(), ranked=bool(row[9]), is_best_of=bool(row[10]),",
"of the channel. \"\"\" name_prefix = match.matchroom_name cut_length = len(name_prefix) + 1 largest_postfix",
"Match. Parameters ---------- match: Match The Match to create a room for. register:",
"matches: if len(schedule_text) > 1800: break schedule_text += '{r1:>{w1}} v {r2:<{w2}} : '.format(",
"= True try: val = int(channel.name[cut_length:]) largest_postfix = max(largest_postfix, val) except ValueError: pass",
"have the match channel channel_id = match.channel_id match_channel = server.find_channel(channel_id=channel_id) if channel_id is",
"match. Returns ------- Optional[Match] The match found, if any. \"\"\" if match_id is",
"the channel. \"\"\" name_prefix = match.matchroom_name cut_length = len(name_prefix) + 1 largest_postfix =",
"found = True try: val = int(channel.name[cut_length:]) largest_postfix = max(largest_postfix, val) except ValueError:",
"find this channel.'.format(channel_id)) return matches async def delete_all_match_channels(log=False, completed_only=False) -> None: \"\"\"Delete all",
"to close the channel for. \"\"\" if not match.is_registered: console.warning('Trying to close the",
"from necrobot.util import console, timestr, writechannel, strutil, rtmputil from necrobot.botbase.necrobot import Necrobot from",
"None: await matchdb.delete_match(match_id=match_id) if match_id in match_library: del match_library[match_id] async def make_match_from_raw_db_data(row: list)",
"to a log file before deletion. completed_only: bool If True, will only find",
"There should be no need to call this directly; use matchutil.make_match instead, since",
"1800: break schedule_text += '{r1:>{w1}} v {r2:<{w2}} : '.format( r1=strutil.tickless(match.racer_1.display_name), w1=max_r1_len, r2=strutil.tickless(match.racer_2.display_name), w2=max_r2_len",
"if match_channel_category is not None: await discordutil.set_channel_category(channel=match_channel, category=match_channel_category) # Make the actual RaceRoom",
"match.') return channel_id = match.channel_id channel = server.find_channel(channel_id=channel_id) if channel is None: console.warning('Coudn\\'t",
"display_text += '\\nFull schedule: <https://condor.host/schedule>' return display_text async def delete_match(match_id: int) -> None:",
"schedule_text += '\\n' schedule_text += '```' return schedule_text async def get_race_data(match: Match): return",
"delete_all_match_channels(log=False, completed_only=False) -> None: \"\"\"Delete all match channels from the server. Parameters ----------",
"match found, if any. \"\"\" if match_id is None: return None if match_id",
"for. \"\"\" if not match.is_registered: console.warning('Trying to close the room for an unregistered",
"server.client.delete_channel(channel) match.set_channel_id(None) async def get_nextrace_displaytext(match_list: list) -> str: utcnow = pytz.utc.localize(datetime.datetime.utcnow()) if len(match_list)",
"necrobot.user.necrouser import NecroUser from necrobot.config import Config match_library = {} # noinspection PyIncorrectDocstring",
"to create a room for. register: bool If True, will register the Match",
"channel for the room # noinspection PyUnresolvedReferences match_channel = await server.client.create_channel( server.server, get_matchroom_name(match),",
"------- list[Match] A list of all upcoming and ongoing matches, in order. \"\"\"",
"is not None: match = await make_match_from_raw_db_data(row=row) if match.suggested_time is None: console.warning('Found match",
"rtmputil from necrobot.botbase.necrobot import Necrobot from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from necrobot.match.match import Match",
"Necrobot from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from necrobot.match.match import Match from necrobot.match.matchinfo import MatchInfo",
"created room object. \"\"\" # Check to see the match is registered if",
"True, will only find completed matches. \"\"\" for row in await matchdb.get_channeled_matches_raw_data(): match_id",
"is not None and await match_room.during_races(): matches.append(match) return matches async def get_matches_with_channels(racer: NecroUser",
"or not match_room.played_all_races: delete_this = False if delete_this: if log: await writechannel.write_channel( client=server.client,",
"If we couldn't find the channel or it didn't exist, make a new",
"async def get_matches_with_channels(racer: NecroUser = None) -> list: \"\"\" Parameters ---------- racer: NecroUser",
"DB user ID of the first racer. racer_2_id: int The DB user ID",
"int The databse ID of the match. Returns ------- Optional[Match] The match found,",
"async def delete_all_match_channels(log=False, completed_only=False) -> None: \"\"\"Delete all match channels from the server.",
"channel = server.find_channel(channel_id=channel_id) if channel is not None: match = await make_match_from_raw_db_data(row=row) matches.append(match)",
"Match, register=False) -> MatchRoom or None: \"\"\"Create a discord.Channel and a corresponding MatchRoom",
"for match in matches: max_r1_len = max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text",
"server.find_channel(channel_id=channel_id) if channel is None: console.warning('Coudn\\'t find channel with id {0} in close_match_room",
"rtmputil.rtmp_link(match.racer_1.rtmp_name, match.racer_2.rtmp_name) # ) display_text += '\\nFull schedule: <https://condor.host/schedule>' return display_text async def",
"None: console.warning('Coudn\\'t find channel with id {0} in close_match_room ' '(match_id={1}).'.format(channel_id, match.match_id)) return",
"discord import pytz from necrobot.botbase import server, discordutil from necrobot.database import matchdb, racedb",
"def delete_all_match_channels(log=False, completed_only=False) -> None: \"\"\"Delete all match channels from the server. Parameters",
"match. suggested_time: datetime.datetime The time the match is suggested for. If no tzinfo,",
"row[15] new_match = Match( commit_fn=matchdb.write_match, match_id=match_id, match_info=match_info, racer_1_id=int(row[2]), racer_2_id=int(row[3]), suggested_time=row[4], finish_time=row[16], r1_confirmed=bool(row[5]), r2_confirmed=bool(row[6]),",
"return matches async def delete_all_match_channels(log=False, completed_only=False) -> None: \"\"\"Delete all match channels from",
"list of all Matches that have associated channels on the server featuring the",
"channel. \"\"\" name_prefix = match.matchroom_name cut_length = len(name_prefix) + 1 largest_postfix = 1",
"is not None else None if channel_id is not None: channel = server.find_channel(channel_id=channel_id)",
"the channel or it didn't exist, make a new one if match_channel is",
"match. sheet_id: int The sheetID of the worksheet the match was created from,",
"return None if match_id in match_library: return match_library[match_id] raw_data = await matchdb.get_raw_match_data(match_id) if",
"from necrobot.race.raceinfo import RaceInfo from necrobot.user.necrouser import NecroUser from necrobot.config import Config match_library",
"match: Match The Match to create a room for. register: bool If True,",
"from necrobot.gsheet.matchgsheetinfo import MatchGSheetInfo from necrobot.match.match import Match from necrobot.match.matchinfo import MatchInfo from",
"unique ID of this match. suggested_time: datetime.datetime The time the match is suggested",
"\"\"\" Parameters ---------- racer: NecroUser The racer to find channels for. If None,",
"< datetime.timedelta(minutes=0): schedule_text += 'Right now!' else: schedule_text += timestr.str_full_24h(match.suggested_time) schedule_text += '\\n'",
"racer_permissions = [] for racer in match.racers: if racer.member is not None: racer_permissions.append(discord.ChannelPermissions(target=racer.member,",
"from necrobot.config import Config match_library = {} # noinspection PyIncorrectDocstring async def make_match(*args,",
"be run in this match. cawmentator_id: int The DB unique ID of the",
"continue display_text += ': {0} \\n'.format(timestr.timedelta_to_str(match.suggested_time - utcnow, punctuate=True)) match_cawmentator = await match.get_cawmentator()",
"**kwargs) await match.initialize() if register: await match.commit() match_library[match.match_id] = match return match async",
"the Match, if any. Parameters ---------- match: Match The Match to close the",
"else: console.warning('Tried to make a MatchRoom for an unregistered Match ({0}).'.format(match.matchroom_name)) return None",
"matches, in order. \"\"\" matches = [] for row in await matchdb.get_channeled_matches_raw_data(must_be_scheduled=True, order_by_time=True):",
"= max(max_r1_len, len(strutil.tickless(match.racer_1.display_name))) max_r2_len = max(max_r2_len, len(strutil.tickless(match.racer_2.display_name))) schedule_text = '``` \\nUpcoming matches: \\n'",
"Parameters ---------- match: Match The Match to create a room for. register: bool",
"from its DB unique ID. Parameters ---------- match_id: int The databse ID of",
"match.is_registered: if register: await match.commit() else: console.warning('Tried to make a MatchRoom for an",
"-> MatchRoom or None: \"\"\"Create a discord.Channel and a corresponding MatchRoom for the",
"room # noinspection PyUnresolvedReferences match_channel = await server.client.create_channel( server.server, get_matchroom_name(match), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me,",
"whose info determines the name. Returns ------- str The name of the channel.",
"**{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time is None: display_text += '\\n' continue display_text +=",
"register the match in the database. Returns --------- Match The created match. \"\"\"",
"make a match channel.') return None # Put the match channel in the",
"for match in matches: if len(schedule_text) > 1800: break schedule_text += '{r1:>{w1}} v",
"match channels from the server. Parameters ---------- log: bool If True, the channel",
"- **{1}**'.format( match.racer_1.display_name, match.racer_2.display_name) if match.suggested_time is None: display_text += '\\n' continue display_text"
] |
[
"# Keras won't let us multiply floats by booleans, so we explicitly cast",
"2 Conv1D then 2 Fully def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model =",
"huber_loss}) model = load_model(model_path) print('Load existing model.') else: model = Sequential() model.add(Dense(InputHandler.input_size *",
"so we explicitly cast the booleans to floats use_linear_term = K.cast(use_linear_term, 'float32') return",
"activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size,",
"W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer = RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer = Nadam(lr=0.002, beta_1=0.9,",
"we explicitly cast the booleans to floats use_linear_term = K.cast(use_linear_term, 'float32') return use_linear_term",
"K from keras.losses import mean_squared_error from sljassbot.player.rl_player.input_handler import InputHandler def huber_loss(a, b, in_keras=True):",
"sljassbot.player.rl_player.input_handler import InputHandler def huber_loss(a, b, in_keras=True): error = a - b quadratic_term",
"model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear'))",
"use_linear_term) * quadratic_term ''' def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path,",
"''' # TODO: first 2 Conv1D then 2 Fully def build_model(model_path, learning_rate=0.01): if",
"activation='linear')) # optimizer = RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None,",
"model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new model.') return model ''' # TODO: first 2 Conv1D",
"load_model(model_path) print('Load existing model.') else: model = Sequential() model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01)))",
"#model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same', activation='relu'))",
"os.path from keras.layers import Dense, Flatten, Conv1D, Reshape from keras.optimizers import Nadam from",
"floats use_linear_term = K.cast(use_linear_term, 'float32') return use_linear_term * linear_term + (1 - use_linear_term)",
"use_linear_term = (abs(error) > 1.0) if in_keras: # Keras won't let us multiply",
"- use_linear_term) * quadratic_term ''' def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model =",
"input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten())",
"import l2 from keras import backend as K from keras.losses import mean_squared_error from",
"build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss': huber_loss}) model = load_model(model_path)",
"return use_linear_term * linear_term + (1 - use_linear_term) * quadratic_term ''' def build_model(model_path,",
"= K.cast(use_linear_term, 'float32') return use_linear_term * linear_term + (1 - use_linear_term) * quadratic_term",
"1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50,",
"in_keras=True): error = a - b quadratic_term = error * error / 2",
"# model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new model.') return model ''' # TODO:",
"import os.path from keras.layers import Dense, Flatten, Conv1D, Reshape from keras.optimizers import Nadam",
"K.cast(use_linear_term, 'float32') return use_linear_term * linear_term + (1 - use_linear_term) * quadratic_term '''",
"* 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9,",
"linear_term + (1 - use_linear_term) * quadratic_term ''' def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path):",
"return model ''' # TODO: first 2 Conv1D then 2 Fully def build_model(model_path,",
"existing model.') else: model = Sequential() model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size *",
"model = Sequential() model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size",
"import backend as K from keras.losses import mean_squared_error from sljassbot.player.rl_player.input_handler import InputHandler def",
"Keras won't let us multiply floats by booleans, so we explicitly cast the",
"def huber_loss(a, b, in_keras=True): error = a - b quadratic_term = error *",
"(1 - use_linear_term) * quadratic_term ''' def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model",
"model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size *",
"floats by booleans, so we explicitly cast the booleans to floats use_linear_term =",
"us multiply floats by booleans, so we explicitly cast the booleans to floats",
"model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9,",
"activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9,",
"= load_model(model_path) print('Load existing model.') else: model = Sequential() model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,),",
"+ (1 - use_linear_term) * quadratic_term ''' def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): #",
"activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer = RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer = Nadam(lr=0.002,",
"strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same', activation='relu'))",
"padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten())",
"/ 2 use_linear_term = (abs(error) > 1.0) if in_keras: # Keras won't let",
"print('Load existing model.') else: model = Sequential() model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size",
"import load_model from keras.regularizers import l2 from keras import backend as K from",
"b, in_keras=True): error = a - b quadratic_term = error * error /",
"# optimizer = RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004)",
"Sequential from keras.models import load_model from keras.regularizers import l2 from keras import backend",
"strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu',",
"2 use_linear_term = (abs(error) > 1.0) if in_keras: # Keras won't let us",
"cast the booleans to floats use_linear_term = K.cast(use_linear_term, 'float32') return use_linear_term * linear_term",
"a - b quadratic_term = error * error / 2 linear_term = abs(error)",
"model = load_model(model_path, custom_objects={'huber_loss': huber_loss}) model = load_model(model_path) print('Load existing model.') else: model",
"activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36,",
"import InputHandler def huber_loss(a, b, in_keras=True): error = a - b quadratic_term =",
"explicitly cast the booleans to floats use_linear_term = K.cast(use_linear_term, 'float32') return use_linear_term *",
"strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu',",
"Nadam from keras.models import Sequential from keras.models import load_model from keras.regularizers import l2",
"* error / 2 linear_term = abs(error) - 1 / 2 use_linear_term =",
"use_linear_term = K.cast(use_linear_term, 'float32') return use_linear_term * linear_term + (1 - use_linear_term) *",
"schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new model.') return model ''' #",
"optimizer = RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004) #",
"l2 from keras import backend as K from keras.losses import mean_squared_error from sljassbot.player.rl_player.input_handler",
"* 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same',",
"= a - b quadratic_term = error * error / 2 linear_term =",
"model ''' # TODO: first 2 Conv1D then 2 Fully def build_model(model_path, learning_rate=0.01):",
"activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size",
"* 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same',",
"= abs(error) - 1 / 2 use_linear_term = (abs(error) > 1.0) if in_keras:",
"kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same',",
"model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9,",
"linear_term = abs(error) - 1 / 2 use_linear_term = (abs(error) > 1.0) if",
"model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18,",
"Flatten, Conv1D, Reshape from keras.optimizers import Nadam from keras.models import Sequential from keras.models",
"Dense, Flatten, Conv1D, Reshape from keras.optimizers import Nadam from keras.models import Sequential from",
"> 1.0) if in_keras: # Keras won't let us multiply floats by booleans,",
"os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss': huber_loss}) model = load_model(model_path) print('Load existing model.')",
"* 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9,",
"= Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new",
"TODO: first 2 Conv1D then 2 Fully def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): #",
"then 2 Fully def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss':",
"padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu', W_regularizer=l2(0.01)))",
"strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu'))",
"1 / 2 use_linear_term = (abs(error) > 1.0) if in_keras: # Keras won't",
"from sljassbot.player.rl_player.input_handler import InputHandler def huber_loss(a, b, in_keras=True): error = a - b",
"huber_loss(a, b, in_keras=True): error = a - b quadratic_term = error * error",
"2 Fully def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss': huber_loss})",
"2 linear_term = abs(error) - 1 / 2 use_linear_term = (abs(error) > 1.0)",
"# TODO: first 2 Conv1D then 2 Fully def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path):",
"keras.models import load_model from keras.regularizers import l2 from keras import backend as K",
"from keras.layers import Dense, Flatten, Conv1D, Reshape from keras.optimizers import Nadam from keras.models",
"import Nadam from keras.models import Sequential from keras.models import load_model from keras.regularizers import",
"- 1 / 2 use_linear_term = (abs(error) > 1.0) if in_keras: # Keras",
"use_linear_term * linear_term + (1 - use_linear_term) * quadratic_term ''' def build_model(model_path, learning_rate=0.01):",
"else: model = Sequential() model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,),",
"beta_2=0.999, epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new model.') return model",
"b quadratic_term = error * error / 2 linear_term = abs(error) - 1",
"epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new model.') return model '''",
"keras.optimizers import Nadam from keras.models import Sequential from keras.models import load_model from keras.regularizers",
"= error * error / 2 linear_term = abs(error) - 1 / 2",
"Conv1D, Reshape from keras.optimizers import Nadam from keras.models import Sequential from keras.models import",
"kernel_size=36, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2,",
"import os import os.path from keras.layers import Dense, Flatten, Conv1D, Reshape from keras.optimizers",
"from keras.regularizers import l2 from keras import backend as K from keras.losses import",
"if in_keras: # Keras won't let us multiply floats by booleans, so we",
"activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size",
"* 2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer = RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer",
"to floats use_linear_term = K.cast(use_linear_term, 'float32') return use_linear_term * linear_term + (1 -",
"import mean_squared_error from sljassbot.player.rl_player.input_handler import InputHandler def huber_loss(a, b, in_keras=True): error = a",
"''' def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss': huber_loss}) model",
"model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer = RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999,",
"new model.') return model ''' # TODO: first 2 Conv1D then 2 Fully",
"model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer = RMSprop(lr=0.00025, rho=0.95,",
"keras import backend as K from keras.losses import mean_squared_error from sljassbot.player.rl_player.input_handler import InputHandler",
"as K from keras.losses import mean_squared_error from sljassbot.player.rl_player.input_handler import InputHandler def huber_loss(a, b,",
"* 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,),",
"* quadratic_term ''' def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss':",
"activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer = RMSprop(lr=0.00025,",
"Sequential() model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size * 2,)))",
"model.') else: model = Sequential() model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2,",
"print('Create new model.') return model ''' # TODO: first 2 Conv1D then 2",
"first 2 Conv1D then 2 Fully def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model",
"input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50,",
"backend as K from keras.losses import mean_squared_error from sljassbot.player.rl_player.input_handler import InputHandler def huber_loss(a,",
"in_keras: # Keras won't let us multiply floats by booleans, so we explicitly",
"2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same', activation='relu'))",
"from keras import backend as K from keras.losses import mean_squared_error from sljassbot.player.rl_player.input_handler import",
"2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same',",
"from keras.losses import mean_squared_error from sljassbot.player.rl_player.input_handler import InputHandler def huber_loss(a, b, in_keras=True): error",
"load_model(model_path, custom_objects={'huber_loss': huber_loss}) model = load_model(model_path) print('Load existing model.') else: model = Sequential()",
"booleans to floats use_linear_term = K.cast(use_linear_term, 'float32') return use_linear_term * linear_term + (1",
"from keras.models import Sequential from keras.models import load_model from keras.regularizers import l2 from",
"input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50,",
"(abs(error) > 1.0) if in_keras: # Keras won't let us multiply floats by",
"quadratic_term = error * error / 2 linear_term = abs(error) - 1 /",
"keras.models import Sequential from keras.models import load_model from keras.regularizers import l2 from keras",
"error = a - b quadratic_term = error * error / 2 linear_term",
"= load_model(model_path, custom_objects={'huber_loss': huber_loss}) model = load_model(model_path) print('Load existing model.') else: model =",
"input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18,",
"import Sequential from keras.models import load_model from keras.regularizers import l2 from keras import",
"keras.regularizers import l2 from keras import backend as K from keras.losses import mean_squared_error",
"keras.layers import Dense, Flatten, Conv1D, Reshape from keras.optimizers import Nadam from keras.models import",
"model = load_model(model_path) print('Load existing model.') else: model = Sequential() model.add(Dense(InputHandler.input_size * 2,",
"= Sequential() model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size *",
"= RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss,",
"epsilon=0.01) optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer)",
"activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9,",
"2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer = RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer =",
"mean_squared_error from sljassbot.player.rl_player.input_handler import InputHandler def huber_loss(a, b, in_keras=True): error = a -",
"# model = load_model(model_path, custom_objects={'huber_loss': huber_loss}) model = load_model(model_path) print('Load existing model.') else:",
"by booleans, so we explicitly cast the booleans to floats use_linear_term = K.cast(use_linear_term,",
"#model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu'))",
"error * error / 2 linear_term = abs(error) - 1 / 2 use_linear_term",
"1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25,",
"learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss': huber_loss}) model = load_model(model_path) print('Load",
"booleans, so we explicitly cast the booleans to floats use_linear_term = K.cast(use_linear_term, 'float32')",
"the booleans to floats use_linear_term = K.cast(use_linear_term, 'float32') return use_linear_term * linear_term +",
"kernel_size=18, strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2,",
"model.add(Dense(InputHandler.input_size * 2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer = RMSprop(lr=0.00025, rho=0.95, epsilon=0.01)",
"import Dense, Flatten, Conv1D, Reshape from keras.optimizers import Nadam from keras.models import Sequential",
"padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer =",
"Reshape from keras.optimizers import Nadam from keras.models import Sequential from keras.models import load_model",
"from keras.models import load_model from keras.regularizers import l2 from keras import backend as",
"optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new model.') return model ''' # TODO: first 2",
"activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18,",
"keras.losses import mean_squared_error from sljassbot.player.rl_player.input_handler import InputHandler def huber_loss(a, b, in_keras=True): error =",
"multiply floats by booleans, so we explicitly cast the booleans to floats use_linear_term",
"RMSprop(lr=0.00025, rho=0.95, epsilon=0.01) optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer)",
"optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create",
"load_model from keras.regularizers import l2 from keras import backend as K from keras.losses",
"quadratic_term ''' def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss': huber_loss})",
"optimizer=optimizer) print('Create new model.') return model ''' # TODO: first 2 Conv1D then",
"1.0) if in_keras: # Keras won't let us multiply floats by booleans, so",
"model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9,",
"def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss': huber_loss}) model =",
"let us multiply floats by booleans, so we explicitly cast the booleans to",
"padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=18, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25,",
"model.add(Dense(InputHandler.input_size * 2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size,",
"model.') return model ''' # TODO: first 2 Conv1D then 2 Fully def",
"input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9,",
"beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new model.') return",
"2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same',",
"= (abs(error) > 1.0) if in_keras: # Keras won't let us multiply floats",
"InputHandler def huber_loss(a, b, in_keras=True): error = a - b quadratic_term = error",
"kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) #",
"model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new model.') return model ''' # TODO: first",
"if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss': huber_loss}) model = load_model(model_path) print('Load existing",
"Fully def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path, custom_objects={'huber_loss': huber_loss}) model",
"abs(error) - 1 / 2 use_linear_term = (abs(error) > 1.0) if in_keras: #",
"from keras.optimizers import Nadam from keras.models import Sequential from keras.models import load_model from",
"custom_objects={'huber_loss': huber_loss}) model = load_model(model_path) print('Load existing model.') else: model = Sequential() model.add(Dense(InputHandler.input_size",
"os import os.path from keras.layers import Dense, Flatten, Conv1D, Reshape from keras.optimizers import",
"2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Conv1D(filters=50, kernel_size=9, strides=9, padding='same', activation='relu'))",
"kernel_size=18, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=50, kernel_size=36, strides=9, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same',",
"won't let us multiply floats by booleans, so we explicitly cast the booleans",
"2, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01))) model.add(Reshape((InputHandler.input_size * 2, 1,), input_shape=(InputHandler.input_size * 2,))) #model.add(Dense(InputHandler.input_size, input_shape=(InputHandler.input_size,), activation='relu',W_regularizer=l2(0.01)))",
"strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size * 2, activation='relu', W_regularizer=l2(0.01))) model.add(Dense(InputHandler.output_size, activation='linear')) # optimizer",
"error / 2 linear_term = abs(error) - 1 / 2 use_linear_term = (abs(error)",
"'float32') return use_linear_term * linear_term + (1 - use_linear_term) * quadratic_term ''' def",
"* linear_term + (1 - use_linear_term) * quadratic_term ''' def build_model(model_path, learning_rate=0.01): if",
"rho=0.95, epsilon=0.01) optimizer = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error,",
"Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004) # model.compile(loss=huber_loss, optimizer=optimizer) model.compile(loss=mean_squared_error, optimizer=optimizer) print('Create new model.')",
"- b quadratic_term = error * error / 2 linear_term = abs(error) -",
"Conv1D then 2 Fully def build_model(model_path, learning_rate=0.01): if os.path.exists(model_path): # model = load_model(model_path,",
"model.add(Conv1D(filters=50, kernel_size=18, strides=18, padding='same', activation='relu')) model.add(Conv1D(filters=25, kernel_size=9, strides=9, padding='same', activation='relu')) model.add(Flatten()) model.add(Dense(InputHandler.input_size *",
"/ 2 linear_term = abs(error) - 1 / 2 use_linear_term = (abs(error) >"
] |
[
"from periphery import GPIO, PWM, GPIOError def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency",
"= PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm try:",
"initPWM(1), initPWM(0), GPIO(77 , \"out\"), ] except GPIOError as e: print(\"Unable to access",
"__del__(self): if hasattr(self, \"_LEDs\"): for x in self._LEDs or [] + self._buttons or",
"sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self): if hasattr(self, \"_LEDs\"): for x in",
"reps=3): for i in range(reps): for i in range(5): self.setLED(i, True) time.sleep(0.05) self.setLED(i,",
"GPIO(7, \"in\"), GPIO(141, \"in\"), ] self._LEDs = [ initPWM(2), GPIO(73, \"out\"), initPWM(1), initPWM(0),",
"self).__init__() def __del__(self): if hasattr(self, \"_LEDs\"): for x in self._LEDs or [] +",
"\"out\"), ] except GPIOError as e: print(\"Unable to access GPIO pins. Did you",
"[]: x.close() def setLED(self, index, state): \"\"\"Abstracts away mix of GPIO and PWM",
"try: self._buttons = [ GPIO(6, \"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141, \"in\"),",
"def isButtonPressed(self, index): buttons = self.getButtonState() return buttons[index] def setLED(self, index, state): raise",
"= 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm try: self._buttons = [ GPIO(6,",
"e: print(\"Unable to access GPIO pins. Did you run with sudo ?\") sys.exit(1)",
"run with sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self): if hasattr(self, \"_LEDs\"): for",
"for i in range(5): self.setLED(i, True) time.sleep(0.05) self.setLED(i, False) class UI_EdgeTpuDevBoard(UI): def __init__(self):",
"def setLED(self, index, state): \"\"\"Abstracts away mix of GPIO and PWM LEDs.\"\"\" if",
"new: self._button_state[i] = False continue old = self._button_state[i] if ((t-self._button_state_last_change[i]) > self._debounce_interval) and",
"raise NotImplementedError() def getButtonState(self): raise NotImplementedError() def getDebouncedButtonState(self): t = time.time() for i,new",
"self.setLED(i, False) if index is not None: self.setLED(index, True) def isButtonPressed(self, index): buttons",
"seconds def setOnlyLED(self, index): for i in range(len(self._LEDs)): self.setLED(i, False) if index is",
"\"in\"), ] self._LEDs = [ initPWM(2), GPIO(73, \"out\"), initPWM(1), initPWM(0), GPIO(77 , \"out\"),",
"def __init__(self): global GPIO, PWM from periphery import GPIO, PWM, GPIOError def initPWM(pin):",
"GPIO pins. Did you run with sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self):",
"self._button_state[i] = False self._button_state_last_change[i] = t return self._button_state def testButtons(self, times): for t",
"i in range(reps): for i in range(5): self.setLED(i, True) time.sleep(0.05) self.setLED(i, False) class",
"not old: self._button_state[i] = True else: self._button_state[i] = False self._button_state_last_change[i] = t return",
"self._buttons] self._debounce_interval = 0.1 # seconds def setOnlyLED(self, index): for i in range(len(self._LEDs)):",
"self._debounce_interval) and not old: self._button_state[i] = True else: self._button_state[i] = False self._button_state_last_change[i] =",
"if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle = 1.0 if state else 0.0 def",
"you run with sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self): if hasattr(self, \"_LEDs\"):",
"raise NotImplementedError() def getDebouncedButtonState(self): t = time.time() for i,new in enumerate(self.getButtonState()): if not",
"index, state): \"\"\"Abstracts away mix of GPIO and PWM LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO):",
"continue old = self._button_state[i] if ((t-self._button_state_last_change[i]) > self._debounce_interval) and not old: self._button_state[i] =",
"__init__(self): global GPIO, PWM from periphery import GPIO, PWM, GPIOError def initPWM(pin): pwm",
"GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141, \"in\"), ] self._LEDs = [ initPWM(2), GPIO(73, \"out\"), initPWM(1),",
"] self._LEDs = [ initPWM(2), GPIO(73, \"out\"), initPWM(1), initPWM(0), GPIO(77 , \"out\"), ]",
"else: self._LEDs[index].duty_cycle = 1.0 if state else 0.0 def getButtonState(self): return [not button.read()",
"pwm.duty_cycle = 0 pwm.enable() return pwm try: self._buttons = [ GPIO(6, \"in\"), GPIO(138,",
"= time.time() self._button_state_last_change = [current_time for _ in self._buttons] self._debounce_interval = 0.1 #",
"Subclassed by specific board implementations.\"\"\" def __init__(self): self._button_state = [False for _ in",
"in enumerate(self.getButtonState()): if not new: self._button_state[i] = False continue old = self._button_state[i] if",
"None: self.setLED(index, True) def isButtonPressed(self, index): buttons = self.getButtonState() return buttons[index] def setLED(self,",
"for _ in self._buttons] current_time = time.time() self._button_state_last_change = [current_time for _ in",
"index is not None: self.setLED(index, True) def isButtonPressed(self, index): buttons = self.getButtonState() return",
"class UI(object): \"\"\"Abstract UI class. Subclassed by specific board implementations.\"\"\" def __init__(self): self._button_state",
"[current_time for _ in self._buttons] self._debounce_interval = 0.1 # seconds def setOnlyLED(self, index):",
"for i in range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \", \" \".join([str(i) for i,v in",
"\"\"\"Abstracts away mix of GPIO and PWM LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else:",
"return [not button.read() for button in self._buttons] if __name__== \"__main__\": ui = UI_EdgeTpuDevBoard()",
"specific board implementations.\"\"\" def __init__(self): self._button_state = [False for _ in self._buttons] current_time",
"] except GPIOError as e: print(\"Unable to access GPIO pins. Did you run",
"not None: self.setLED(index, True) def isButtonPressed(self, index): buttons = self.getButtonState() return buttons[index] def",
", \"out\"), ] except GPIOError as e: print(\"Unable to access GPIO pins. Did",
"setLED(self, index, state): \"\"\"Abstracts away mix of GPIO and PWM LEDs.\"\"\" if isinstance(self._LEDs[index],",
"def getButtonState(self): raise NotImplementedError() def getDebouncedButtonState(self): t = time.time() for i,new in enumerate(self.getButtonState()):",
"range(len(self._LEDs)): self.setLED(i, False) if index is not None: self.setLED(index, True) def isButtonPressed(self, index):",
"self._button_state[i] if ((t-self._button_state_last_change[i]) > self._debounce_interval) and not old: self._button_state[i] = True else: self._button_state[i]",
"self._button_state[i] = False continue old = self._button_state[i] if ((t-self._button_state_last_change[i]) > self._debounce_interval) and not",
"range(reps): for i in range(5): self.setLED(i, True) time.sleep(0.05) self.setLED(i, False) class UI_EdgeTpuDevBoard(UI): def",
"class UI_EdgeTpuDevBoard(UI): def __init__(self): global GPIO, PWM from periphery import GPIO, PWM, GPIOError",
"= t return self._button_state def testButtons(self, times): for t in range(0,times): for i",
"= 1.0 if state else 0.0 def getButtonState(self): return [not button.read() for button",
"i,v in enumerate(self.getButtonState()) if v])) time.sleep(0.01) def wiggleLEDs(self, reps=3): for i in range(reps):",
"t = time.time() for i,new in enumerate(self.getButtonState()): if not new: self._button_state[i] = False",
"False self._button_state_last_change[i] = t return self._button_state def testButtons(self, times): for t in range(0,times):",
"i in range(len(self._LEDs)): self.setLED(i, False) if index is not None: self.setLED(index, True) def",
"in range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \", \" \".join([str(i) for i,v in enumerate(self.getButtonState()) if",
"import GPIO, PWM, GPIOError def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency = 1e3",
"Did you run with sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self): if hasattr(self,",
"\"in\"), GPIO(141, \"in\"), ] self._LEDs = [ initPWM(2), GPIO(73, \"out\"), initPWM(1), initPWM(0), GPIO(77",
"for x in self._LEDs or [] + self._buttons or []: x.close() def setLED(self,",
"def setOnlyLED(self, index): for i in range(len(self._LEDs)): self.setLED(i, False) if index is not",
"\"\"\"Abstract UI class. Subclassed by specific board implementations.\"\"\" def __init__(self): self._button_state = [False",
"state): raise NotImplementedError() def getButtonState(self): raise NotImplementedError() def getDebouncedButtonState(self): t = time.time() for",
"for t in range(0,times): for i in range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \", \"",
"[] + self._buttons or []: x.close() def setLED(self, index, state): \"\"\"Abstracts away mix",
"getButtonState(self): raise NotImplementedError() def getDebouncedButtonState(self): t = time.time() for i,new in enumerate(self.getButtonState()): if",
"_ in self._buttons] current_time = time.time() self._button_state_last_change = [current_time for _ in self._buttons]",
"[ GPIO(6, \"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141, \"in\"), ] self._LEDs =",
"is not None: self.setLED(index, True) def isButtonPressed(self, index): buttons = self.getButtonState() return buttons[index]",
"self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle = 1.0 if state else 0.0 def getButtonState(self): return [not",
"True else: self._button_state[i] = False self._button_state_last_change[i] = t return self._button_state def testButtons(self, times):",
"def __init__(self): self._button_state = [False for _ in self._buttons] current_time = time.time() self._button_state_last_change",
"self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \", \" \".join([str(i) for i,v in enumerate(self.getButtonState()) if v])) time.sleep(0.01)",
"GPIO(77 , \"out\"), ] except GPIOError as e: print(\"Unable to access GPIO pins.",
"pins. Did you run with sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self): if",
"v])) time.sleep(0.01) def wiggleLEDs(self, reps=3): for i in range(reps): for i in range(5):",
"True) def isButtonPressed(self, index): buttons = self.getButtonState() return buttons[index] def setLED(self, index, state):",
"self._button_state_last_change[i] = t return self._button_state def testButtons(self, times): for t in range(0,times): for",
"self._LEDs[index].duty_cycle = 1.0 if state else 0.0 def getButtonState(self): return [not button.read() for",
"[not button.read() for button in self._buttons] if __name__== \"__main__\": ui = UI_EdgeTpuDevBoard() ui.wiggleLEDs()",
"= 0 pwm.enable() return pwm try: self._buttons = [ GPIO(6, \"in\"), GPIO(138, \"in\"),",
"hasattr(self, \"_LEDs\"): for x in self._LEDs or [] + self._buttons or []: x.close()",
"GPIO(141, \"in\"), ] self._LEDs = [ initPWM(2), GPIO(73, \"out\"), initPWM(1), initPWM(0), GPIO(77 ,",
"> self._debounce_interval) and not old: self._button_state[i] = True else: self._button_state[i] = False self._button_state_last_change[i]",
"PWM from periphery import GPIO, PWM, GPIOError def initPWM(pin): pwm = PWM(pin, 0)",
"time class UI(object): \"\"\"Abstract UI class. Subclassed by specific board implementations.\"\"\" def __init__(self):",
"in enumerate(self.getButtonState()) if v])) time.sleep(0.01) def wiggleLEDs(self, reps=3): for i in range(reps): for",
"range(5): self.setLED(i, True) time.sleep(0.05) self.setLED(i, False) class UI_EdgeTpuDevBoard(UI): def __init__(self): global GPIO, PWM",
"range(0,times): for i in range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \", \" \".join([str(i) for i,v",
"self._LEDs or [] + self._buttons or []: x.close() def setLED(self, index, state): \"\"\"Abstracts",
"if ((t-self._button_state_last_change[i]) > self._debounce_interval) and not old: self._button_state[i] = True else: self._button_state[i] =",
"self._buttons or []: x.close() def setLED(self, index, state): \"\"\"Abstracts away mix of GPIO",
"\"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141, \"in\"), ] self._LEDs = [ initPWM(2),",
"= [current_time for _ in self._buttons] self._debounce_interval = 0.1 # seconds def setOnlyLED(self,",
"setLED(self, index, state): raise NotImplementedError() def getButtonState(self): raise NotImplementedError() def getDebouncedButtonState(self): t =",
"return self._button_state def testButtons(self, times): for t in range(0,times): for i in range(5):",
"def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable()",
"pwm try: self._buttons = [ GPIO(6, \"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141,",
"self.isButtonPressed(i)) print(\"Buttons: \", \" \".join([str(i) for i,v in enumerate(self.getButtonState()) if v])) time.sleep(0.01) def",
"of GPIO and PWM LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle = 1.0",
"if hasattr(self, \"_LEDs\"): for x in self._LEDs or [] + self._buttons or []:",
"self._button_state = [False for _ in self._buttons] current_time = time.time() self._button_state_last_change = [current_time",
"sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self): if hasattr(self, \"_LEDs\"): for x in self._LEDs or",
"isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle = 1.0 if state else 0.0 def getButtonState(self):",
"if state else 0.0 def getButtonState(self): return [not button.read() for button in self._buttons]",
"((t-self._button_state_last_change[i]) > self._debounce_interval) and not old: self._button_state[i] = True else: self._button_state[i] = False",
"old: self._button_state[i] = True else: self._button_state[i] = False self._button_state_last_change[i] = t return self._button_state",
"= [False for _ in self._buttons] current_time = time.time() self._button_state_last_change = [current_time for",
"to access GPIO pins. Did you run with sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__()",
"import time class UI(object): \"\"\"Abstract UI class. Subclassed by specific board implementations.\"\"\" def",
"0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm try: self._buttons =",
"else: self._button_state[i] = False self._button_state_last_change[i] = t return self._button_state def testButtons(self, times): for",
"self._button_state[i] = True else: self._button_state[i] = False self._button_state_last_change[i] = t return self._button_state def",
"and not old: self._button_state[i] = True else: self._button_state[i] = False self._button_state_last_change[i] = t",
"by specific board implementations.\"\"\" def __init__(self): self._button_state = [False for _ in self._buttons]",
"pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm try: self._buttons = [",
"GPIO(6, \"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141, \"in\"), ] self._LEDs = [",
"+ self._buttons or []: x.close() def setLED(self, index, state): \"\"\"Abstracts away mix of",
"PWM LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle = 1.0 if state else",
"LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle = 1.0 if state else 0.0",
"testButtons(self, times): for t in range(0,times): for i in range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons:",
"def wiggleLEDs(self, reps=3): for i in range(reps): for i in range(5): self.setLED(i, True)",
"class. Subclassed by specific board implementations.\"\"\" def __init__(self): self._button_state = [False for _",
"for i,v in enumerate(self.getButtonState()) if v])) time.sleep(0.01) def wiggleLEDs(self, reps=3): for i in",
"import sys import time class UI(object): \"\"\"Abstract UI class. Subclassed by specific board",
"in self._LEDs or [] + self._buttons or []: x.close() def setLED(self, index, state):",
"False) class UI_EdgeTpuDevBoard(UI): def __init__(self): global GPIO, PWM from periphery import GPIO, PWM,",
"pwm.enable() return pwm try: self._buttons = [ GPIO(6, \"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7,",
"i,new in enumerate(self.getButtonState()): if not new: self._button_state[i] = False continue old = self._button_state[i]",
"= [ initPWM(2), GPIO(73, \"out\"), initPWM(1), initPWM(0), GPIO(77 , \"out\"), ] except GPIOError",
"\"_LEDs\"): for x in self._LEDs or [] + self._buttons or []: x.close() def",
"or []: x.close() def setLED(self, index, state): \"\"\"Abstracts away mix of GPIO and",
"# seconds def setOnlyLED(self, index): for i in range(len(self._LEDs)): self.setLED(i, False) if index",
"x in self._LEDs or [] + self._buttons or []: x.close() def setLED(self, index,",
"t in range(0,times): for i in range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \", \" \".join([str(i)",
"<gh_stars>0 import sys import time class UI(object): \"\"\"Abstract UI class. Subclassed by specific",
"GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle = 1.0 if state else 0.0 def getButtonState(self): return",
"state else 0.0 def getButtonState(self): return [not button.read() for button in self._buttons] if",
"= self.getButtonState() return buttons[index] def setLED(self, index, state): raise NotImplementedError() def getButtonState(self): raise",
"1e3 pwm.duty_cycle = 0 pwm.enable() return pwm try: self._buttons = [ GPIO(6, \"in\"),",
"return buttons[index] def setLED(self, index, state): raise NotImplementedError() def getButtonState(self): raise NotImplementedError() def",
"= 0.1 # seconds def setOnlyLED(self, index): for i in range(len(self._LEDs)): self.setLED(i, False)",
"def testButtons(self, times): for t in range(0,times): for i in range(5): self.setLED(i, self.isButtonPressed(i))",
"not new: self._button_state[i] = False continue old = self._button_state[i] if ((t-self._button_state_last_change[i]) > self._debounce_interval)",
"True) time.sleep(0.05) self.setLED(i, False) class UI_EdgeTpuDevBoard(UI): def __init__(self): global GPIO, PWM from periphery",
"GPIO, PWM, GPIOError def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle",
"in self._buttons] current_time = time.time() self._button_state_last_change = [current_time for _ in self._buttons] self._debounce_interval",
"GPIOError def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0",
"access GPIO pins. Did you run with sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def",
"away mix of GPIO and PWM LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle",
"time.sleep(0.01) def wiggleLEDs(self, reps=3): for i in range(reps): for i in range(5): self.setLED(i,",
"?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self): if hasattr(self, \"_LEDs\"): for x in self._LEDs",
"= True else: self._button_state[i] = False self._button_state_last_change[i] = t return self._button_state def testButtons(self,",
"i in range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \", \" \".join([str(i) for i,v in enumerate(self.getButtonState())",
"GPIO(73, \"out\"), initPWM(1), initPWM(0), GPIO(77 , \"out\"), ] except GPIOError as e: print(\"Unable",
"for i,new in enumerate(self.getButtonState()): if not new: self._button_state[i] = False continue old =",
"for i in range(reps): for i in range(5): self.setLED(i, True) time.sleep(0.05) self.setLED(i, False)",
"def setLED(self, index, state): raise NotImplementedError() def getButtonState(self): raise NotImplementedError() def getDebouncedButtonState(self): t",
"initPWM(0), GPIO(77 , \"out\"), ] except GPIOError as e: print(\"Unable to access GPIO",
"for _ in self._buttons] self._debounce_interval = 0.1 # seconds def setOnlyLED(self, index): for",
"def getButtonState(self): return [not button.read() for button in self._buttons] if __name__== \"__main__\": ui",
"initPWM(pin): pwm = PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return",
"x.close() def setLED(self, index, state): \"\"\"Abstracts away mix of GPIO and PWM LEDs.\"\"\"",
"in self._buttons] self._debounce_interval = 0.1 # seconds def setOnlyLED(self, index): for i in",
"sys import time class UI(object): \"\"\"Abstract UI class. Subclassed by specific board implementations.\"\"\"",
"GPIOError as e: print(\"Unable to access GPIO pins. Did you run with sudo",
"enumerate(self.getButtonState()): if not new: self._button_state[i] = False continue old = self._button_state[i] if ((t-self._button_state_last_change[i])",
"old = self._button_state[i] if ((t-self._button_state_last_change[i]) > self._debounce_interval) and not old: self._button_state[i] = True",
"\", \" \".join([str(i) for i,v in enumerate(self.getButtonState()) if v])) time.sleep(0.01) def wiggleLEDs(self, reps=3):",
"__init__(self): self._button_state = [False for _ in self._buttons] current_time = time.time() self._button_state_last_change =",
"= self._button_state[i] if ((t-self._button_state_last_change[i]) > self._debounce_interval) and not old: self._button_state[i] = True else:",
"in range(5): self.setLED(i, True) time.sleep(0.05) self.setLED(i, False) class UI_EdgeTpuDevBoard(UI): def __init__(self): global GPIO,",
"self._buttons = [ GPIO(6, \"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141, \"in\"), ]",
"times): for t in range(0,times): for i in range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \",",
"initPWM(2), GPIO(73, \"out\"), initPWM(1), initPWM(0), GPIO(77 , \"out\"), ] except GPIOError as e:",
"wiggleLEDs(self, reps=3): for i in range(reps): for i in range(5): self.setLED(i, True) time.sleep(0.05)",
"0.1 # seconds def setOnlyLED(self, index): for i in range(len(self._LEDs)): self.setLED(i, False) if",
"NotImplementedError() def getButtonState(self): raise NotImplementedError() def getDebouncedButtonState(self): t = time.time() for i,new in",
"self.getButtonState() return buttons[index] def setLED(self, index, state): raise NotImplementedError() def getButtonState(self): raise NotImplementedError()",
"0 pwm.enable() return pwm try: self._buttons = [ GPIO(6, \"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"),",
"self._LEDs = [ initPWM(2), GPIO(73, \"out\"), initPWM(1), initPWM(0), GPIO(77 , \"out\"), ] except",
"NotImplementedError() def getDebouncedButtonState(self): t = time.time() for i,new in enumerate(self.getButtonState()): if not new:",
"or [] + self._buttons or []: x.close() def setLED(self, index, state): \"\"\"Abstracts away",
"0.0 def getButtonState(self): return [not button.read() for button in self._buttons] if __name__== \"__main__\":",
"if v])) time.sleep(0.01) def wiggleLEDs(self, reps=3): for i in range(reps): for i in",
"except GPIOError as e: print(\"Unable to access GPIO pins. Did you run with",
"t return self._button_state def testButtons(self, times): for t in range(0,times): for i in",
"\".join([str(i) for i,v in enumerate(self.getButtonState()) if v])) time.sleep(0.01) def wiggleLEDs(self, reps=3): for i",
"self.setLED(i, True) time.sleep(0.05) self.setLED(i, False) class UI_EdgeTpuDevBoard(UI): def __init__(self): global GPIO, PWM from",
"GPIO, PWM from periphery import GPIO, PWM, GPIOError def initPWM(pin): pwm = PWM(pin,",
"pwm = PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm",
"PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm try: self._buttons",
"return pwm try: self._buttons = [ GPIO(6, \"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"),",
"self._debounce_interval = 0.1 # seconds def setOnlyLED(self, index): for i in range(len(self._LEDs)): self.setLED(i,",
"in range(reps): for i in range(5): self.setLED(i, True) time.sleep(0.05) self.setLED(i, False) class UI_EdgeTpuDevBoard(UI):",
"index): buttons = self.getButtonState() return buttons[index] def setLED(self, index, state): raise NotImplementedError() def",
"= [ GPIO(6, \"in\"), GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141, \"in\"), ] self._LEDs",
"with sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self): if hasattr(self, \"_LEDs\"): for x",
"periphery import GPIO, PWM, GPIOError def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency =",
"mix of GPIO and PWM LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle =",
"range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \", \" \".join([str(i) for i,v in enumerate(self.getButtonState()) if v]))",
"time.sleep(0.05) self.setLED(i, False) class UI_EdgeTpuDevBoard(UI): def __init__(self): global GPIO, PWM from periphery import",
"UI class. Subclassed by specific board implementations.\"\"\" def __init__(self): self._button_state = [False for",
"in range(len(self._LEDs)): self.setLED(i, False) if index is not None: self.setLED(index, True) def isButtonPressed(self,",
"setOnlyLED(self, index): for i in range(len(self._LEDs)): self.setLED(i, False) if index is not None:",
"[ initPWM(2), GPIO(73, \"out\"), initPWM(1), initPWM(0), GPIO(77 , \"out\"), ] except GPIOError as",
"self._buttons] current_time = time.time() self._button_state_last_change = [current_time for _ in self._buttons] self._debounce_interval =",
"_ in self._buttons] self._debounce_interval = 0.1 # seconds def setOnlyLED(self, index): for i",
"super(UI_EdgeTpuDevBoard, self).__init__() def __del__(self): if hasattr(self, \"_LEDs\"): for x in self._LEDs or []",
"GPIO and PWM LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle = 1.0 if",
"as e: print(\"Unable to access GPIO pins. Did you run with sudo ?\")",
"if index is not None: self.setLED(index, True) def isButtonPressed(self, index): buttons = self.getButtonState()",
"def getDebouncedButtonState(self): t = time.time() for i,new in enumerate(self.getButtonState()): if not new: self._button_state[i]",
"time.time() for i,new in enumerate(self.getButtonState()): if not new: self._button_state[i] = False continue old",
"self.setLED(index, True) def isButtonPressed(self, index): buttons = self.getButtonState() return buttons[index] def setLED(self, index,",
"print(\"Unable to access GPIO pins. Did you run with sudo ?\") sys.exit(1) super(UI_EdgeTpuDevBoard,",
"index): for i in range(len(self._LEDs)): self.setLED(i, False) if index is not None: self.setLED(index,",
"False continue old = self._button_state[i] if ((t-self._button_state_last_change[i]) > self._debounce_interval) and not old: self._button_state[i]",
"enumerate(self.getButtonState()) if v])) time.sleep(0.01) def wiggleLEDs(self, reps=3): for i in range(reps): for i",
"i in range(5): self.setLED(i, True) time.sleep(0.05) self.setLED(i, False) class UI_EdgeTpuDevBoard(UI): def __init__(self): global",
"current_time = time.time() self._button_state_last_change = [current_time for _ in self._buttons] self._debounce_interval = 0.1",
"index, state): raise NotImplementedError() def getButtonState(self): raise NotImplementedError() def getDebouncedButtonState(self): t = time.time()",
"and PWM LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state) else: self._LEDs[index].duty_cycle = 1.0 if state",
"print(\"Buttons: \", \" \".join([str(i) for i,v in enumerate(self.getButtonState()) if v])) time.sleep(0.01) def wiggleLEDs(self,",
"global GPIO, PWM from periphery import GPIO, PWM, GPIOError def initPWM(pin): pwm =",
"UI_EdgeTpuDevBoard(UI): def __init__(self): global GPIO, PWM from periphery import GPIO, PWM, GPIOError def",
"for i in range(len(self._LEDs)): self.setLED(i, False) if index is not None: self.setLED(index, True)",
"implementations.\"\"\" def __init__(self): self._button_state = [False for _ in self._buttons] current_time = time.time()",
"board implementations.\"\"\" def __init__(self): self._button_state = [False for _ in self._buttons] current_time =",
"buttons[index] def setLED(self, index, state): raise NotImplementedError() def getButtonState(self): raise NotImplementedError() def getDebouncedButtonState(self):",
"buttons = self.getButtonState() return buttons[index] def setLED(self, index, state): raise NotImplementedError() def getButtonState(self):",
"isButtonPressed(self, index): buttons = self.getButtonState() return buttons[index] def setLED(self, index, state): raise NotImplementedError()",
"\" \".join([str(i) for i,v in enumerate(self.getButtonState()) if v])) time.sleep(0.01) def wiggleLEDs(self, reps=3): for",
"self.setLED(i, False) class UI_EdgeTpuDevBoard(UI): def __init__(self): global GPIO, PWM from periphery import GPIO,",
"PWM, GPIOError def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle =",
"if not new: self._button_state[i] = False continue old = self._button_state[i] if ((t-self._button_state_last_change[i]) >",
"GPIO(138, \"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141, \"in\"), ] self._LEDs = [ initPWM(2), GPIO(73,",
"[False for _ in self._buttons] current_time = time.time() self._button_state_last_change = [current_time for _",
"\"in\"), GPIO(140,\"in\"), GPIO(7, \"in\"), GPIO(141, \"in\"), ] self._LEDs = [ initPWM(2), GPIO(73, \"out\"),",
"self._button_state def testButtons(self, times): for t in range(0,times): for i in range(5): self.setLED(i,",
"else 0.0 def getButtonState(self): return [not button.read() for button in self._buttons] if __name__==",
"button.read() for button in self._buttons] if __name__== \"__main__\": ui = UI_EdgeTpuDevBoard() ui.wiggleLEDs() ui.testButtons(1000)",
"getDebouncedButtonState(self): t = time.time() for i,new in enumerate(self.getButtonState()): if not new: self._button_state[i] =",
"False) if index is not None: self.setLED(index, True) def isButtonPressed(self, index): buttons =",
"1.0 if state else 0.0 def getButtonState(self): return [not button.read() for button in",
"in range(0,times): for i in range(5): self.setLED(i, self.isButtonPressed(i)) print(\"Buttons: \", \" \".join([str(i) for",
"state): \"\"\"Abstracts away mix of GPIO and PWM LEDs.\"\"\" if isinstance(self._LEDs[index], GPIO): self._LEDs[index].write(state)",
"UI(object): \"\"\"Abstract UI class. Subclassed by specific board implementations.\"\"\" def __init__(self): self._button_state =",
"= False continue old = self._button_state[i] if ((t-self._button_state_last_change[i]) > self._debounce_interval) and not old:",
"def __del__(self): if hasattr(self, \"_LEDs\"): for x in self._LEDs or [] + self._buttons",
"time.time() self._button_state_last_change = [current_time for _ in self._buttons] self._debounce_interval = 0.1 # seconds",
"= time.time() for i,new in enumerate(self.getButtonState()): if not new: self._button_state[i] = False continue",
"getButtonState(self): return [not button.read() for button in self._buttons] if __name__== \"__main__\": ui =",
"self._button_state_last_change = [current_time for _ in self._buttons] self._debounce_interval = 0.1 # seconds def",
"= False self._button_state_last_change[i] = t return self._button_state def testButtons(self, times): for t in",
"\"out\"), initPWM(1), initPWM(0), GPIO(77 , \"out\"), ] except GPIOError as e: print(\"Unable to"
] |
[
"ConventionManager() class Meta: verbose_name = _('Convention') verbose_name_plural = _('Conventions') def __str__(self): return self.name",
"range(days)] return dates def ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now()",
"class ConventionManager(models.Manager): def next(self): \"\"\" The upcoming event \"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return",
"TODO: logo som sorl-greie location = models.CharField(max_length=500) start_time = models.DateTimeField() end_time = models.DateTimeField()",
"models.DateTimeField() program_signup_opens = models.DateTimeField() program_signup_closes = models.DateTimeField() objects = ConventionManager() class Meta: verbose_name",
"> self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now() > self.ticket_sales_closes def full_description(self): return '{name}\\n{description}\\n{start} to",
"self.name def dates(self): days = (self.end_time.date() - self.start_time.date()).days + 1 dates = [self.start_time.replace(hour=0,",
"_ from django.utils import formats from django.utils import timezone # Create your models",
"models.DateTimeField() end_time = models.DateTimeField() ticket_sales_opens = models.DateTimeField() ticket_sales_closes = models.DateTimeField() program_signup_opens = models.DateTimeField()",
"import formats from django.utils import timezone # Create your models here. class ConventionManager(models.Manager):",
"def full_description(self): return '{name}\\n{description}\\n{start} to {end}'.format( name=self.name, description=self.description, start=formats.date_format(self.start_time, 'SHORT_DATE_FORMAT'), end=formats.date_format(self.end_time, 'SHORT_DATE_FORMAT'), )",
"name = models.CharField(max_length=100) description = models.TextField() mail_signature = models.TextField() # logo # TODO:",
"= _('Conventions') def __str__(self): return self.name def dates(self): days = (self.end_time.date() - self.start_time.date()).days",
"verbose_name = _('Convention') verbose_name_plural = _('Conventions') def __str__(self): return self.name def dates(self): days",
"def ticket_sales_has_ended(self): return timezone.now() > self.ticket_sales_closes def full_description(self): return '{name}\\n{description}\\n{start} to {end}'.format( name=self.name,",
"\"\"\" A con, festival or event \"\"\" name = models.CharField(max_length=100) description = models.TextField()",
"program_signup_closes = models.DateTimeField() objects = ConventionManager() class Meta: verbose_name = _('Convention') verbose_name_plural =",
"import ugettext_lazy as _ from django.utils import formats from django.utils import timezone #",
"timezone # Create your models here. class ConventionManager(models.Manager): def next(self): \"\"\" The upcoming",
"mail_signature = models.TextField() # logo # TODO: logo som sorl-greie location = models.CharField(max_length=500)",
"or event \"\"\" name = models.CharField(max_length=100) description = models.TextField() mail_signature = models.TextField() #",
"def ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now() > self.ticket_sales_closes def",
"self.ticket_sales_closes def full_description(self): return '{name}\\n{description}\\n{start} to {end}'.format( name=self.name, description=self.description, start=formats.date_format(self.start_time, 'SHORT_DATE_FORMAT'), end=formats.date_format(self.end_time, 'SHORT_DATE_FORMAT'),",
"som sorl-greie location = models.CharField(max_length=500) start_time = models.DateTimeField() end_time = models.DateTimeField() ticket_sales_opens =",
"= models.CharField(max_length=100) description = models.TextField() mail_signature = models.TextField() # logo # TODO: logo",
"return timezone.now() > self.ticket_sales_closes def full_description(self): return '{name}\\n{description}\\n{start} to {end}'.format( name=self.name, description=self.description, start=formats.date_format(self.start_time,",
"+ 1 dates = [self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x) for x in range(days)] return",
"verbose_name_plural = _('Conventions') def __str__(self): return self.name def dates(self): days = (self.end_time.date() -",
"return next_convention class Convention(models.Model): \"\"\" A con, festival or event \"\"\" name =",
"django.utils.translation import ugettext_lazy as _ from django.utils import formats from django.utils import timezone",
"event \"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class Convention(models.Model): \"\"\" A con, festival",
"models.TextField() mail_signature = models.TextField() # logo # TODO: logo som sorl-greie location =",
"1 dates = [self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x) for x in range(days)] return dates",
"models here. class ConventionManager(models.Manager): def next(self): \"\"\" The upcoming event \"\"\" next_convention =",
"django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import formats",
"= models.TextField() # logo # TODO: logo som sorl-greie location = models.CharField(max_length=500) start_time",
"_('Convention') verbose_name_plural = _('Conventions') def __str__(self): return self.name def dates(self): days = (self.end_time.date()",
"objects = ConventionManager() class Meta: verbose_name = _('Convention') verbose_name_plural = _('Conventions') def __str__(self):",
"sorl-greie location = models.CharField(max_length=500) start_time = models.DateTimeField() end_time = models.DateTimeField() ticket_sales_opens = models.DateTimeField()",
"dates = [self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x) for x in range(days)] return dates def",
"models.DateTimeField() program_signup_closes = models.DateTimeField() objects = ConventionManager() class Meta: verbose_name = _('Convention') verbose_name_plural",
"next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class Convention(models.Model): \"\"\" A con, festival or event",
"con, festival or event \"\"\" name = models.CharField(max_length=100) description = models.TextField() mail_signature =",
"from django.utils.translation import ugettext_lazy as _ from django.utils import formats from django.utils import",
"= ConventionManager() class Meta: verbose_name = _('Convention') verbose_name_plural = _('Conventions') def __str__(self): return",
"__str__(self): return self.name def dates(self): days = (self.end_time.date() - self.start_time.date()).days + 1 dates",
"return self.name def dates(self): days = (self.end_time.date() - self.start_time.date()).days + 1 dates =",
"in range(days)] return dates def ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self): return",
"logo som sorl-greie location = models.CharField(max_length=500) start_time = models.DateTimeField() end_time = models.DateTimeField() ticket_sales_opens",
"timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now() > self.ticket_sales_closes def full_description(self): return '{name}\\n{description}\\n{start}",
"A con, festival or event \"\"\" name = models.CharField(max_length=100) description = models.TextField() mail_signature",
"x in range(days)] return dates def ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self):",
"models.DateTimeField() ticket_sales_opens = models.DateTimeField() ticket_sales_closes = models.DateTimeField() program_signup_opens = models.DateTimeField() program_signup_closes = models.DateTimeField()",
"def __str__(self): return self.name def dates(self): days = (self.end_time.date() - self.start_time.date()).days + 1",
"class Meta: verbose_name = _('Convention') verbose_name_plural = _('Conventions') def __str__(self): return self.name def",
"django.utils import timezone # Create your models here. class ConventionManager(models.Manager): def next(self): \"\"\"",
"days = (self.end_time.date() - self.start_time.date()).days + 1 dates = [self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x)",
"event \"\"\" name = models.CharField(max_length=100) description = models.TextField() mail_signature = models.TextField() # logo",
"= (self.end_time.date() - self.start_time.date()).days + 1 dates = [self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x) for",
"return dates def ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now() >",
"= models.DateTimeField() program_signup_opens = models.DateTimeField() program_signup_closes = models.DateTimeField() objects = ConventionManager() class Meta:",
"timezone.now() > self.ticket_sales_closes def full_description(self): return '{name}\\n{description}\\n{start} to {end}'.format( name=self.name, description=self.description, start=formats.date_format(self.start_time, 'SHORT_DATE_FORMAT'),",
"next_convention class Convention(models.Model): \"\"\" A con, festival or event \"\"\" name = models.CharField(max_length=100)",
"= models.DateTimeField() objects = ConventionManager() class Meta: verbose_name = _('Convention') verbose_name_plural = _('Conventions')",
"# TODO: logo som sorl-greie location = models.CharField(max_length=500) start_time = models.DateTimeField() end_time =",
"self.start_time.date()).days + 1 dates = [self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x) for x in range(days)]",
"dates def ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now() > self.ticket_sales_closes",
"class Convention(models.Model): \"\"\" A con, festival or event \"\"\" name = models.CharField(max_length=100) description",
"+ timezone.timedelta(days=x) for x in range(days)] return dates def ticket_sales_has_started(self): return timezone.now() >",
"ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now() > self.ticket_sales_closes def full_description(self):",
"models.CharField(max_length=500) start_time = models.DateTimeField() end_time = models.DateTimeField() ticket_sales_opens = models.DateTimeField() ticket_sales_closes = models.DateTimeField()",
"your models here. class ConventionManager(models.Manager): def next(self): \"\"\" The upcoming event \"\"\" next_convention",
"ticket_sales_opens = models.DateTimeField() ticket_sales_closes = models.DateTimeField() program_signup_opens = models.DateTimeField() program_signup_closes = models.DateTimeField() objects",
"> self.ticket_sales_closes def full_description(self): return '{name}\\n{description}\\n{start} to {end}'.format( name=self.name, description=self.description, start=formats.date_format(self.start_time, 'SHORT_DATE_FORMAT'), end=formats.date_format(self.end_time,",
"from django.utils import timezone # Create your models here. class ConventionManager(models.Manager): def next(self):",
"\"\"\" name = models.CharField(max_length=100) description = models.TextField() mail_signature = models.TextField() # logo #",
"= models.DateTimeField() end_time = models.DateTimeField() ticket_sales_opens = models.DateTimeField() ticket_sales_closes = models.DateTimeField() program_signup_opens =",
"\"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class Convention(models.Model): \"\"\" A con, festival or",
"from django.utils import formats from django.utils import timezone # Create your models here.",
"Meta: verbose_name = _('Convention') verbose_name_plural = _('Conventions') def __str__(self): return self.name def dates(self):",
"models.DateTimeField() ticket_sales_closes = models.DateTimeField() program_signup_opens = models.DateTimeField() program_signup_closes = models.DateTimeField() objects = ConventionManager()",
"from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import",
"import timezone # Create your models here. class ConventionManager(models.Manager): def next(self): \"\"\" The",
"next(self): \"\"\" The upcoming event \"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class Convention(models.Model):",
"= models.DateTimeField() program_signup_closes = models.DateTimeField() objects = ConventionManager() class Meta: verbose_name = _('Convention')",
"= models.DateTimeField() ticket_sales_closes = models.DateTimeField() program_signup_opens = models.DateTimeField() program_signup_closes = models.DateTimeField() objects =",
"models.TextField() # logo # TODO: logo som sorl-greie location = models.CharField(max_length=500) start_time =",
"upcoming event \"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class Convention(models.Model): \"\"\" A con,",
"program_signup_opens = models.DateTimeField() program_signup_closes = models.DateTimeField() objects = ConventionManager() class Meta: verbose_name =",
"import models from django.utils.translation import ugettext_lazy as _ from django.utils import formats from",
"as _ from django.utils import formats from django.utils import timezone # Create your",
"here. class ConventionManager(models.Manager): def next(self): \"\"\" The upcoming event \"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first()",
"ticket_sales_closes = models.DateTimeField() program_signup_opens = models.DateTimeField() program_signup_closes = models.DateTimeField() objects = ConventionManager() class",
"# logo # TODO: logo som sorl-greie location = models.CharField(max_length=500) start_time = models.DateTimeField()",
"= self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class Convention(models.Model): \"\"\" A con, festival or event \"\"\"",
"location = models.CharField(max_length=500) start_time = models.DateTimeField() end_time = models.DateTimeField() ticket_sales_opens = models.DateTimeField() ticket_sales_closes",
"= [self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x) for x in range(days)] return dates def ticket_sales_has_started(self):",
"end_time = models.DateTimeField() ticket_sales_opens = models.DateTimeField() ticket_sales_closes = models.DateTimeField() program_signup_opens = models.DateTimeField() program_signup_closes",
"self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class Convention(models.Model): \"\"\" A con, festival or event \"\"\" name",
"Convention(models.Model): \"\"\" A con, festival or event \"\"\" name = models.CharField(max_length=100) description =",
"festival or event \"\"\" name = models.CharField(max_length=100) description = models.TextField() mail_signature = models.TextField()",
"models.CharField(max_length=100) description = models.TextField() mail_signature = models.TextField() # logo # TODO: logo som",
"formats from django.utils import timezone # Create your models here. class ConventionManager(models.Manager): def",
"django.utils import formats from django.utils import timezone # Create your models here. class",
"models.DateTimeField() objects = ConventionManager() class Meta: verbose_name = _('Convention') verbose_name_plural = _('Conventions') def",
"= models.DateTimeField() ticket_sales_opens = models.DateTimeField() ticket_sales_closes = models.DateTimeField() program_signup_opens = models.DateTimeField() program_signup_closes =",
"timezone.timedelta(days=x) for x in range(days)] return dates def ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens",
"Create your models here. class ConventionManager(models.Manager): def next(self): \"\"\" The upcoming event \"\"\"",
"\"\"\" The upcoming event \"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class Convention(models.Model): \"\"\"",
"models from django.utils.translation import ugettext_lazy as _ from django.utils import formats from django.utils",
"def next(self): \"\"\" The upcoming event \"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class",
"description = models.TextField() mail_signature = models.TextField() # logo # TODO: logo som sorl-greie",
"= models.TextField() mail_signature = models.TextField() # logo # TODO: logo som sorl-greie location",
"ugettext_lazy as _ from django.utils import formats from django.utils import timezone # Create",
"= models.CharField(max_length=500) start_time = models.DateTimeField() end_time = models.DateTimeField() ticket_sales_opens = models.DateTimeField() ticket_sales_closes =",
"= _('Convention') verbose_name_plural = _('Conventions') def __str__(self): return self.name def dates(self): days =",
"# Create your models here. class ConventionManager(models.Manager): def next(self): \"\"\" The upcoming event",
"_('Conventions') def __str__(self): return self.name def dates(self): days = (self.end_time.date() - self.start_time.date()).days +",
"[self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x) for x in range(days)] return dates def ticket_sales_has_started(self): return",
"for x in range(days)] return dates def ticket_sales_has_started(self): return timezone.now() > self.ticket_sales_opens def",
"The upcoming event \"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention class Convention(models.Model): \"\"\" A",
"ticket_sales_has_ended(self): return timezone.now() > self.ticket_sales_closes def full_description(self): return '{name}\\n{description}\\n{start} to {end}'.format( name=self.name, description=self.description,",
"self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now() > self.ticket_sales_closes def full_description(self): return '{name}\\n{description}\\n{start} to {end}'.format(",
"def dates(self): days = (self.end_time.date() - self.start_time.date()).days + 1 dates = [self.start_time.replace(hour=0, minute=0)",
"ConventionManager(models.Manager): def next(self): \"\"\" The upcoming event \"\"\" next_convention = self.exclude(end_time__lt=timezone.now()).order_by('start_time').first() return next_convention",
"logo # TODO: logo som sorl-greie location = models.CharField(max_length=500) start_time = models.DateTimeField() end_time",
"dates(self): days = (self.end_time.date() - self.start_time.date()).days + 1 dates = [self.start_time.replace(hour=0, minute=0) +",
"start_time = models.DateTimeField() end_time = models.DateTimeField() ticket_sales_opens = models.DateTimeField() ticket_sales_closes = models.DateTimeField() program_signup_opens",
"minute=0) + timezone.timedelta(days=x) for x in range(days)] return dates def ticket_sales_has_started(self): return timezone.now()",
"return timezone.now() > self.ticket_sales_opens def ticket_sales_has_ended(self): return timezone.now() > self.ticket_sales_closes def full_description(self): return",
"- self.start_time.date()).days + 1 dates = [self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x) for x in",
"(self.end_time.date() - self.start_time.date()).days + 1 dates = [self.start_time.replace(hour=0, minute=0) + timezone.timedelta(days=x) for x"
] |
[
"from string import ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\", \"bar\",",
"in range(1, 1000): routing_key = \"%s.%s\" % (choice(APPS), choice(LEVELS)) body = \"%03d Some",
"#!/usr/bin/env python import time from random import choice from string import ascii_lowercase from",
"\"warn\", \"error\"] def publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel() for counter in range(1, 1000): routing_key",
"string import ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\", \"bar\", \"infrastructure\"]",
"amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\", \"bar\", \"infrastructure\"] LEVELS = [\"debug\", \"info\",",
"random import choice from string import ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS",
"connect_get_channel_declare_exchange_and_return_channel() for counter in range(1, 1000): routing_key = \"%s.%s\" % (choice(APPS), choice(LEVELS)) body",
"range(1, 1000): routing_key = \"%s.%s\" % (choice(APPS), choice(LEVELS)) body = \"%03d Some random",
"EXCHANGE_NAME APPS = [\"foo\", \"bar\", \"infrastructure\"] LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] def",
"channel = connect_get_channel_declare_exchange_and_return_channel() for counter in range(1, 1000): routing_key = \"%s.%s\" % (choice(APPS),",
"routing_key=routing_key, body=body ) print(\"Published '%s' to '%s' with routing-key '%s'.\" % (body, EXCHANGE_NAME,",
"print(\"Published '%s' to '%s' with routing-key '%s'.\" % (body, EXCHANGE_NAME, routing_key)) time.sleep(1) if",
"(body, EXCHANGE_NAME, routing_key)) time.sleep(1) if __name__ == \"__main__\": try: publish_cyclically() except KeyboardInterrupt: pass",
"= \"%s.%s\" % (choice(APPS), choice(LEVELS)) body = \"%03d Some random text: %s \"",
"= \"%03d Some random text: %s \" % ( counter, ''.join(choice(ascii_lowercase) for _",
"import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\", \"bar\", \"infrastructure\"] LEVELS = [\"debug\", \"info\", \"warn\",",
"= connect_get_channel_declare_exchange_and_return_channel() for counter in range(1, 1000): routing_key = \"%s.%s\" % (choice(APPS), choice(LEVELS))",
"'%s'.\" % (body, EXCHANGE_NAME, routing_key)) time.sleep(1) if __name__ == \"__main__\": try: publish_cyclically() except",
"routing-key '%s'.\" % (body, EXCHANGE_NAME, routing_key)) time.sleep(1) if __name__ == \"__main__\": try: publish_cyclically()",
"publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel() for counter in range(1, 1000): routing_key = \"%s.%s\" %",
"'%s' with routing-key '%s'.\" % (body, EXCHANGE_NAME, routing_key)) time.sleep(1) if __name__ == \"__main__\":",
"for counter in range(1, 1000): routing_key = \"%s.%s\" % (choice(APPS), choice(LEVELS)) body =",
"def publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel() for counter in range(1, 1000): routing_key = \"%s.%s\"",
"from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\", \"bar\", \"infrastructure\"] LEVELS = [\"debug\",",
"routing_key = \"%s.%s\" % (choice(APPS), choice(LEVELS)) body = \"%03d Some random text: %s",
"body = \"%03d Some random text: %s \" % ( counter, ''.join(choice(ascii_lowercase) for",
"_ in range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body ) print(\"Published '%s' to '%s'",
"channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body ) print(\"Published '%s' to '%s' with routing-key '%s'.\" %",
"\"error\"] def publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel() for counter in range(1, 1000): routing_key =",
"import ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\", \"bar\", \"infrastructure\"] LEVELS",
"% (body, EXCHANGE_NAME, routing_key)) time.sleep(1) if __name__ == \"__main__\": try: publish_cyclically() except KeyboardInterrupt:",
"body=body ) print(\"Published '%s' to '%s' with routing-key '%s'.\" % (body, EXCHANGE_NAME, routing_key))",
"\"info\", \"warn\", \"error\"] def publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel() for counter in range(1, 1000):",
"= [\"debug\", \"info\", \"warn\", \"error\"] def publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel() for counter in",
"to '%s' with routing-key '%s'.\" % (body, EXCHANGE_NAME, routing_key)) time.sleep(1) if __name__ ==",
"choice(LEVELS)) body = \"%03d Some random text: %s \" % ( counter, ''.join(choice(ascii_lowercase)",
"time from random import choice from string import ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel,",
"\"%03d Some random text: %s \" % ( counter, ''.join(choice(ascii_lowercase) for _ in",
"with routing-key '%s'.\" % (body, EXCHANGE_NAME, routing_key)) time.sleep(1) if __name__ == \"__main__\": try:",
"\"%s.%s\" % (choice(APPS), choice(LEVELS)) body = \"%03d Some random text: %s \" %",
"[\"foo\", \"bar\", \"infrastructure\"] LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] def publish_cyclically(): channel =",
"choice from string import ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\",",
") channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body ) print(\"Published '%s' to '%s' with routing-key '%s'.\"",
"counter in range(1, 1000): routing_key = \"%s.%s\" % (choice(APPS), choice(LEVELS)) body = \"%03d",
"import choice from string import ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS =",
"[\"debug\", \"info\", \"warn\", \"error\"] def publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel() for counter in range(1,",
"in range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body ) print(\"Published '%s' to '%s' with",
"( counter, ''.join(choice(ascii_lowercase) for _ in range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body )",
"counter, ''.join(choice(ascii_lowercase) for _ in range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body ) print(\"Published",
"exchange=EXCHANGE_NAME, routing_key=routing_key, body=body ) print(\"Published '%s' to '%s' with routing-key '%s'.\" % (body,",
"''.join(choice(ascii_lowercase) for _ in range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body ) print(\"Published '%s'",
"\"infrastructure\"] LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] def publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel() for",
"connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\", \"bar\", \"infrastructure\"] LEVELS = [\"debug\", \"info\", \"warn\", \"error\"]",
"random text: %s \" % ( counter, ''.join(choice(ascii_lowercase) for _ in range(16)) )",
"ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME APPS = [\"foo\", \"bar\", \"infrastructure\"] LEVELS =",
"APPS = [\"foo\", \"bar\", \"infrastructure\"] LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] def publish_cyclically():",
"%s \" % ( counter, ''.join(choice(ascii_lowercase) for _ in range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME,",
") print(\"Published '%s' to '%s' with routing-key '%s'.\" % (body, EXCHANGE_NAME, routing_key)) time.sleep(1)",
"\"bar\", \"infrastructure\"] LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] def publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel()",
"LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] def publish_cyclically(): channel = connect_get_channel_declare_exchange_and_return_channel() for counter",
"1000): routing_key = \"%s.%s\" % (choice(APPS), choice(LEVELS)) body = \"%03d Some random text:",
"Some random text: %s \" % ( counter, ''.join(choice(ascii_lowercase) for _ in range(16))",
"text: %s \" % ( counter, ''.join(choice(ascii_lowercase) for _ in range(16)) ) channel.basic_publish(",
"from random import choice from string import ascii_lowercase from amqp import connect_get_channel_declare_exchange_and_return_channel, EXCHANGE_NAME",
"\" % ( counter, ''.join(choice(ascii_lowercase) for _ in range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key,",
"(choice(APPS), choice(LEVELS)) body = \"%03d Some random text: %s \" % ( counter,",
"% (choice(APPS), choice(LEVELS)) body = \"%03d Some random text: %s \" % (",
"% ( counter, ''.join(choice(ascii_lowercase) for _ in range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body",
"for _ in range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body ) print(\"Published '%s' to",
"import time from random import choice from string import ascii_lowercase from amqp import",
"= [\"foo\", \"bar\", \"infrastructure\"] LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] def publish_cyclically(): channel",
"python import time from random import choice from string import ascii_lowercase from amqp",
"range(16)) ) channel.basic_publish( exchange=EXCHANGE_NAME, routing_key=routing_key, body=body ) print(\"Published '%s' to '%s' with routing-key",
"'%s' to '%s' with routing-key '%s'.\" % (body, EXCHANGE_NAME, routing_key)) time.sleep(1) if __name__"
] |
[
"to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url)) await ctx.message.delete() await ctx.send(embed=embed,",
"help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def help(self, ctx): embed",
"import asyncio class help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def",
"bot @commands.command() async def help(self, ctx): embed = discord.Embed( title=\"KEKW Bot Help\", description=\"_",
"[Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount, defaults to 50)```**\\n**```kekw!emojis```**\", inline=False)",
"from discord.ext import commands from discord.ext import * from discord.ext.commands import * import",
"KEKW bot!\\nCheck out our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\",",
"def __init__(self, bot): self.bot = bot @commands.command() async def help(self, ctx): embed =",
"import * from discord.ext.commands import * import asyncio class help(commands.Cog): def __init__(self, bot):",
"ctx): embed = discord.Embed( title=\"KEKW Bot Help\", description=\"_ _\\nThank you for inviting KEKW",
"* import asyncio class help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async",
"bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount, defaults to 50)```**\\n**```kekw!emojis```**\",",
"embed = discord.Embed( title=\"KEKW Bot Help\", description=\"_ _\\nThank you for inviting KEKW bot!\\nCheck",
"def help(self, ctx): embed = discord.Embed( title=\"KEKW Bot Help\", description=\"_ _\\nThank you for",
"inviting KEKW bot!\\nCheck out our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main",
"Help\", description=\"_ _\\nThank you for inviting KEKW bot!\\nCheck out our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup",
"defaults to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url)) await ctx.message.delete() await",
"from discord.ext.commands import * import asyncio class help(commands.Cog): def __init__(self, bot): self.bot =",
"you for inviting KEKW bot!\\nCheck out our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold()",
"bot!\\nCheck out our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\", value=\"**```kekw!start",
"embed.set_footer(text=\"Requested by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url)) await ctx.message.delete() await ctx.send(embed=embed, delete_after=30) def setup(bot):",
"discord from discord.ext import commands from discord.ext import * from discord.ext.commands import *",
"from discord.ext import * from discord.ext.commands import * import asyncio class help(commands.Cog): def",
"(amount, defaults to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url)) await ctx.message.delete()",
"self.bot = bot @commands.command() async def help(self, ctx): embed = discord.Embed( title=\"KEKW Bot",
"by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url)) await ctx.message.delete() await ctx.send(embed=embed, delete_after=30) def setup(bot): bot.add_cog(help(bot))",
"discord.ext.commands import * import asyncio class help(commands.Cog): def __init__(self, bot): self.bot = bot",
"discord.ext import commands from discord.ext import * from discord.ext.commands import * import asyncio",
"50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url)) await ctx.message.delete() await ctx.send(embed=embed, delete_after=30)",
"title=\"KEKW Bot Help\", description=\"_ _\\nThank you for inviting KEKW bot!\\nCheck out our other",
"inline=False) embed.set_footer(text=\"Requested by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url)) await ctx.message.delete() await ctx.send(embed=embed, delete_after=30) def",
"import commands from discord.ext import * from discord.ext.commands import * import asyncio class",
"import discord from discord.ext import commands from discord.ext import * from discord.ext.commands import",
"commands from discord.ext import * from discord.ext.commands import * import asyncio class help(commands.Cog):",
"asyncio class help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def help(self,",
"class help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def help(self, ctx):",
"= discord.Embed( title=\"KEKW Bot Help\", description=\"_ _\\nThank you for inviting KEKW bot!\\nCheck out",
"out our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount,",
"__init__(self, bot): self.bot = bot @commands.command() async def help(self, ctx): embed = discord.Embed(",
"value=\"**```kekw!start (amount, defaults to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url)) await",
"help(self, ctx): embed = discord.Embed( title=\"KEKW Bot Help\", description=\"_ _\\nThank you for inviting",
"async def help(self, ctx): embed = discord.Embed( title=\"KEKW Bot Help\", description=\"_ _\\nThank you",
"bot): self.bot = bot @commands.command() async def help(self, ctx): embed = discord.Embed( title=\"KEKW",
"= bot @commands.command() async def help(self, ctx): embed = discord.Embed( title=\"KEKW Bot Help\",",
"for inviting KEKW bot!\\nCheck out our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() )",
"our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount, defaults",
"the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount, defaults to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested",
") embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount, defaults to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \" +",
"bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount, defaults to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by:",
"@commands.command() async def help(self, ctx): embed = discord.Embed( title=\"KEKW Bot Help\", description=\"_ _\\nThank",
"import * import asyncio class help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command()",
"commands:\", value=\"**```kekw!start (amount, defaults to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \" + str(ctx.author), icon_url=str(ctx.author.avatar_url))",
"_\\nThank you for inviting KEKW bot!\\nCheck out our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\",",
"discord.Embed( title=\"KEKW Bot Help\", description=\"_ _\\nThank you for inviting KEKW bot!\\nCheck out our",
"other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the bot](https://github.com/Fxcilities/KEKWBot/blob/main/README.md)\", color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount, defaults to",
"discord.ext import * from discord.ext.commands import * import asyncio class help(commands.Cog): def __init__(self,",
"embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount, defaults to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \" + str(ctx.author),",
"Bot Help\", description=\"_ _\\nThank you for inviting KEKW bot!\\nCheck out our other bot,",
"description=\"_ _\\nThank you for inviting KEKW bot!\\nCheck out our other bot, [Essentials](https://essentialsbot.xyz)\\n\\n[Setup the",
"color=discord.Color.dark_gold() ) embed.add_field(name=\"Main commands:\", value=\"**```kekw!start (amount, defaults to 50)```**\\n**```kekw!emojis```**\", inline=False) embed.set_footer(text=\"Requested by: \"",
"* from discord.ext.commands import * import asyncio class help(commands.Cog): def __init__(self, bot): self.bot"
] |
[
"''' Twilio keys for send_text.py: account_sid_key auth_token ''' class TwilioKey: def __init__(self): #",
"account_sid_key auth_token ''' class TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key",
"__init__(self): # https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key = \"your_auth\" def get_sid(self): return self.account_sid_key",
"<reponame>ridwanrahman/wavemaps<filename>twiliokey.py ''' Twilio keys for send_text.py: account_sid_key auth_token ''' class TwilioKey: def __init__(self):",
"send_text.py: account_sid_key auth_token ''' class TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\"",
"for send_text.py: account_sid_key auth_token ''' class TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key =",
"= \"your_sid\" self.auth_token_key = \"your_auth\" def get_sid(self): return self.account_sid_key def get_auth(self): return self.auth_token_key",
"keys for send_text.py: account_sid_key auth_token ''' class TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key",
"TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key = \"your_auth\" def get_sid(self):",
"def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key = \"your_auth\" def get_sid(self): return",
"# https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key = \"your_auth\" def get_sid(self): return self.account_sid_key def",
"class TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key = \"your_auth\" def",
"''' class TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key = \"your_auth\"",
"self.account_sid_key = \"your_sid\" self.auth_token_key = \"your_auth\" def get_sid(self): return self.account_sid_key def get_auth(self): return",
"Twilio keys for send_text.py: account_sid_key auth_token ''' class TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio",
"auth_token ''' class TwilioKey: def __init__(self): # https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key =",
"https://www.twilio.com/try-twilio self.account_sid_key = \"your_sid\" self.auth_token_key = \"your_auth\" def get_sid(self): return self.account_sid_key def get_auth(self):"
] |
[
"doing computation using spark streaming # store back to kafka producer in another",
"5) logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd): def group(record): data",
"topic to send processed data to kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this is the kafka",
"the topic to receive data from kafka producer\") parser.add_argument(\"target_topic\", help=\"this is the topic",
"json import logging import atexit from pyspark import SparkContext from pyspark.streaming import StreamingContext",
"direceKafkaStream.foreachRDD(self.process) # transformation with action self.ssc.start() self.ssc.awaitTermination() if __name__ == \"__main__\": parser =",
"kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this is the kafka broker\") args = parser.parse_args() topic =",
"broker\") args = parser.parse_args() topic = args.topic target_topic = args.target_topic kafka_broker = args.kafka_broker",
"broker\") parser.add_argument(\"kafka_broker\", help=\"this is the kafka broker\") args = parser.parse_args() topic = args.topic",
"topic import argparse import json import logging import atexit from pyspark import SparkContext",
"pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from kafka import KafkaProducer from kafka.errors",
"kafka import KafkaProducer from kafka.errors import KafkaError class spark_streaming(): def __init__(self, topic, target_topic,",
"try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send processed data to {}, {}\".format(self.target_topic, msg)) except KafkaError",
"= topic self.kafka_broker = kafka_broker self.target_topic = target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc =",
"in results: msg = {\"StockSymbol\": res[0], \"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send",
"msg)) except KafkaError as KE: self.logger.warning(\"Failed to send data, the error is {}\".format(msg))",
"self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation with action self.ssc.start() self.ssc.awaitTermination() if __name__ == \"__main__\": parser",
"from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from",
"@author: <NAME> # email: <EMAIL> # -2 # fetch data from kafka producer",
"SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc, 5) logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def",
"back to kafka producer in another topic import argparse import json import logging",
"help=\"this is the kafka broker\") args = parser.parse_args() topic = args.topic target_topic =",
"directKafkaStream def run(self): direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation with action self.ssc.start() self.ssc.awaitTermination()",
"send data, the error is {}\".format(msg)) def createStream(self): # create space for data",
"{}\".format(self.target_topic, msg)) except KafkaError as KE: self.logger.warning(\"Failed to send data, the error is",
"class spark_streaming(): def __init__(self, topic, target_topic, kafka_broker): self.topic = topic self.kafka_broker = kafka_broker",
"except KafkaError as KE: self.logger.warning(\"Failed to send data, the error is {}\".format(msg)) def",
"(float(data.get(\"LastTradePrice\")), 1) newRDD = rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol, price :",
"results = newRDD.collect() for res in results: msg = {\"StockSymbol\": res[0], \"AveragePrice\": res[1]}",
"self.ssc.awaitTermination() if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is the topic",
"in another topic import argparse import json import logging import atexit from pyspark",
"msg = {\"StockSymbol\": res[0], \"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send processed data",
"y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol, price : (symbol, price[0]/price[1])) results = newRDD.collect() for",
"data computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" : self.kafka_broker}) return directKafkaStream def run(self):",
"target_topic, kafka_broker): self.topic = topic self.kafka_broker = kafka_broker self.target_topic = target_topic self.kafka_producer =",
"kafka_broker): self.topic = topic self.kafka_broker = kafka_broker self.target_topic = target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker)",
"producer # doing computation using spark streaming # store back to kafka producer",
"KE: self.logger.warning(\"Failed to send data, the error is {}\".format(msg)) def createStream(self): # create",
"is {}\".format(msg)) def createStream(self): # create space for data computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc,",
"as KE: self.logger.warning(\"Failed to send data, the error is {}\".format(msg)) def createStream(self): #",
"from pyspark.streaming.kafka import KafkaUtils from kafka import KafkaProducer from kafka.errors import KafkaError class",
"from kafka import KafkaProducer from kafka.errors import KafkaError class spark_streaming(): def __init__(self, topic,",
"x, y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol, price : (symbol, price[0]/price[1])) results = newRDD.collect()",
"price : (symbol, price[0]/price[1])) results = newRDD.collect() for res in results: msg =",
"computation using spark streaming # store back to kafka producer in another topic",
"== \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is the topic to receive data",
"# @author: <NAME> # email: <EMAIL> # -2 # fetch data from kafka",
"# -2 # fetch data from kafka producer # doing computation using spark",
"= SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc, 5) logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO)",
"[self.topic], {\"metadata.broker.list\" : self.kafka_broker}) return directKafkaStream def run(self): direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process) #",
"self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd): def group(record): data = json.loads(record[1].decode('utf-8'))[0]",
"parser.add_argument(\"topic\", help=\"this is the topic to receive data from kafka producer\") parser.add_argument(\"target_topic\", help=\"this",
"self.logger.info(\"Successfully send processed data to {}, {}\".format(self.target_topic, msg)) except KafkaError as KE: self.logger.warning(\"Failed",
"KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" : self.kafka_broker}) return directKafkaStream def run(self): direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process)",
"spark_streaming(): def __init__(self, topic, target_topic, kafka_broker): self.topic = topic self.kafka_broker = kafka_broker self.target_topic",
"if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is the topic to",
"= rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol, price : (symbol, price[0]/price[1])) results",
"to kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this is the kafka broker\") args = parser.parse_args() topic",
"topic, target_topic, kafka_broker): self.topic = topic self.kafka_broker = kafka_broker self.target_topic = target_topic self.kafka_producer",
"-2 # fetch data from kafka producer # doing computation using spark streaming",
"using spark streaming # store back to kafka producer in another topic import",
"def createStream(self): # create space for data computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\"",
"error is {}\".format(msg)) def createStream(self): # create space for data computation directKafkaStream =",
"kafka producer\") parser.add_argument(\"target_topic\", help=\"this is the topic to send processed data to kafka",
"import KafkaError class spark_streaming(): def __init__(self, topic, target_topic, kafka_broker): self.topic = topic self.kafka_broker",
"StreamingContext(sc, 5) logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd): def group(record):",
"the error is {}\".format(msg)) def createStream(self): # create space for data computation directKafkaStream",
"action self.ssc.start() self.ssc.awaitTermination() if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is",
"transformation with action self.ssc.start() self.ssc.awaitTermination() if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"topic\",",
"res[0], \"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send processed data to {}, {}\".format(self.target_topic,",
"create space for data computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" : self.kafka_broker}) return",
"space for data computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" : self.kafka_broker}) return directKafkaStream",
"receive data from kafka producer\") parser.add_argument(\"target_topic\", help=\"this is the topic to send processed",
"{\"metadata.broker.list\" : self.kafka_broker}) return directKafkaStream def run(self): direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation",
"atexit from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils",
"run(self): direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation with action self.ssc.start() self.ssc.awaitTermination() if __name__",
"directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" : self.kafka_broker}) return directKafkaStream def run(self): direceKafkaStream =",
"{}, {}\".format(self.target_topic, msg)) except KafkaError as KE: self.logger.warning(\"Failed to send data, the error",
"email: <EMAIL> # -2 # fetch data from kafka producer # doing computation",
": (symbol, price[0]/price[1])) results = newRDD.collect() for res in results: msg = {\"StockSymbol\":",
"StreamingContext from pyspark.streaming.kafka import KafkaUtils from kafka import KafkaProducer from kafka.errors import KafkaError",
"kafka broker\") args = parser.parse_args() topic = args.topic target_topic = args.target_topic kafka_broker =",
"self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd): def group(record): data = json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")),",
"send processed data to {}, {}\".format(self.target_topic, msg)) except KafkaError as KE: self.logger.warning(\"Failed to",
"res in results: msg = {\"StockSymbol\": res[0], \"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully",
"from kafka producer # doing computation using spark streaming # store back to",
"the topic to send processed data to kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this is the",
"processed data to {}, {}\".format(self.target_topic, msg)) except KafkaError as KE: self.logger.warning(\"Failed to send",
"= parser.parse_args() topic = args.topic target_topic = args.target_topic kafka_broker = args.kafka_broker KafkaSpark =",
"timeobj, rdd): def group(record): data = json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD =",
"1) newRDD = rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol, price : (symbol,",
"target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc, 5)",
"kafka_broker self.target_topic = target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc",
"help=\"this is the topic to receive data from kafka producer\") parser.add_argument(\"target_topic\", help=\"this is",
"import KafkaProducer from kafka.errors import KafkaError class spark_streaming(): def __init__(self, topic, target_topic, kafka_broker):",
"= kafka_broker self.target_topic = target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\")",
"with action self.ssc.start() self.ssc.awaitTermination() if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this",
"import atexit from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import",
"= {\"StockSymbol\": res[0], \"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send processed data to",
"spark streaming # store back to kafka producer in another topic import argparse",
"= json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD = rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))\\",
"return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD = rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol,",
"# fetch data from kafka producer # doing computation using spark streaming #",
"pyspark.streaming.kafka import KafkaUtils from kafka import KafkaProducer from kafka.errors import KafkaError class spark_streaming():",
"kafka producer in another topic import argparse import json import logging import atexit",
"= self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation with action self.ssc.start() self.ssc.awaitTermination() if __name__ == \"__main__\":",
"= argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is the topic to receive data from kafka producer\")",
"help=\"this is the topic to send processed data to kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this",
"x[1]+y[1]))\\ .map(lambda symbol, price : (symbol, price[0]/price[1])) results = newRDD.collect() for res in",
"__name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is the topic to receive",
"sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc, 5) logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj,",
"\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is the topic to receive data from",
"KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc, 5) logging.basicConfig() self.logger =",
"data = json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD = rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0],",
"newRDD.collect() for res in results: msg = {\"StockSymbol\": res[0], \"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic,",
"parser.add_argument(\"target_topic\", help=\"this is the topic to send processed data to kafka broker\") parser.add_argument(\"kafka_broker\",",
"KafkaUtils from kafka import KafkaProducer from kafka.errors import KafkaError class spark_streaming(): def __init__(self,",
"producer\") parser.add_argument(\"target_topic\", help=\"this is the topic to send processed data to kafka broker\")",
"self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc, 5) logging.basicConfig()",
"KafkaProducer from kafka.errors import KafkaError class spark_streaming(): def __init__(self, topic, target_topic, kafka_broker): self.topic",
"argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is the topic to receive data from kafka producer\") parser.add_argument(\"target_topic\",",
"parser = argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is the topic to receive data from kafka",
"is the topic to receive data from kafka producer\") parser.add_argument(\"target_topic\", help=\"this is the",
"data from kafka producer # doing computation using spark streaming # store back",
"self.kafka_broker}) return directKafkaStream def run(self): direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation with action",
"group(record): data = json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD = rdd.map(group).reduceByKey(lambda x, y:",
"newRDD = rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol, price : (symbol, price[0]/price[1]))",
"streaming # store back to kafka producer in another topic import argparse import",
"def run(self): direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation with action self.ssc.start() self.ssc.awaitTermination() if",
"rdd): def group(record): data = json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD = rdd.map(group).reduceByKey(lambda",
"for data computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" : self.kafka_broker}) return directKafkaStream def",
"kafka.errors import KafkaError class spark_streaming(): def __init__(self, topic, target_topic, kafka_broker): self.topic = topic",
".map(lambda symbol, price : (symbol, price[0]/price[1])) results = newRDD.collect() for res in results:",
"self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send processed data to {}, {}\".format(self.target_topic, msg)) except KafkaError as",
"fetch data from kafka producer # doing computation using spark streaming # store",
"<EMAIL> # -2 # fetch data from kafka producer # doing computation using",
"data to {}, {}\".format(self.target_topic, msg)) except KafkaError as KE: self.logger.warning(\"Failed to send data,",
"topic to receive data from kafka producer\") parser.add_argument(\"target_topic\", help=\"this is the topic to",
"from kafka producer\") parser.add_argument(\"target_topic\", help=\"this is the topic to send processed data to",
"symbol, price : (symbol, price[0]/price[1])) results = newRDD.collect() for res in results: msg",
"json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD = rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda",
"createStream(self): # create space for data computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" :",
"= KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" : self.kafka_broker}) return directKafkaStream def run(self): direceKafkaStream = self.createStream()",
"data to kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this is the kafka broker\") args = parser.parse_args()",
"to kafka producer in another topic import argparse import json import logging import",
"\"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send processed data to {}, {}\".format(self.target_topic, msg))",
"pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from kafka",
"import StreamingContext from pyspark.streaming.kafka import KafkaUtils from kafka import KafkaProducer from kafka.errors import",
"rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol, price : (symbol, price[0]/price[1])) results =",
"price[0]/price[1])) results = newRDD.collect() for res in results: msg = {\"StockSymbol\": res[0], \"AveragePrice\":",
"<NAME> # email: <EMAIL> # -2 # fetch data from kafka producer #",
"is the topic to send processed data to kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this is",
"to send processed data to kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this is the kafka broker\")",
"# email: <EMAIL> # -2 # fetch data from kafka producer # doing",
"{}\".format(msg)) def createStream(self): # create space for data computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic],",
"= args.topic target_topic = args.target_topic kafka_broker = args.kafka_broker KafkaSpark = spark_streaming(topic, target_topic, kafka_broker)",
"another topic import argparse import json import logging import atexit from pyspark import",
"from kafka.errors import KafkaError class spark_streaming(): def __init__(self, topic, target_topic, kafka_broker): self.topic =",
"data, the error is {}\".format(msg)) def createStream(self): # create space for data computation",
"self.topic = topic self.kafka_broker = kafka_broker self.target_topic = target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc",
"self.target_topic = target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc =",
"kafka producer # doing computation using spark streaming # store back to kafka",
"KafkaError class spark_streaming(): def __init__(self, topic, target_topic, kafka_broker): self.topic = topic self.kafka_broker =",
"(x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol, price : (symbol, price[0]/price[1])) results = newRDD.collect() for res",
"is the kafka broker\") args = parser.parse_args() topic = args.topic target_topic = args.target_topic",
"topic = args.topic target_topic = args.target_topic kafka_broker = args.kafka_broker KafkaSpark = spark_streaming(topic, target_topic,",
"args.topic target_topic = args.target_topic kafka_broker = args.kafka_broker KafkaSpark = spark_streaming(topic, target_topic, kafka_broker) KafkaSpark.run()",
": self.kafka_broker}) return directKafkaStream def run(self): direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation with",
"res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send processed data to {}, {}\".format(self.target_topic, msg)) except",
"= target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc,",
"logging import atexit from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka",
"KafkaError as KE: self.logger.warning(\"Failed to send data, the error is {}\".format(msg)) def createStream(self):",
"# store back to kafka producer in another topic import argparse import json",
"the kafka broker\") args = parser.parse_args() topic = args.topic target_topic = args.target_topic kafka_broker",
"parser.parse_args() topic = args.topic target_topic = args.target_topic kafka_broker = args.kafka_broker KafkaSpark = spark_streaming(topic,",
"logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd): def group(record): data =",
"= newRDD.collect() for res in results: msg = {\"StockSymbol\": res[0], \"AveragePrice\": res[1]} try:",
"import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from kafka import",
"self.ssc.start() self.ssc.awaitTermination() if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"topic\", help=\"this is the",
"results: msg = {\"StockSymbol\": res[0], \"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send processed",
"= StreamingContext(sc, 5) logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd): def",
"send processed data to kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this is the kafka broker\") args",
"from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from kafka import KafkaProducer from",
"self.kafka_broker = kafka_broker self.target_topic = target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\", \"AveragePrice\")",
"to {}, {}\".format(self.target_topic, msg)) except KafkaError as KE: self.logger.warning(\"Failed to send data, the",
"# transformation with action self.ssc.start() self.ssc.awaitTermination() if __name__ == \"__main__\": parser = argparse.ArgumentParser()",
"\"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc, 5) logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def process(self,",
"return directKafkaStream def run(self): direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation with action self.ssc.start()",
"= logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd): def group(record): data = json.loads(record[1].decode('utf-8'))[0] return",
"# doing computation using spark streaming # store back to kafka producer in",
"def process(self, timeobj, rdd): def group(record): data = json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1)",
"def group(record): data = json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD = rdd.map(group).reduceByKey(lambda x,",
"sc = SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc, 5) logging.basicConfig() self.logger = logging.getLogger()",
"value=json.dumps(msg)) self.logger.info(\"Successfully send processed data to {}, {}\".format(self.target_topic, msg)) except KafkaError as KE:",
"store back to kafka producer in another topic import argparse import json import",
"# create space for data computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" : self.kafka_broker})",
"data from kafka producer\") parser.add_argument(\"target_topic\", help=\"this is the topic to send processed data",
"= KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\", \"AveragePrice\") sc.setLogLevel(\"INFO\") self.ssc = StreamingContext(sc, 5) logging.basicConfig() self.logger",
"computation directKafkaStream = KafkaUtils.createDirectStream(self.ssc, [self.topic], {\"metadata.broker.list\" : self.kafka_broker}) return directKafkaStream def run(self): direceKafkaStream",
"self.logger.warning(\"Failed to send data, the error is {}\".format(msg)) def createStream(self): # create space",
"__init__(self, topic, target_topic, kafka_broker): self.topic = topic self.kafka_broker = kafka_broker self.target_topic = target_topic",
"import logging import atexit from pyspark import SparkContext from pyspark.streaming import StreamingContext from",
"parser.add_argument(\"kafka_broker\", help=\"this is the kafka broker\") args = parser.parse_args() topic = args.topic target_topic",
"argparse import json import logging import atexit from pyspark import SparkContext from pyspark.streaming",
"data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD = rdd.map(group).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1]))\\ .map(lambda symbol, price",
"def __init__(self, topic, target_topic, kafka_broker): self.topic = topic self.kafka_broker = kafka_broker self.target_topic =",
"direceKafkaStream = self.createStream() direceKafkaStream.foreachRDD(self.process) # transformation with action self.ssc.start() self.ssc.awaitTermination() if __name__ ==",
"topic self.kafka_broker = kafka_broker self.target_topic = target_topic self.kafka_producer = KafkaProducer(bootrap_servers=kafka_broker) sc = SparkContext(\"local[2]\",",
"logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd): def group(record): data = json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"),",
"for res in results: msg = {\"StockSymbol\": res[0], \"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg))",
"self.ssc = StreamingContext(sc, 5) logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) def process(self, timeobj, rdd):",
"import json import logging import atexit from pyspark import SparkContext from pyspark.streaming import",
"import KafkaUtils from kafka import KafkaProducer from kafka.errors import KafkaError class spark_streaming(): def",
"producer in another topic import argparse import json import logging import atexit from",
"SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from kafka import KafkaProducer",
"(symbol, price[0]/price[1])) results = newRDD.collect() for res in results: msg = {\"StockSymbol\": res[0],",
"to receive data from kafka producer\") parser.add_argument(\"target_topic\", help=\"this is the topic to send",
"args = parser.parse_args() topic = args.topic target_topic = args.target_topic kafka_broker = args.kafka_broker KafkaSpark",
"processed data to kafka broker\") parser.add_argument(\"kafka_broker\", help=\"this is the kafka broker\") args =",
"import argparse import json import logging import atexit from pyspark import SparkContext from",
"{\"StockSymbol\": res[0], \"AveragePrice\": res[1]} try: self.kafka_producer.send(self.target_topic, value=json.dumps(msg)) self.logger.info(\"Successfully send processed data to {},",
"process(self, timeobj, rdd): def group(record): data = json.loads(record[1].decode('utf-8'))[0] return data.get(\"StockSymbol\"), (float(data.get(\"LastTradePrice\")), 1) newRDD",
"to send data, the error is {}\".format(msg)) def createStream(self): # create space for"
] |
[
"start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def parse(self, response): json_data = response.json() res_list",
"item = WallstreetcnItem() resource = res[\"resource\"] title = resource[\"title\"] display_time = resource[\"display_time\"] url",
"= 'wallstreetcn' allowed_domains = ['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def parse(self,",
"category_id = get_category_by_name(name) def parse(self, response): json_data = response.json() res_list = json_data[\"data\"][\"items\"] for",
"resource[\"display_time\"] url = resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"] item[\"title\"] = title item[\"url\"] = url",
"resource[\"author\"][\"display_name\"] item[\"title\"] = title item[\"url\"] = url item[\"hot_val\"] = hot_val item[\"rank\"] = display_time",
"item[\"url\"] = url item[\"hot_val\"] = hot_val item[\"rank\"] = display_time item[\"category_id\"] = self.category_id yield",
"WallstreetcnItem from news_spider.utils.common import get_category_by_name class WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn' allowed_domains = ['https://api.wallstcn.com']",
"response): json_data = response.json() res_list = json_data[\"data\"][\"items\"] for res in res_list: item =",
"json_data = response.json() res_list = json_data[\"data\"][\"items\"] for res in res_list: item = WallstreetcnItem()",
"news_spider.utils.common import get_category_by_name class WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn' allowed_domains = ['https://api.wallstcn.com'] start_urls =",
"import get_category_by_name class WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn' allowed_domains = ['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide']",
"allowed_domains = ['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def parse(self, response): json_data",
"res[\"resource\"] title = resource[\"title\"] display_time = resource[\"display_time\"] url = resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"]",
"display_time = resource[\"display_time\"] url = resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"] item[\"title\"] = title item[\"url\"]",
"json_data[\"data\"][\"items\"] for res in res_list: item = WallstreetcnItem() resource = res[\"resource\"] title =",
"= resource[\"display_time\"] url = resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"] item[\"title\"] = title item[\"url\"] =",
"= title item[\"url\"] = url item[\"hot_val\"] = hot_val item[\"rank\"] = display_time item[\"category_id\"] =",
"for res in res_list: item = WallstreetcnItem() resource = res[\"resource\"] title = resource[\"title\"]",
"= res[\"resource\"] title = resource[\"title\"] display_time = resource[\"display_time\"] url = resource[\"uri\"] hot_val =",
"= url item[\"hot_val\"] = hot_val item[\"rank\"] = display_time item[\"category_id\"] = self.category_id yield item",
"['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def parse(self, response): json_data = response.json() res_list = json_data[\"data\"][\"items\"]",
"get_category_by_name class WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn' allowed_domains = ['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id",
"def parse(self, response): json_data = response.json() res_list = json_data[\"data\"][\"items\"] for res in res_list:",
"from news_spider.items import WallstreetcnItem from news_spider.utils.common import get_category_by_name class WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn'",
"res_list = json_data[\"data\"][\"items\"] for res in res_list: item = WallstreetcnItem() resource = res[\"resource\"]",
"= get_category_by_name(name) def parse(self, response): json_data = response.json() res_list = json_data[\"data\"][\"items\"] for res",
"resource = res[\"resource\"] title = resource[\"title\"] display_time = resource[\"display_time\"] url = resource[\"uri\"] hot_val",
"= resource[\"title\"] display_time = resource[\"display_time\"] url = resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"] item[\"title\"] =",
"= WallstreetcnItem() resource = res[\"resource\"] title = resource[\"title\"] display_time = resource[\"display_time\"] url =",
"= ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def parse(self, response): json_data = response.json() res_list =",
"hot_val = resource[\"author\"][\"display_name\"] item[\"title\"] = title item[\"url\"] = url item[\"hot_val\"] = hot_val item[\"rank\"]",
"import WallstreetcnItem from news_spider.utils.common import get_category_by_name class WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn' allowed_domains =",
"= json_data[\"data\"][\"items\"] for res in res_list: item = WallstreetcnItem() resource = res[\"resource\"] title",
"item[\"title\"] = title item[\"url\"] = url item[\"hot_val\"] = hot_val item[\"rank\"] = display_time item[\"category_id\"]",
"get_category_by_name(name) def parse(self, response): json_data = response.json() res_list = json_data[\"data\"][\"items\"] for res in",
"WallstreetcnItem() resource = res[\"resource\"] title = resource[\"title\"] display_time = resource[\"display_time\"] url = resource[\"uri\"]",
"WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn' allowed_domains = ['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name)",
"= resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"] item[\"title\"] = title item[\"url\"] = url item[\"hot_val\"] =",
"class WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn' allowed_domains = ['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id =",
"= response.json() res_list = json_data[\"data\"][\"items\"] for res in res_list: item = WallstreetcnItem() resource",
"news_spider.items import WallstreetcnItem from news_spider.utils.common import get_category_by_name class WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn' allowed_domains",
"resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"] item[\"title\"] = title item[\"url\"] = url item[\"hot_val\"] = hot_val",
"scrapy from news_spider.items import WallstreetcnItem from news_spider.utils.common import get_category_by_name class WallstreetcnSpider(scrapy.Spider): name =",
"title = resource[\"title\"] display_time = resource[\"display_time\"] url = resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"] item[\"title\"]",
"= ['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def parse(self, response): json_data =",
"res_list: item = WallstreetcnItem() resource = res[\"resource\"] title = resource[\"title\"] display_time = resource[\"display_time\"]",
"title item[\"url\"] = url item[\"hot_val\"] = hot_val item[\"rank\"] = display_time item[\"category_id\"] = self.category_id",
"url = resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"] item[\"title\"] = title item[\"url\"] = url item[\"hot_val\"]",
"res in res_list: item = WallstreetcnItem() resource = res[\"resource\"] title = resource[\"title\"] display_time",
"response.json() res_list = json_data[\"data\"][\"items\"] for res in res_list: item = WallstreetcnItem() resource =",
"name = 'wallstreetcn' allowed_domains = ['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def",
"= resource[\"author\"][\"display_name\"] item[\"title\"] = title item[\"url\"] = url item[\"hot_val\"] = hot_val item[\"rank\"] =",
"parse(self, response): json_data = response.json() res_list = json_data[\"data\"][\"items\"] for res in res_list: item",
"['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def parse(self, response): json_data = response.json()",
"resource[\"title\"] display_time = resource[\"display_time\"] url = resource[\"uri\"] hot_val = resource[\"author\"][\"display_name\"] item[\"title\"] = title",
"from news_spider.utils.common import get_category_by_name class WallstreetcnSpider(scrapy.Spider): name = 'wallstreetcn' allowed_domains = ['https://api.wallstcn.com'] start_urls",
"in res_list: item = WallstreetcnItem() resource = res[\"resource\"] title = resource[\"title\"] display_time =",
"'wallstreetcn' allowed_domains = ['https://api.wallstcn.com'] start_urls = ['https://api.wallstcn.com/apiv1/content/information-flow?channel=global&accept=article&limit=20&action=upglide'] category_id = get_category_by_name(name) def parse(self, response):",
"import scrapy from news_spider.items import WallstreetcnItem from news_spider.utils.common import get_category_by_name class WallstreetcnSpider(scrapy.Spider): name"
] |
[
"end <= max: break else: print(f'Please enter a number between {min} and {max}')",
"print(f'Please enter a number between {min} and {max}') while True: end = get_num_int('Enter",
"a list in a cleaner way\"\"\" string = '' for i in range(len(lst)):",
"get_num_int(prompt: str) -> int: \"\"\"Function to check if users input is an integer\"\"\"",
"number of slice: ') if start <= end <= max: break else: print(f'Please",
"0: if i % 10 == 0: string += '\\n' print(string) def get_num_int(prompt:",
"10 == 0: string += '\\n' print(string) def get_num_int(prompt: str) -> int: \"\"\"Function",
"input is an integer\"\"\" while True: try: number = int(input(prompt)) return number except",
"i == len(lst) - 1: string += f'{lst[i]}.' else: string += f'{lst[i]}, '",
"Show the user a line of text from your favourite poem and #",
"{min} and {max}') return sl[start: end] if __name__ == '__main__': poem = 'line",
"is an integer\"\"\" while True: try: number = int(input(prompt)) return number except Exception",
"else: string += f'{lst[i]}, ' if i > 0: if i % 10",
"very similar to challenge 74 from typing import List def print_list(lst: List): \"\"\"prints",
"-> int: \"\"\"Function to check if users input is an integer\"\"\" while True:",
"# very similar to challenge 74 from typing import List def print_list(lst: List):",
"enter a number between {min} and {max}') while True: end = get_num_int('Enter end",
"try: number = int(input(prompt)) return number except Exception as e: print(e) def get_slice(sl):",
"break else: print(f'Please enter a number between {min} and {max}') while True: end",
"end = get_num_int('Enter end number of slice: ') if start <= end <=",
"print(f'Please enter a number between {min} and {max}') return sl[start: end] if __name__",
"ending point. Display the characters # between those two points. # very similar",
"return sl[start: end] if __name__ == '__main__': poem = 'line from poem' print(poem)",
"import List def print_list(lst: List): \"\"\"prints a list in a cleaner way\"\"\" string",
"number = int(input(prompt)) return number except Exception as e: print(e) def get_slice(sl): min,",
"start = get_num_int('Enter starting number of slice: ') if min <= start <=",
"% 10 == 0: string += '\\n' print(string) def get_num_int(prompt: str) -> int:",
"print_list(lst: List): \"\"\"prints a list in a cleaner way\"\"\" string = '' for",
"{min} and {max}') while True: end = get_num_int('Enter end number of slice: ')",
"between {min} and {max}') while True: end = get_num_int('Enter end number of slice:",
"82.py<gh_stars>0 # 082 # Show the user a line of text from your",
"i in range(len(lst)): if i == len(lst) - 1: string += f'{lst[i]}.' else:",
"List def print_list(lst: List): \"\"\"prints a list in a cleaner way\"\"\" string =",
"of text from your favourite poem and # ask for a starting and",
"# between those two points. # very similar to challenge 74 from typing",
"return number except Exception as e: print(e) def get_slice(sl): min, max = 0,",
"an integer\"\"\" while True: try: number = int(input(prompt)) return number except Exception as",
"if users input is an integer\"\"\" while True: try: number = int(input(prompt)) return",
"= get_num_int('Enter starting number of slice: ') if min <= start <= max:",
"line of text from your favourite poem and # ask for a starting",
"to challenge 74 from typing import List def print_list(lst: List): \"\"\"prints a list",
"+= f'{lst[i]}.' else: string += f'{lst[i]}, ' if i > 0: if i",
"print(e) def get_slice(sl): min, max = 0, len(sl) while True: start = get_num_int('Enter",
"number between {min} and {max}') return sl[start: end] if __name__ == '__main__': poem",
"== 0: string += '\\n' print(string) def get_num_int(prompt: str) -> int: \"\"\"Function to",
"for a starting and ending point. Display the characters # between those two",
"if i % 10 == 0: string += '\\n' print(string) def get_num_int(prompt: str)",
"those two points. # very similar to challenge 74 from typing import List",
"\"\"\"Function to check if users input is an integer\"\"\" while True: try: number",
"between those two points. # very similar to challenge 74 from typing import",
"True: end = get_num_int('Enter end number of slice: ') if start <= end",
"{max}') while True: end = get_num_int('Enter end number of slice: ') if start",
"typing import List def print_list(lst: List): \"\"\"prints a list in a cleaner way\"\"\"",
"if min <= start <= max: break else: print(f'Please enter a number between",
"while True: try: number = int(input(prompt)) return number except Exception as e: print(e)",
"check if users input is an integer\"\"\" while True: try: number = int(input(prompt))",
"challenge 74 from typing import List def print_list(lst: List): \"\"\"prints a list in",
"<= max: break else: print(f'Please enter a number between {min} and {max}') return",
"string = '' for i in range(len(lst)): if i == len(lst) - 1:",
"get_num_int('Enter end number of slice: ') if start <= end <= max: break",
"between {min} and {max}') return sl[start: end] if __name__ == '__main__': poem =",
"= '' for i in range(len(lst)): if i == len(lst) - 1: string",
"# Show the user a line of text from your favourite poem and",
"i % 10 == 0: string += '\\n' print(string) def get_num_int(prompt: str) ->",
"while True: end = get_num_int('Enter end number of slice: ') if start <=",
"def get_num_int(prompt: str) -> int: \"\"\"Function to check if users input is an",
"i > 0: if i % 10 == 0: string += '\\n' print(string)",
"except Exception as e: print(e) def get_slice(sl): min, max = 0, len(sl) while",
"else: print(f'Please enter a number between {min} and {max}') return sl[start: end] if",
"== len(lst) - 1: string += f'{lst[i]}.' else: string += f'{lst[i]}, ' if",
"082 # Show the user a line of text from your favourite poem",
"a starting and ending point. Display the characters # between those two points.",
"if i == len(lst) - 1: string += f'{lst[i]}.' else: string += f'{lst[i]},",
"f'{lst[i]}.' else: string += f'{lst[i]}, ' if i > 0: if i %",
"if i > 0: if i % 10 == 0: string += '\\n'",
"' if i > 0: if i % 10 == 0: string +=",
"integer\"\"\" while True: try: number = int(input(prompt)) return number except Exception as e:",
"number of slice: ') if min <= start <= max: break else: print(f'Please",
"the user a line of text from your favourite poem and # ask",
"sl[start: end] if __name__ == '__main__': poem = 'line from poem' print(poem) print_list(get_slice(poem))",
"points. # very similar to challenge 74 from typing import List def print_list(lst:",
"\"\"\"prints a list in a cleaner way\"\"\" string = '' for i in",
"a cleaner way\"\"\" string = '' for i in range(len(lst)): if i ==",
"max: break else: print(f'Please enter a number between {min} and {max}') return sl[start:",
"a line of text from your favourite poem and # ask for a",
"in range(len(lst)): if i == len(lst) - 1: string += f'{lst[i]}.' else: string",
"start <= end <= max: break else: print(f'Please enter a number between {min}",
"> 0: if i % 10 == 0: string += '\\n' print(string) def",
"80 - 87/Challenge 82.py<gh_stars>0 # 082 # Show the user a line of",
"slice: ') if min <= start <= max: break else: print(f'Please enter a",
"74 from typing import List def print_list(lst: List): \"\"\"prints a list in a",
"<= max: break else: print(f'Please enter a number between {min} and {max}') while",
"from your favourite poem and # ask for a starting and ending point.",
"get_num_int('Enter starting number of slice: ') if min <= start <= max: break",
"else: print(f'Please enter a number between {min} and {max}') while True: end =",
"<filename>150-Challenges/Challenges 80 - 87/Challenge 82.py<gh_stars>0 # 082 # Show the user a line",
"point. Display the characters # between those two points. # very similar to",
"'\\n' print(string) def get_num_int(prompt: str) -> int: \"\"\"Function to check if users input",
"= get_num_int('Enter end number of slice: ') if start <= end <= max:",
"get_slice(sl): min, max = 0, len(sl) while True: start = get_num_int('Enter starting number",
"start <= max: break else: print(f'Please enter a number between {min} and {max}')",
"and ending point. Display the characters # between those two points. # very",
"len(sl) while True: start = get_num_int('Enter starting number of slice: ') if min",
"the characters # between those two points. # very similar to challenge 74",
"while True: start = get_num_int('Enter starting number of slice: ') if min <=",
"of slice: ') if start <= end <= max: break else: print(f'Please enter",
"text from your favourite poem and # ask for a starting and ending",
"string += f'{lst[i]}.' else: string += f'{lst[i]}, ' if i > 0: if",
"list in a cleaner way\"\"\" string = '' for i in range(len(lst)): if",
"string += '\\n' print(string) def get_num_int(prompt: str) -> int: \"\"\"Function to check if",
"a number between {min} and {max}') return sl[start: end] if __name__ == '__main__':",
"min <= start <= max: break else: print(f'Please enter a number between {min}",
"= 0, len(sl) while True: start = get_num_int('Enter starting number of slice: ')",
"len(lst) - 1: string += f'{lst[i]}.' else: string += f'{lst[i]}, ' if i",
"ask for a starting and ending point. Display the characters # between those",
"starting number of slice: ') if min <= start <= max: break else:",
"<= end <= max: break else: print(f'Please enter a number between {min} and",
"to check if users input is an integer\"\"\" while True: try: number =",
"end number of slice: ') if start <= end <= max: break else:",
"and {max}') return sl[start: end] if __name__ == '__main__': poem = 'line from",
"') if min <= start <= max: break else: print(f'Please enter a number",
"similar to challenge 74 from typing import List def print_list(lst: List): \"\"\"prints a",
"0, len(sl) while True: start = get_num_int('Enter starting number of slice: ') if",
"your favourite poem and # ask for a starting and ending point. Display",
"'' for i in range(len(lst)): if i == len(lst) - 1: string +=",
"int: \"\"\"Function to check if users input is an integer\"\"\" while True: try:",
"87/Challenge 82.py<gh_stars>0 # 082 # Show the user a line of text from",
"in a cleaner way\"\"\" string = '' for i in range(len(lst)): if i",
"Display the characters # between those two points. # very similar to challenge",
"- 1: string += f'{lst[i]}.' else: string += f'{lst[i]}, ' if i >",
"int(input(prompt)) return number except Exception as e: print(e) def get_slice(sl): min, max =",
"and {max}') while True: end = get_num_int('Enter end number of slice: ') if",
"+= '\\n' print(string) def get_num_int(prompt: str) -> int: \"\"\"Function to check if users",
"= int(input(prompt)) return number except Exception as e: print(e) def get_slice(sl): min, max",
"characters # between those two points. # very similar to challenge 74 from",
"and # ask for a starting and ending point. Display the characters #",
"user a line of text from your favourite poem and # ask for",
"enter a number between {min} and {max}') return sl[start: end] if __name__ ==",
"from typing import List def print_list(lst: List): \"\"\"prints a list in a cleaner",
"def print_list(lst: List): \"\"\"prints a list in a cleaner way\"\"\" string = ''",
"two points. # very similar to challenge 74 from typing import List def",
"range(len(lst)): if i == len(lst) - 1: string += f'{lst[i]}.' else: string +=",
"number except Exception as e: print(e) def get_slice(sl): min, max = 0, len(sl)",
"f'{lst[i]}, ' if i > 0: if i % 10 == 0: string",
"# 082 # Show the user a line of text from your favourite",
"users input is an integer\"\"\" while True: try: number = int(input(prompt)) return number",
"max: break else: print(f'Please enter a number between {min} and {max}') while True:",
"cleaner way\"\"\" string = '' for i in range(len(lst)): if i == len(lst)",
"e: print(e) def get_slice(sl): min, max = 0, len(sl) while True: start =",
"List): \"\"\"prints a list in a cleaner way\"\"\" string = '' for i",
"slice: ') if start <= end <= max: break else: print(f'Please enter a",
"max = 0, len(sl) while True: start = get_num_int('Enter starting number of slice:",
"if start <= end <= max: break else: print(f'Please enter a number between",
"break else: print(f'Please enter a number between {min} and {max}') return sl[start: end]",
"as e: print(e) def get_slice(sl): min, max = 0, len(sl) while True: start",
"min, max = 0, len(sl) while True: start = get_num_int('Enter starting number of",
"of slice: ') if min <= start <= max: break else: print(f'Please enter",
"True: try: number = int(input(prompt)) return number except Exception as e: print(e) def",
"poem and # ask for a starting and ending point. Display the characters",
"starting and ending point. Display the characters # between those two points. #",
"<= start <= max: break else: print(f'Please enter a number between {min} and",
"') if start <= end <= max: break else: print(f'Please enter a number",
"Exception as e: print(e) def get_slice(sl): min, max = 0, len(sl) while True:",
"number between {min} and {max}') while True: end = get_num_int('Enter end number of",
"True: start = get_num_int('Enter starting number of slice: ') if min <= start",
"str) -> int: \"\"\"Function to check if users input is an integer\"\"\" while",
"+= f'{lst[i]}, ' if i > 0: if i % 10 == 0:",
"def get_slice(sl): min, max = 0, len(sl) while True: start = get_num_int('Enter starting",
"# ask for a starting and ending point. Display the characters # between",
"a number between {min} and {max}') while True: end = get_num_int('Enter end number",
"for i in range(len(lst)): if i == len(lst) - 1: string += f'{lst[i]}.'",
"{max}') return sl[start: end] if __name__ == '__main__': poem = 'line from poem'",
"0: string += '\\n' print(string) def get_num_int(prompt: str) -> int: \"\"\"Function to check",
"favourite poem and # ask for a starting and ending point. Display the",
"way\"\"\" string = '' for i in range(len(lst)): if i == len(lst) -",
"- 87/Challenge 82.py<gh_stars>0 # 082 # Show the user a line of text",
"print(string) def get_num_int(prompt: str) -> int: \"\"\"Function to check if users input is",
"1: string += f'{lst[i]}.' else: string += f'{lst[i]}, ' if i > 0:",
"string += f'{lst[i]}, ' if i > 0: if i % 10 =="
] |
[
"from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.http import",
"HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset, 'formID':pdfid } #print(context) template = loader.get_template('rearrangeformquestions.html') return HttpResponse(template.render(context, request))",
"to be made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the Join combinedDF=PDFFieldsDF.join(userFieldDF,",
"\"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData) template =",
"pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\" metaData = { '/Title':",
"context = { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context) template =",
"\"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context) template = loader.get_template('process_form.html') return HttpResponse(template.render(context, request))",
", } template = loader.get_template('formsList.html') return HttpResponse(template.render(context, request)) @login_required def addFormToProfile(request,form_id): #return HttpResponse(str(form_id))",
"if(not superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset, 'formID':pdfid } #print(context) template = loader.get_template('rearrangeformquestions.html')",
"HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs is not",
"#missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for question in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \",",
"made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right')",
"return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) @login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all() context = { 'systemforms':pdfforms",
"on='field',lsuffix='_left', rsuffix='_right') #remove rows with NA Values. Will happen when the number of",
"@login_required def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset, 'formID':pdfid",
"def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset, 'formID':pdfid }",
"in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid)) def logoutUser(request):",
"#dprint.dprint(fieldsinPDF) context = { \"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid } #print(formData) template = loader.get_template('editPDF.html')",
"return redirect('login') @login_required def fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use the dataset",
"userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData) template = loader.get_template('base_view_profile.html') context =",
") #print(userFields) #print(fieldsinPDF) #Set the column as index on which the join is",
"pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF) context",
"return HttpResponse(template.render(context, request)) def loginForm(request): context = { 'errors': \"\", } template =",
"the Dataframe by Field Page Number, then convert it to a list of",
"of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for question",
"is to be made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the Join",
"request)) @login_required def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request,",
"above datasets differ in count. #combinedDF.dropna(0,inplace=True) #sort the Dataframe by Field Page Number,",
"\"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount } #print(context) return HttpResponse(template.render(context, request)) @login_required def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user,",
"return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset, 'formID':pdfid } #print(context) template = loader.get_template('rearrangeformquestions.html') return HttpResponse(template.render(context,",
"return redirect('systemForms') else: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) @login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all() context",
"redirect('login') @login_required def fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use the dataset as",
"in count. #combinedDF.dropna(0,inplace=True) #sort the Dataframe by Field Page Number, then convert it",
"dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use the dataset as input to generate the pdf,",
"def homePage(request): template = loader.get_template('base_intro.html') context = { } return HttpResponse(template.render(context, request)) def",
"question in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context =",
"user is not None: login(request, user) return redirect('systemForms') else: return redirect('%s?next=%s' % (settings.LOGIN_URL,",
"dateutil.parser import * def homePage(request): template = loader.get_template('base_intro.html') context = { } return",
"logout(request) return redirect('login') @login_required def fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use the",
"pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove rows",
"None): fieldIDList=fieldIDs.split(\",\") for fieldID in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user)",
"the responseobject pdfData.write(response) #response.write(pdfData) #return the response return response @login_required def profile(request): #",
"import * from django.conf import settings from django.shortcuts import redirect from utils import",
"= authenticate(request, username=username, password=password) #print(user) if user is not None: login(request, user) return",
"None: login(request, user) return redirect('systemForms') else: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) @login_required def",
"logout from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.utils.dateparse import parse_date",
"#print(fieldsinPDF) #Set the column as index on which the join is to be",
"saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs is not None): fieldIDList=fieldIDs.split(\",\") for fieldID in",
"else: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) @login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all() context = {",
"to User in UserProfile and that match the fields in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list(",
"loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all",
"column as index on which the join is to be made in pandas",
"import parse_date import datetime from dateutil.parser import * def homePage(request): template = loader.get_template('base_intro.html')",
"Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove rows with NA Values. Will happen when the",
"differ in count. #combinedDF.dropna(0,inplace=True) #sort the Dataframe by Field Page Number, then convert",
"filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\" metaData = { '/Title': filename, } pdfData.addMetadata(metaData) #Set",
"missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context = { 'formObject':PDFormObject,",
"#print(context) template = loader.get_template('process_form.html') return HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"]",
"= { '/Title': filename, } pdfData.addMetadata(metaData) #Set the httpresponse to download a pdf",
"import settings from django.shortcuts import redirect from utils import dataLayerPDF from utils import",
"join is to be made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the",
"utils import dprint from utils import modelUtils import pandas as pd from django.contrib.auth",
"loader.get_template('base_view_profile.html') context = { \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount } #print(context) return HttpResponse(template.render(context, request)) @login_required",
"responseobject pdfData.write(response) #response.write(pdfData) #return the response return response @login_required def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\",",
"= { \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount } #print(context) return HttpResponse(template.render(context, request)) @login_required def editPDFLive(request,",
"rsuffix='_right') #remove rows with NA Values. Will happen when the number of rows",
"HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename= \"%s\"' % filename #response.write(PDFBytes) #write the pdfdata to",
"django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.utils.dateparse import parse_date import datetime",
"from django.utils.dateparse import parse_date import datetime from dateutil.parser import * def homePage(request): template",
"pandas as pd from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required",
"userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", # \"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\")",
"arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset, 'formID':pdfid } #print(context)",
"#get all fields in PDF related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\",",
"redirect from utils import dataLayerPDF from utils import dprint from utils import modelUtils",
"return HttpResponse(template.render(context, request)) @login_required def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not found\");",
"user = authenticate(request, username=username, password=password) #print(user) if user is not None: login(request, user)",
"the fields in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\", named=True ) #print(userFields) #print(fieldsinPDF)",
"login(request, user) return redirect('systemForms') else: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) @login_required def viewSystemForms(request):",
"HttpResponse(template.render(context, request)) @login_required def addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count()",
"the join is to be made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make",
"a pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename= \"%s\"' % filename #response.write(PDFBytes)",
"#Set the column as index on which the join is to be made",
"} #dprint.dprint(missingQuestionsList) #print(context) template = loader.get_template('process_form.html') return HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid):",
"% (settings.LOGIN_URL, request.path)) @login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all() context = { 'systemforms':pdfforms , }",
"named=True ) #get all fields Related to User in UserProfile and that match",
"missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for question in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\"",
"+ str(timestamp) +\".pdf\" metaData = { '/Title': filename, } pdfData.addMetadata(metaData) #Set the httpresponse",
"= loader.get_template('base_intro.html') context = { } return HttpResponse(template.render(context, request)) def loginForm(request): context =",
"HttpResponse(template.render(context, request)) @login_required def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not found\"); dataSet,",
"return HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs is",
"the dataset as input to generate the pdf, recieve a buffer as reponse",
"pdfid) #print(dataSet) #Use the dataset as input to generate the pdf, recieve a",
"with NA Values. Will happen when the number of rows in the above",
"Values. Will happen when the number of rows in the above datasets differ",
"from utils import modelUtils import pandas as pd from django.contrib.auth import authenticate, login,",
"by Field Page Number, then convert it to a list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records')",
"metaData = { '/Title': filename, } pdfData.addMetadata(metaData) #Set the httpresponse to download a",
"if(fieldIDs is not None): fieldIDList=fieldIDs.split(\",\") for fieldID in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict)",
"PDFormObject) #get all fields in PDF related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\",",
"def fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use the dataset as input to",
") userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData) template = loader.get_template('base_view_profile.html') context",
"in the above datasets differ in count. #combinedDF.dropna(0,inplace=True) #sort the Dataframe by Field",
"userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData) template = loader.get_template('base_view_profile.html') context = { \"systemforms\":userForms,",
"PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\", named=True ) #print(userFields) #print(fieldsinPDF) #Set the column as",
"datasets differ in count. #combinedDF.dropna(0,inplace=True) #sort the Dataframe by Field Page Number, then",
"password = request.POST['password'] user = authenticate(request, username=username, password=password) #print(user) if user is not",
"editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF)",
"request.POST['password'] user = authenticate(request, username=username, password=password) #print(user) if user is not None: login(request,",
"PDF related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\", named=True ) #get",
"'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context) template = loader.get_template('process_form.html') return HttpResponse(template.render(context,",
"@login_required def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid,",
"addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save()",
"Page Number, then convert it to a list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC']",
"#Set the httpresponse to download a pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline;",
"pdfid, False) #dprint.dprint(fieldsinPDF) context = { \"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid } #print(formData) template",
"{ 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context) template = loader.get_template('process_form.html') return",
"a buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\"",
"@login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs is not None): fieldIDList=fieldIDs.split(\",\")",
"fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request) return redirect('login') @login_required def",
"NA Values. Will happen when the number of rows in the above datasets",
"missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for question in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \"",
"= HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename= \"%s\"' % filename #response.write(PDFBytes) #write the pdfdata",
"# ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData) template = loader.get_template('base_view_profile.html')",
"\"field__field_state\", \"field__field_description\", named=True ) #get all fields Related to User in UserProfile and",
"# \"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData) template",
"response return response @login_required def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", # \"pdf__image\", #",
"import loader from .models import * from django.conf import settings from django.shortcuts import",
"django.conf import settings from django.shortcuts import redirect from utils import dataLayerPDF from utils",
"from django.conf import settings from django.shortcuts import redirect from utils import dataLayerPDF from",
"redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) @login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all() context = { 'systemforms':pdfforms ,",
"= loader.get_template('formsList.html') return HttpResponse(template.render(context, request)) @login_required def addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user",
"'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context) template = loader.get_template('process_form.html') return HttpResponse(template.render(context, request)) @login_required",
"the pdfdata to the responseobject pdfData.write(response) #response.write(pdfData) #return the response return response @login_required",
"# \"pdf__pdf_description\", # \"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count()",
"return redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request) return redirect('login') @login_required def fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request,",
"* def homePage(request): template = loader.get_template('base_intro.html') context = { } return HttpResponse(template.render(context, request))",
"return response @login_required def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", # \"pdf__image\", # )",
"if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all fields in PDF related to",
"#return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject,",
"from django.shortcuts import redirect from utils import dataLayerPDF from utils import dprint from",
"and that match the fields in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\", named=True",
"timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\" metaData = { '/Title': filename, } pdfData.addMetadata(metaData)",
"logoutUser(request): logout(request) return redirect('login') @login_required def fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use",
"user) return redirect('systemForms') else: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) @login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all()",
"settings from django.shortcuts import redirect from utils import dataLayerPDF from utils import dprint",
"#Make the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove rows with NA Values. Will happen",
"\"field__field_description\", named=True ) #get all fields Related to User in UserProfile and that",
"def loginUser(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password)",
"pdfdata to the responseobject pdfData.write(response) #response.write(pdfData) #return the response return response @login_required def",
"index on which the join is to be made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field')",
"#print(context) return HttpResponse(template.render(context, request)) @login_required def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not",
"fields in PDF related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\", named=True",
"% filename #response.write(PDFBytes) #write the pdfdata to the responseobject pdfData.write(response) #response.write(pdfData) #return the",
"@login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all() context = { 'systemforms':pdfforms , } template = loader.get_template('formsList.html')",
"httpresponse to download a pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename= \"%s\"'",
"fields Related to User in UserProfile and that match the fields in the",
"fieldID in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid)) def",
"template = loader.get_template('base_intro.html') context = { } return HttpResponse(template.render(context, request)) def loginForm(request): context",
"loader.get_template('process_form.html') return HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs",
"django.views.decorators.http import require_http_methods from django.utils.dateparse import parse_date import datetime from dateutil.parser import *",
"filename #response.write(PDFBytes) #write the pdfdata to the responseobject pdfData.write(response) #response.write(pdfData) #return the response",
"def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", # \"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by(",
"number of rows in the above datasets differ in count. #combinedDF.dropna(0,inplace=True) #sort the",
"authenticate(request, username=username, password=password) #print(user) if user is not None: login(request, user) return redirect('systemForms')",
"redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request) return redirect('login') @login_required def fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid)",
"loader.get_template('base_intro.html') context = { } return HttpResponse(template.render(context, request)) def loginForm(request): context = {",
"when the number of rows in the above datasets differ in count. #combinedDF.dropna(0,inplace=True)",
"'formID':pdfid } #print(formData) template = loader.get_template('editPDF.html') return HttpResponse(template.render(context, request)) @login_required def arrangeFormQuestions(request, pdfid):",
"django.utils.dateparse import parse_date import datetime from dateutil.parser import * def homePage(request): template =",
"#print(user) if user is not None: login(request, user) return redirect('systemForms') else: return redirect('%s?next=%s'",
"\",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context = { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList)",
"def addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject)",
"import redirect from utils import dataLayerPDF from utils import dprint from utils import",
"to a list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples))",
"combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove rows with NA Values. Will happen when the number",
"formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF) context = { \"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid } #print(formData)",
"count. #combinedDF.dropna(0,inplace=True) #sort the Dataframe by Field Page Number, then convert it to",
"in UserProfile and that match the fields in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\",",
"reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\" metaData = {",
"= { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context) template = loader.get_template('process_form.html')",
"fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request)",
"not None: login(request, user) return redirect('systemForms') else: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) @login_required",
"\"data_index\", named=True ) #print(userFields) #print(fieldsinPDF) #Set the column as index on which the",
"} template = loader.get_template('registration/login.html') return HttpResponse(template.render(context, request)) def loginUser(request): username = request.POST['username'] password",
"(settings.LOGIN_URL, request.path)) @login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all() context = { 'systemforms':pdfforms , } template",
"return HttpResponse(template.render(context, request)) def loginUser(request): username = request.POST['username'] password = request.POST['password'] user =",
"template = loader.get_template('registration/login.html') return HttpResponse(template.render(context, request)) def loginUser(request): username = request.POST['username'] password =",
"addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all fields in PDF related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\",",
"convert it to a list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str)",
"in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove",
"= request.POST['password'] user = authenticate(request, username=username, password=password) #print(user) if user is not None:",
"Dataframe by Field Page Number, then convert it to a list of dictionaries",
"the pdf, recieve a buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\"",
"the httpresponse to download a pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=",
"PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all fields in",
"'inline; filename= \"%s\"' % filename #response.write(PDFBytes) #write the pdfdata to the responseobject pdfData.write(response)",
"dataSet, formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF) context = { \"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid }",
"utils import modelUtils import pandas as pd from django.contrib.auth import authenticate, login, logout",
"to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\", named=True ) #get all fields",
"fieldIDList=[] fieldData=[] if(fieldIDs is not None): fieldIDList=fieldIDs.split(\",\") for fieldID in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID",
"as pd from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from",
"= { } return HttpResponse(template.render(context, request)) def loginForm(request): context = { 'errors': \"\",",
"numberOfMissingQuestions=len(missingQuestionTuples) context = { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context) template",
"filename= \"%s\"' % filename #response.write(PDFBytes) #write the pdfdata to the responseobject pdfData.write(response) #response.write(pdfData)",
"generate the pdf, recieve a buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name",
".models import * from django.conf import settings from django.shortcuts import redirect from utils",
"fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context = { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr",
"return HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF) context = { \"userFormDataSet\":dataSet, \"formData\":",
"{ '/Title': filename, } pdfData.addMetadata(metaData) #Set the httpresponse to download a pdf response",
"fields in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\", named=True ) #print(userFields) #print(fieldsinPDF) #Set",
"pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all fields in PDF related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list(",
"fieldIDList=fieldIDs.split(\",\") for fieldID in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return",
"= { 'systemforms':pdfforms , } template = loader.get_template('formsList.html') return HttpResponse(template.render(context, request)) @login_required def",
"Field Page Number, then convert it to a list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF)",
"loader.get_template('registration/login.html') return HttpResponse(template.render(context, request)) def loginUser(request): username = request.POST['username'] password = request.POST['password'] user",
"@login_required def fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use the dataset as input",
"= { \"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid } #print(formData) template = loader.get_template('editPDF.html') return HttpResponse(template.render(context,",
"modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request) return redirect('login') @login_required def fillForm(request, pdfid):",
"fieldIDStr=\"\" for question in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples)",
"HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF) context = { \"userFormDataSet\":dataSet, \"formData\": formData,",
"import dataLayerPDF from utils import dprint from utils import modelUtils import pandas as",
"from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.utils.dateparse import parse_date import",
"# #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\" metaData = { '/Title': filename,",
"missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for question in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\")",
"the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\", named=True ) #print(userFields) #print(fieldsinPDF) #Set the column",
"loader.get_template('formsList.html') return HttpResponse(template.render(context, request)) @login_required def addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id)",
"= 'inline; filename= \"%s\"' % filename #response.write(PDFBytes) #write the pdfdata to the responseobject",
"django.template import loader from .models import * from django.conf import settings from django.shortcuts",
"Related to User in UserProfile and that match the fields in the PDFForm",
"django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods",
"template = loader.get_template('editPDF.html') return HttpResponse(template.render(context, request)) @login_required def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not superUser):",
"to download a pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename= \"%s\"' %",
"request)) @login_required def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset,",
"from django.http import HttpResponse from django.template import loader from .models import * from",
"the column as index on which the join is to be made in",
"+str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context = { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id,",
"@login_required def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", # \"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms)",
"fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context = { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples,",
"Number, then convert it to a list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True)",
"context = { } return HttpResponse(template.render(context, request)) def loginForm(request): context = { 'errors':",
"= loader.get_template('process_form.html') return HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[]",
"\"field_text\", \"data_index\", named=True ) #print(userFields) #print(fieldsinPDF) #Set the column as index on which",
"formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use the dataset as input to generate the pdf, recieve",
"of rows in the above datasets differ in count. #combinedDF.dropna(0,inplace=True) #sort the Dataframe",
"#dprint.dprint(PDFFieldsDF) #Make the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove rows with NA Values. Will",
"in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\", named=True ) #print(userFields) #print(fieldsinPDF) #Set the",
"{ \"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid } #print(formData) template = loader.get_template('editPDF.html') return HttpResponse(template.render(context, request))",
"#combinedDF.dropna(0,inplace=True) #sort the Dataframe by Field Page Number, then convert it to a",
"login_required from django.views.decorators.http import require_http_methods from django.utils.dateparse import parse_date import datetime from dateutil.parser",
"#write the pdfdata to the responseobject pdfData.write(response) #response.write(pdfData) #return the response return response",
"\"field\", \"field_text\", \"data_index\", named=True ) #print(userFields) #print(fieldsinPDF) #Set the column as index on",
"request)) def loginForm(request): context = { 'errors': \"\", } template = loader.get_template('registration/login.html') return",
"#get all fields Related to User in UserProfile and that match the fields",
"{ } return HttpResponse(template.render(context, request)) def loginForm(request): context = { 'errors': \"\", }",
"\"pdf__pdf_description\", # \"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData)",
"\", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context = { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr }",
"the number of rows in the above datasets differ in count. #combinedDF.dropna(0,inplace=True) #sort",
"pdfforms=PDFForm.objects.all() context = { 'systemforms':pdfforms , } template = loader.get_template('formsList.html') return HttpResponse(template.render(context, request))",
"HttpResponse from django.template import loader from .models import * from django.conf import settings",
"login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.utils.dateparse import",
"@require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs is not None): fieldIDList=fieldIDs.split(\",\") for",
"template = loader.get_template('process_form.html') return HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[]",
"response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename= \"%s\"' % filename #response.write(PDFBytes) #write the",
"input to generate the pdf, recieve a buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs()",
"fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs is not None): fieldIDList=fieldIDs.split(\",\") for fieldID in fieldIDList: fieldDict={}",
"all fields Related to User in UserProfile and that match the fields in",
"match the fields in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\", named=True ) #print(userFields)",
"HttpResponse(template.render(context, request)) @login_required def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={",
"a list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\"",
"then convert it to a list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True)",
"pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename= \"%s\"' % filename #response.write(PDFBytes) #write",
"# userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", # \"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\",",
"{ 'systemforms':pdfforms , } template = loader.get_template('formsList.html') return HttpResponse(template.render(context, request)) @login_required def addFormToProfile(request,form_id):",
"homePage(request): template = loader.get_template('base_intro.html') context = { } return HttpResponse(template.render(context, request)) def loginForm(request):",
"#print(type(missingQuestionTuples)) fieldIDStr=\"\" for question in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr)",
"superUser=request.user.is_superuser if(not superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset, 'formID':pdfid } #print(context) template =",
"loader from .models import * from django.conf import settings from django.shortcuts import redirect",
"formData, 'formID':pdfid } #print(formData) template = loader.get_template('editPDF.html') return HttpResponse(template.render(context, request)) @login_required def arrangeFormQuestions(request,",
"django.http import HttpResponse from django.template import loader from .models import * from django.conf",
"errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get",
"formsCount=userForms.count() #print(userData) template = loader.get_template('base_view_profile.html') context = { \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount } #print(context)",
"the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove rows with NA Values. Will happen when",
"the response return response @login_required def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", # \"pdf__image\",",
"buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\" metaData",
"#print(userFields) #print(fieldsinPDF) #Set the column as index on which the join is to",
"dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for question in",
"request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) #print(user) if user is",
"#remove rows with NA Values. Will happen when the number of rows in",
"return HttpResponse(template.render(context, request)) @login_required def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field')",
") #get all fields Related to User in UserProfile and that match the",
"pd from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.http",
"#print(formData) template = loader.get_template('editPDF.html') return HttpResponse(template.render(context, request)) @login_required def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not",
"template = loader.get_template('formsList.html') return HttpResponse(template.render(context, request)) @login_required def addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id",
"be made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left',",
"import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from",
"\"userData\":userData, \"formcount\":formsCount } #print(context) return HttpResponse(template.render(context, request)) @login_required def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count()",
"\"field__field_question\", \"field__field_state\", \"field__field_description\", named=True ) #get all fields Related to User in UserProfile",
"= loader.get_template('editPDF.html') return HttpResponse(template.render(context, request)) @login_required def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not superUser): return",
"require_http_methods from django.utils.dateparse import parse_date import datetime from dateutil.parser import * def homePage(request):",
"#output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\" metaData = { '/Title': filename, }",
"the above datasets differ in count. #combinedDF.dropna(0,inplace=True) #sort the Dataframe by Field Page",
"= loader.get_template('registration/login.html') return HttpResponse(template.render(context, request)) def loginUser(request): username = request.POST['username'] password = request.POST['password']",
"parse_date import datetime from dateutil.parser import * def homePage(request): template = loader.get_template('base_intro.html') context",
"modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all fields in PDF related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\",",
"+\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\" metaData = { '/Title': filename, } pdfData.addMetadata(metaData) #Set the",
"def viewSystemForms(request): pdfforms=PDFForm.objects.all() context = { 'systemforms':pdfforms , } template = loader.get_template('formsList.html') return",
"Will happen when the number of rows in the above datasets differ in",
"rows in the above datasets differ in count. #combinedDF.dropna(0,inplace=True) #sort the Dataframe by",
"\"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData) template = loader.get_template('base_view_profile.html') context = { \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount",
"fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\", named=True ) #get all fields Related to",
"recieve a buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp)",
"#sort the Dataframe by Field Page Number, then convert it to a list",
"#dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for question in missingQuestionTuples:",
"related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\", named=True ) #get all",
"HttpResponse(template.render(context, request)) def loginForm(request): context = { 'errors': \"\", } template = loader.get_template('registration/login.html')",
"request.path)) @login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all() context = { 'systemforms':pdfforms , } template =",
"datetime from dateutil.parser import * def homePage(request): template = loader.get_template('base_intro.html') context = {",
"= loader.get_template('base_view_profile.html') context = { \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount } #print(context) return HttpResponse(template.render(context, request))",
"for question in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context",
"response @login_required def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", # \"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\")",
"#Use the dataset as input to generate the pdf, recieve a buffer as",
"as input to generate the pdf, recieve a buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData) #",
"import HttpResponse from django.template import loader from .models import * from django.conf import",
"\"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData) template = loader.get_template('base_view_profile.html') context = { \"systemforms\":userForms, \"userData\":userData,",
"if user is not None: login(request, user) return redirect('systemForms') else: return redirect('%s?next=%s' %",
"} #print(context) return HttpResponse(template.render(context, request)) @login_required def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return",
"pdf, recieve a buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" +",
"filename, } pdfData.addMetadata(metaData) #Set the httpresponse to download a pdf response = HttpResponse(content_type='application/pdf')",
"def loginForm(request): context = { 'errors': \"\", } template = loader.get_template('registration/login.html') return HttpResponse(template.render(context,",
"str(timestamp) +\".pdf\" metaData = { '/Title': filename, } pdfData.addMetadata(metaData) #Set the httpresponse to",
"context = { 'systemforms':pdfforms , } template = loader.get_template('formsList.html') return HttpResponse(template.render(context, request)) @login_required",
"fieldData=[] if(fieldIDs is not None): fieldIDList=fieldIDs.split(\",\") for fieldID in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID]",
"loginUser(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) #print(user)",
"return HttpResponse(template.render(context, request)) @login_required def addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject,",
"\"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\", named=True ) #get all fields Related to User",
"= { 'errors': \"\", } template = loader.get_template('registration/login.html') return HttpResponse(template.render(context, request)) def loginUser(request):",
"{ 'errors': \"\", } template = loader.get_template('registration/login.html') return HttpResponse(template.render(context, request)) def loginUser(request): username",
"\"formcount\":formsCount } #print(context) return HttpResponse(template.render(context, request)) @login_required def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0):",
"username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) #print(user) if",
"#print(dataSet) #Use the dataset as input to generate the pdf, recieve a buffer",
"import pandas as pd from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import",
"addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all fields in PDF related to PDFID",
"is not None): fieldIDList=fieldIDs.split(\",\") for fieldID in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData)",
"found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF) context = { \"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid",
"not None): fieldIDList=fieldIDs.split(\",\") for fieldID in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData,",
"HttpResponse(template.render(context, request)) def loginUser(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request,",
"password=password) #print(user) if user is not None: login(request, user) return redirect('systemForms') else: return",
"userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove rows with",
"def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs is not None): fieldIDList=fieldIDs.split(\",\") for fieldID",
"download a pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename= \"%s\"' % filename",
"from django.template import loader from .models import * from django.conf import settings from",
"in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context = {",
"in PDF related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\", named=True )",
"fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request) return",
"#print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request) return redirect('login') @login_required def fillForm(request,",
"from .models import * from django.conf import settings from django.shortcuts import redirect from",
"named=True ) #print(userFields) #print(fieldsinPDF) #Set the column as index on which the join",
"pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF) context = {",
"django.shortcuts import redirect from utils import dataLayerPDF from utils import dprint from utils",
"PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove rows with NA",
"'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context) template = loader.get_template('process_form.html') return HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"]) def",
"list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for",
"import * def homePage(request): template = loader.get_template('base_intro.html') context = { } return HttpResponse(template.render(context,",
"isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all fields in PDF",
"UserProfile and that match the fields in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\",",
"context = { \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount } #print(context) return HttpResponse(template.render(context, request)) @login_required def",
"userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\", named=True ) #print(userFields) #print(fieldsinPDF) #Set the column as index",
"import login_required from django.views.decorators.http import require_http_methods from django.utils.dateparse import parse_date import datetime from",
"'errors': \"\", } template = loader.get_template('registration/login.html') return HttpResponse(template.render(context, request)) def loginUser(request): username =",
"loader.get_template('editPDF.html') return HttpResponse(template.render(context, request)) @login_required def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser if(not superUser): return HttpResponse(status=404)",
"request)) @login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs is not None):",
"'systemforms':pdfforms , } template = loader.get_template('formsList.html') return HttpResponse(template.render(context, request)) @login_required def addFormToProfile(request,form_id): #return",
"username=username, password=password) #print(user) if user is not None: login(request, user) return redirect('systemForms') else:",
"User in UserProfile and that match the fields in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\",",
"to generate the pdf, recieve a buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\")",
"authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.utils.dateparse",
"happen when the number of rows in the above datasets differ in count.",
"pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use the dataset as input to generate the",
"from utils import dataLayerPDF from utils import dprint from utils import modelUtils import",
"superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset, 'formID':pdfid } #print(context) template = loader.get_template('rearrangeformquestions.html') return",
"from django.views.decorators.http import require_http_methods from django.utils.dateparse import parse_date import datetime from dateutil.parser import",
"+\".pdf\" metaData = { '/Title': filename, } pdfData.addMetadata(metaData) #Set the httpresponse to download",
"fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet) #Use the dataset as input to generate",
"dataset as input to generate the pdf, recieve a buffer as reponse pdfData=dataLayerPDF.addText(dataSet,formData)",
"pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all fields in PDF related",
"profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", # \"pdf__image\", # ) userForms=GeneratedPDF.objects.filter(user=request.user).prefetch_related(\"pdf\") #print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\",",
"rows with NA Values. Will happen when the number of rows in the",
"it to a list of dictionaries #dataSet=combinedDF.sort_values(by=['field_page_number']).to_dict('records') #dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples())",
"'/Title': filename, } pdfData.addMetadata(metaData) #Set the httpresponse to download a pdf response =",
"} template = loader.get_template('formsList.html') return HttpResponse(template.render(context, request)) @login_required def addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False",
"#print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context = { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions, 'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context)",
"} #print(formData) template = loader.get_template('editPDF.html') return HttpResponse(template.render(context, request)) @login_required def arrangeFormQuestions(request, pdfid): superUser=request.user.is_superuser",
"response['Content-Disposition'] = 'inline; filename= \"%s\"' % filename #response.write(PDFBytes) #write the pdfdata to the",
"@login_required def addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject,",
"def editPDFLive(request, pdfid): userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid, False)",
"from utils import dprint from utils import modelUtils import pandas as pd from",
"for fieldID in fieldIDList: fieldDict={} fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid))",
"to the responseobject pdfData.write(response) #response.write(pdfData) #return the response return response @login_required def profile(request):",
"import datetime from dateutil.parser import * def homePage(request): template = loader.get_template('base_intro.html') context =",
"HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject)",
"userFormsCount=GeneratedPDF.objects.filter(user=request.user, pdf=pdfid).count() if(userFormsCount==0): return HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF) context =",
"pdfData.write(response) #response.write(pdfData) #return the response return response @login_required def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", #",
"PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\", named=True ) #get all fields Related",
"{ \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount } #print(context) return HttpResponse(template.render(context, request)) @login_required def editPDFLive(request, pdfid):",
"pdfData.addMetadata(metaData) #Set the httpresponse to download a pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] =",
"redirect('systemForms') else: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) @login_required def viewSystemForms(request): pdfforms=PDFForm.objects.all() context =",
"as index on which the join is to be made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field')",
"False) #dprint.dprint(fieldsinPDF) context = { \"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid } #print(formData) template =",
"\"formData\": formData, 'formID':pdfid } #print(formData) template = loader.get_template('editPDF.html') return HttpResponse(template.render(context, request)) @login_required def",
"\"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid } #print(formData) template = loader.get_template('editPDF.html') return HttpResponse(template.render(context, request)) @login_required",
"context = { 'errors': \"\", } template = loader.get_template('registration/login.html') return HttpResponse(template.render(context, request)) def",
"context = { \"userFormDataSet\":dataSet, \"formData\": formData, 'formID':pdfid } #print(formData) template = loader.get_template('editPDF.html') return",
"all fields in PDF related to PDFID fieldsinPDF=PDFFormField.objects.filter(pdf=form_id).values_list( \"field\", \"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\",",
"#return the response return response @login_required def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\", #",
"is not None: login(request, user) return redirect('systemForms') else: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))",
"which the join is to be made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF)",
"from dateutil.parser import * def homePage(request): template = loader.get_template('base_intro.html') context = { }",
"UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0): addform=GeneratedPDF(user=UserObject, pdf=PDFormObject) addform.save() modelUtils.addFieldsToProfile(UserObject, PDFormObject) #get all fields",
"'form_id':form_id, 'fieldIDS':fieldIDStr } #dprint.dprint(missingQuestionsList) #print(context) template = loader.get_template('process_form.html') return HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"])",
"* from django.conf import settings from django.shortcuts import redirect from utils import dataLayerPDF",
"missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for question in missingQuestionTuples: fieldIDStr=fieldIDStr+\" \" +str(question.field)",
"viewSystemForms(request): pdfforms=PDFForm.objects.all() context = { 'systemforms':pdfforms , } template = loader.get_template('formsList.html') return HttpResponse(template.render(context,",
"\" +str(question.field) fieldIDStr=fieldIDStr.strip().replace(\" \", \",\") #print(fieldIDStr) numberOfMissingQuestions=len(missingQuestionTuples) context = { 'formObject':PDFormObject, \"missingQuestions\":missingQuestionTuples, 'questionCount':numberOfMissingQuestions,",
"loginForm(request): context = { 'errors': \"\", } template = loader.get_template('registration/login.html') return HttpResponse(template.render(context, request))",
"} return HttpResponse(template.render(context, request)) def loginForm(request): context = { 'errors': \"\", } template",
"#dprint.dprint(userFieldDF) #dprint.dprint(PDFFieldsDF) #Make the Join combinedDF=PDFFieldsDF.join(userFieldDF, on='field',lsuffix='_left', rsuffix='_right') #remove rows with NA Values.",
"fieldDict[\"ID\"]=fieldID fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request) return redirect('login')",
"dprint from utils import modelUtils import pandas as pd from django.contrib.auth import authenticate,",
"#print(userData) template = loader.get_template('base_view_profile.html') context = { \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount } #print(context) return",
"import require_http_methods from django.utils.dateparse import parse_date import datetime from dateutil.parser import * def",
"\"field__field_description\") formsCount=userForms.count() #print(userData) template = loader.get_template('base_view_profile.html') context = { \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount }",
"\"\", } template = loader.get_template('registration/login.html') return HttpResponse(template.render(context, request)) def loginUser(request): username = request.POST['username']",
"request)) @login_required def addFormToProfile(request,form_id): #return HttpResponse(str(form_id)) errorCondition=False loggedUserID=request.user.id UserObject=request.user PDFormObject=PDFForm.objects.get(id=form_id) isFormPresent=GeneratedPDF.objects.filter(user=UserObject, pdf=PDFormObject).count() if(isFormPresent==0):",
"#dprint.dprint(combinedDF) missingQuestionsList=combinedDF[combinedDF[\"field__field_state\"]=='DYNAMIC'] missingQuestionsList.fillna(value='',inplace=True) missingQuestionsList.reset_index(inplace=True) #missingQuestionsList['field_str']=missingQuestionsList['field'].astype(str) missingQuestionTuples=list(missingQuestionsList.itertuples()) #print(type(missingQuestionTuples)) fieldIDStr=\"\" for question in missingQuestionTuples: fieldIDStr=fieldIDStr+\"",
"\"field__field_display\", \"field__field_question\", \"field__field_state\", \"field__field_description\", named=True ) #get all fields Related to User in",
"= request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) #print(user) if user",
"#response.write(PDFBytes) #write the pdfdata to the responseobject pdfData.write(response) #response.write(pdfData) #return the response return",
"import dprint from utils import modelUtils import pandas as pd from django.contrib.auth import",
"import modelUtils import pandas as pd from django.contrib.auth import authenticate, login, logout from",
"def logoutUser(request): logout(request) return redirect('login') @login_required def fillForm(request, pdfid): dataSet, formData=modelUtils.getUserFormData(request, pdfid) #print(dataSet)",
"pdfid): superUser=request.user.is_superuser if(not superUser): return HttpResponse(status=404) FormFieldQueryset=PDFFormField.objects.filter(pdf=pdfid).prefetch_related('field') context={ \"formFields\":FormFieldQueryset, 'formID':pdfid } #print(context) template",
"dataLayerPDF from utils import dprint from utils import modelUtils import pandas as pd",
"\"%s\"' % filename #response.write(PDFBytes) #write the pdfdata to the responseobject pdfData.write(response) #response.write(pdfData) #return",
"utils import dataLayerPDF from utils import dprint from utils import modelUtils import pandas",
"modelUtils import pandas as pd from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators",
"that match the fields in the PDFForm userFields=UserProfile.objects.filter(user=loggedUserID).values_list( \"field\", \"field_text\", \"data_index\", named=True )",
"#response.write(pdfData) #return the response return response @login_required def profile(request): # userForms=GeneratedPDF.objects.filter(user=request.user).values(\"pdf__pdf_name\", # \"pdf__pdf_description\",",
"if(userFormsCount==0): return HttpResponse(\"Not found\"); dataSet, formData=modelUtils.getUserFormData(request, pdfid, False) #dprint.dprint(fieldsinPDF) context = { \"userFormDataSet\":dataSet,",
"#dprint.dprint(missingQuestionsList) #print(context) template = loader.get_template('process_form.html') return HttpResponse(template.render(context, request)) @login_required @require_http_methods([\"POST\"]) def saveDynamicFieldData(request,pdfid): recievedDateFormat=\"\"",
"request)) def loginUser(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username,",
"} pdfData.addMetadata(metaData) #Set the httpresponse to download a pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition']",
"template = loader.get_template('base_view_profile.html') context = { \"systemforms\":userForms, \"userData\":userData, \"formcount\":formsCount } #print(context) return HttpResponse(template.render(context,",
"recievedDateFormat=\"\" fieldIDs=request.POST[\"fieldIDs\"] fieldIDList=[] fieldData=[] if(fieldIDs is not None): fieldIDList=fieldIDs.split(\",\") for fieldID in fieldIDList:",
"on which the join is to be made in pandas userFieldDF=pd.DataFrame(list(userFields)).set_index('field') PDFFieldsDF=pd.DataFrame(list(fieldsinPDF)).set_index('field') #dprint.dprint(userFieldDF)",
"#print(userForms) userData=UserProfile.objects.filter(user=request.user).prefetch_related(\"field\").order_by( \"field__category\", \"field__category_order\", \"field__field_description\") formsCount=userForms.count() #print(userData) template = loader.get_template('base_view_profile.html') context = {",
"as reponse pdfData=dataLayerPDF.addText(dataSet,formData) # #output=dataLayerPDF.mergePDFs() timestamp=datetime.datetime.now().strftime(\"%d-%m-%Y-%I-%M-%S\") filename=formData.pdf_name +\"-\"+request.user.first_name+\"-\" + str(timestamp) +\".pdf\" metaData =",
"fieldDict[\"userValue\"]=request.POST[fieldID] fieldData.append(fieldDict) #print(fieldData) modelUtils.saveUserProfileFields(fieldData, request.user) return redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request) return redirect('login') @login_required",
"request.user) return redirect('/editPDF/'+str(pdfid)) def logoutUser(request): logout(request) return redirect('login') @login_required def fillForm(request, pdfid): dataSet,"
] |
[
"'Zoo', 'Credit'], key=str.lower, reverse=True) print(s) L = [('Bob', 75), ('Adam', 92), ('Bart', 66),",
"return t[0].lower() def by_score(t): return t[1] if __name__ == '__main__': print(sorted([36, 5, -12,",
"L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] s2 = sorted(L,",
"92), ('Bart', 66), ('Lisa', 88)] s2 = sorted(L, key = by_name) print(s2) s3",
"'Credit'], key=str.lower, reverse=True) print(s) L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa',",
"sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) print(s) L = [('Bob', 75), ('Adam', 92),",
"5, -12, 9, -21])) s = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) print(s)",
"('Adam', 92), ('Bart', 66), ('Lisa', 88)] s2 = sorted(L, key = by_name) print(s2)",
"('Bart', 66), ('Lisa', 88)] s2 = sorted(L, key = by_name) print(s2) s3 =",
"= [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] s2 = sorted(L, key",
"# _*_ coding: utf-8 _*_ def by_name(t): return t[0].lower() def by_score(t): return t[1]",
"_*_ def by_name(t): return t[0].lower() def by_score(t): return t[1] if __name__ == '__main__':",
"def by_score(t): return t[1] if __name__ == '__main__': print(sorted([36, 5, -12, 9, -21]))",
"9, -21])) s = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) print(s) L =",
"key=str.lower, reverse=True) print(s) L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]",
"_*_ coding: utf-8 _*_ def by_name(t): return t[0].lower() def by_score(t): return t[1] if",
"print(sorted([36, 5, -12, 9, -21])) s = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)",
"('Lisa', 88)] s2 = sorted(L, key = by_name) print(s2) s3 = sorted(L, key",
"print(s) L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] s2 =",
"== '__main__': print(sorted([36, 5, -12, 9, -21])) s = sorted(['bob', 'about', 'Zoo', 'Credit'],",
"s2 = sorted(L, key = by_name) print(s2) s3 = sorted(L, key = by_score)",
"reverse=True) print(s) L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] s2",
"def by_name(t): return t[0].lower() def by_score(t): return t[1] if __name__ == '__main__': print(sorted([36,",
"-12, 9, -21])) s = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) print(s) L",
"-21])) s = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) print(s) L = [('Bob',",
"t[1] if __name__ == '__main__': print(sorted([36, 5, -12, 9, -21])) s = sorted(['bob',",
"utf-8 _*_ def by_name(t): return t[0].lower() def by_score(t): return t[1] if __name__ ==",
"88)] s2 = sorted(L, key = by_name) print(s2) s3 = sorted(L, key =",
"coding: utf-8 _*_ def by_name(t): return t[0].lower() def by_score(t): return t[1] if __name__",
"= sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) print(s) L = [('Bob', 75), ('Adam',",
"= sorted(L, key = by_name) print(s2) s3 = sorted(L, key = by_score) print(s3)",
"75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] s2 = sorted(L, key = by_name)",
"'__main__': print(sorted([36, 5, -12, 9, -21])) s = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower,",
"[('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] s2 = sorted(L, key =",
"by_name(t): return t[0].lower() def by_score(t): return t[1] if __name__ == '__main__': print(sorted([36, 5,",
"t[0].lower() def by_score(t): return t[1] if __name__ == '__main__': print(sorted([36, 5, -12, 9,",
"'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) print(s) L = [('Bob', 75), ('Adam', 92), ('Bart',",
"if __name__ == '__main__': print(sorted([36, 5, -12, 9, -21])) s = sorted(['bob', 'about',",
"__name__ == '__main__': print(sorted([36, 5, -12, 9, -21])) s = sorted(['bob', 'about', 'Zoo',",
"66), ('Lisa', 88)] s2 = sorted(L, key = by_name) print(s2) s3 = sorted(L,",
"return t[1] if __name__ == '__main__': print(sorted([36, 5, -12, 9, -21])) s =",
"by_score(t): return t[1] if __name__ == '__main__': print(sorted([36, 5, -12, 9, -21])) s",
"s = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) print(s) L = [('Bob', 75),"
] |
[
"distributed in the hope that it will be useful, # but WITHOUT ANY",
"not, see <http://www.gnu.org/licenses/>. import sys import fontforge if __name__ == \"__main__\": font =",
"either version 3 of the License, or # (at your option) any later",
"#!/usr/bin/python # Copyright (C) 2012, <NAME> <<EMAIL>> # http://aravindavk.in # This program is",
"by # the Free Software Foundation, either version 3 of the License, or",
"import sys import fontforge if __name__ == \"__main__\": font = fontforge.open(\"../Gubbi.sfd\") # Remove",
"version 3 of the License, or # (at your option) any later version.",
"GSUB lookups for lookup in font.gsub_lookups: font.removeLookup(lookup) # Merge the new featurefile font.mergeFeature(\"gsub.fea\")",
"published by # the Free Software Foundation, either version 3 of the License,",
"or # (at your option) any later version. # This program is distributed",
"it and/or modify # it under the terms of the GNU General Public",
"lookups for lookup in font.gsub_lookups: font.removeLookup(lookup) # Merge the new featurefile font.mergeFeature(\"gsub.fea\") font.save()",
"fontforge if __name__ == \"__main__\": font = fontforge.open(\"../Gubbi.sfd\") # Remove all GSUB lookups",
"General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import",
"# it under the terms of the GNU General Public License as published",
"terms of the GNU General Public License as published by # the Free",
"<<EMAIL>> # http://aravindavk.in # This program is free software: you can redistribute it",
"GNU General Public License as published by # the Free Software Foundation, either",
"# (at your option) any later version. # This program is distributed in",
"it under the terms of the GNU General Public License as published by",
"of the GNU General Public License # along with this program. If not,",
"free software: you can redistribute it and/or modify # it under the terms",
"# GNU General Public License for more details. # You should have received",
"http://aravindavk.in # This program is free software: you can redistribute it and/or modify",
"you can redistribute it and/or modify # it under the terms of the",
"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General",
"__name__ == \"__main__\": font = fontforge.open(\"../Gubbi.sfd\") # Remove all GSUB lookups for lookup",
"of the GNU General Public License as published by # the Free Software",
"License for more details. # You should have received a copy of the",
"redistribute it and/or modify # it under the terms of the GNU General",
"Public License as published by # the Free Software Foundation, either version 3",
"modify # it under the terms of the GNU General Public License as",
"details. # You should have received a copy of the GNU General Public",
"the Free Software Foundation, either version 3 of the License, or # (at",
"should have received a copy of the GNU General Public License # along",
"2012, <NAME> <<EMAIL>> # http://aravindavk.in # This program is free software: you can",
"PARTICULAR PURPOSE. See the # GNU General Public License for more details. #",
"See the # GNU General Public License for more details. # You should",
"the GNU General Public License # along with this program. If not, see",
"is free software: you can redistribute it and/or modify # it under the",
"without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"= fontforge.open(\"../Gubbi.sfd\") # Remove all GSUB lookups for lookup in font.gsub_lookups: font.removeLookup(lookup) #",
"if __name__ == \"__main__\": font = fontforge.open(\"../Gubbi.sfd\") # Remove all GSUB lookups for",
"hope that it will be useful, # but WITHOUT ANY WARRANTY; without even",
"(at your option) any later version. # This program is distributed in the",
"# http://aravindavk.in # This program is free software: you can redistribute it and/or",
"License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sys import",
"version. # This program is distributed in the hope that it will be",
"the GNU General Public License as published by # the Free Software Foundation,",
"of the License, or # (at your option) any later version. # This",
"all GSUB lookups for lookup in font.gsub_lookups: font.removeLookup(lookup) # Merge the new featurefile",
"warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #",
"You should have received a copy of the GNU General Public License #",
"with this program. If not, see <http://www.gnu.org/licenses/>. import sys import fontforge if __name__",
"# the Free Software Foundation, either version 3 of the License, or #",
"see <http://www.gnu.org/licenses/>. import sys import fontforge if __name__ == \"__main__\": font = fontforge.open(\"../Gubbi.sfd\")",
"Foundation, either version 3 of the License, or # (at your option) any",
"<NAME> <<EMAIL>> # http://aravindavk.in # This program is free software: you can redistribute",
"This program is distributed in the hope that it will be useful, #",
"program is free software: you can redistribute it and/or modify # it under",
"WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A",
"useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #",
"that it will be useful, # but WITHOUT ANY WARRANTY; without even the",
"PURPOSE. See the # GNU General Public License for more details. # You",
"the # GNU General Public License for more details. # You should have",
"# This program is free software: you can redistribute it and/or modify #",
"received a copy of the GNU General Public License # along with this",
"License as published by # the Free Software Foundation, either version 3 of",
"along with this program. If not, see <http://www.gnu.org/licenses/>. import sys import fontforge if",
"later version. # This program is distributed in the hope that it will",
"the terms of the GNU General Public License as published by # the",
"License, or # (at your option) any later version. # This program is",
"as published by # the Free Software Foundation, either version 3 of the",
"more details. # You should have received a copy of the GNU General",
"even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"your option) any later version. # This program is distributed in the hope",
"implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR",
"copy of the GNU General Public License # along with this program. If",
"Public License for more details. # You should have received a copy of",
"this program. If not, see <http://www.gnu.org/licenses/>. import sys import fontforge if __name__ ==",
"it will be useful, # but WITHOUT ANY WARRANTY; without even the implied",
"WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS",
"== \"__main__\": font = fontforge.open(\"../Gubbi.sfd\") # Remove all GSUB lookups for lookup in",
"the hope that it will be useful, # but WITHOUT ANY WARRANTY; without",
"<http://www.gnu.org/licenses/>. import sys import fontforge if __name__ == \"__main__\": font = fontforge.open(\"../Gubbi.sfd\") #",
"program. If not, see <http://www.gnu.org/licenses/>. import sys import fontforge if __name__ == \"__main__\":",
"fontforge.open(\"../Gubbi.sfd\") # Remove all GSUB lookups for lookup in font.gsub_lookups: font.removeLookup(lookup) # Merge",
"# Copyright (C) 2012, <NAME> <<EMAIL>> # http://aravindavk.in # This program is free",
"FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more",
"any later version. # This program is distributed in the hope that it",
"for more details. # You should have received a copy of the GNU",
"be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of",
"have received a copy of the GNU General Public License # along with",
"GNU General Public License for more details. # You should have received a",
"the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"Copyright (C) 2012, <NAME> <<EMAIL>> # http://aravindavk.in # This program is free software:",
"# along with this program. If not, see <http://www.gnu.org/licenses/>. import sys import fontforge",
"the License, or # (at your option) any later version. # This program",
"# You should have received a copy of the GNU General Public License",
"(C) 2012, <NAME> <<EMAIL>> # http://aravindavk.in # This program is free software: you",
"is distributed in the hope that it will be useful, # but WITHOUT",
"\"__main__\": font = fontforge.open(\"../Gubbi.sfd\") # Remove all GSUB lookups for lookup in font.gsub_lookups:",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public",
"in the hope that it will be useful, # but WITHOUT ANY WARRANTY;",
"font = fontforge.open(\"../Gubbi.sfd\") # Remove all GSUB lookups for lookup in font.gsub_lookups: font.removeLookup(lookup)",
"General Public License for more details. # You should have received a copy",
"# Remove all GSUB lookups for lookup in font.gsub_lookups: font.removeLookup(lookup) # Merge the",
"FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for",
"This program is free software: you can redistribute it and/or modify # it",
"and/or modify # it under the terms of the GNU General Public License",
"GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.",
"a copy of the GNU General Public License # along with this program.",
"If not, see <http://www.gnu.org/licenses/>. import sys import fontforge if __name__ == \"__main__\": font",
"3 of the License, or # (at your option) any later version. #",
"A PARTICULAR PURPOSE. See the # GNU General Public License for more details.",
"or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License",
"option) any later version. # This program is distributed in the hope that",
"will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty",
"General Public License as published by # the Free Software Foundation, either version",
"software: you can redistribute it and/or modify # it under the terms of",
"import fontforge if __name__ == \"__main__\": font = fontforge.open(\"../Gubbi.sfd\") # Remove all GSUB",
"of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU",
"Remove all GSUB lookups for lookup in font.gsub_lookups: font.removeLookup(lookup) # Merge the new",
"under the terms of the GNU General Public License as published by #",
"# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY",
"for lookup in font.gsub_lookups: font.removeLookup(lookup) # Merge the new featurefile font.mergeFeature(\"gsub.fea\") font.save() font.close()",
"can redistribute it and/or modify # it under the terms of the GNU",
"Free Software Foundation, either version 3 of the License, or # (at your",
"Software Foundation, either version 3 of the License, or # (at your option)",
"program is distributed in the hope that it will be useful, # but",
"# This program is distributed in the hope that it will be useful,",
"Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sys",
"but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or",
"sys import fontforge if __name__ == \"__main__\": font = fontforge.open(\"../Gubbi.sfd\") # Remove all"
] |
[
"* 1 if x is not None else None, alpha=alpha if alpha is",
"not None else None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args): return np.prod(args,",
"<reponame>i1bgv/abtools # -*- coding: utf-8 -*- import numpy as np from .base import",
"k_b=None, k_l=None): self.bernoulli = Bernoulli( x=(x > 0) * 1 if x is",
"None, beta=n - alpha if n is not None and alpha is not",
"None ) self.lognormal = Lognormal( x=x[x > 0] if x is not None",
".base import Distribution from .distributions import Bernoulli, Lognormal class BLModel(Distribution): def __init__(self, x=None,",
"def __mul__(self, k): if not isinstance(k, list): raise TypeError self.bernoulli.k = self._set_k(k[0]) self.lognormal.k",
"self.bernoulli >> dist.bernoulli new_l_model = self.lognormal >> dist.lognormal new_bl = BLModel( mu=new_l_model.mu, std=new_l_model.std,",
"if alpha is not None else None, beta=n - alpha if n is",
"self.lognormal) def prod(args): return np.prod(args, axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k = self._set_k(k_b) self.lognormal.k =",
"None, n=alpha if alpha is not None else None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli,",
"class BLModel(Distribution): def __init__(self, x=None, mu=None, std=None, alpha=None, n=None, k_b=None, k_l=None): self.bernoulli =",
"__init__(self, x=None, mu=None, std=None, alpha=None, n=None, k_b=None, k_l=None): self.bernoulli = Bernoulli( x=(x >",
"new_b_model = self.bernoulli >> dist.bernoulli new_l_model = self.lognormal >> dist.lognormal new_bl = BLModel(",
") super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args): return np.prod(args, axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k",
"mu=mu if mu is not None else None, std=std if std is not",
"is not None else None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args): return",
"def __rshift__(self, dist): if not isinstance(dist, BLModel): raise TypeError new_b_model = self.bernoulli >>",
"std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n ) return new_bl def __mul__(self, k): if not isinstance(k, list):",
"None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args): return np.prod(args, axis=0) self._set_parent_operation(prod, 'Product')",
"self._set_k(k_l) def __rshift__(self, dist): if not isinstance(dist, BLModel): raise TypeError new_b_model = self.bernoulli",
"alpha=None, n=None, k_b=None, k_l=None): self.bernoulli = Bernoulli( x=(x > 0) * 1 if",
"None else None, mu=mu if mu is not None else None, std=std if",
"TypeError new_b_model = self.bernoulli >> dist.bernoulli new_l_model = self.lognormal >> dist.lognormal new_bl =",
"new_l_model = self.lognormal >> dist.lognormal new_bl = BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n )",
"if not isinstance(k, list): raise TypeError self.bernoulli.k = self._set_k(k[0]) self.lognormal.k = self._set_k(k[1]) return",
"0) * 1 if x is not None else None, alpha=alpha if alpha",
"std=std if std is not None else None, n=alpha if alpha is not",
"# -*- coding: utf-8 -*- import numpy as np from .base import Distribution",
"not isinstance(k, list): raise TypeError self.bernoulli.k = self._set_k(k[0]) self.lognormal.k = self._set_k(k[1]) return self",
"is not None and alpha is not None else None ) self.lognormal =",
"else None, n=alpha if alpha is not None else None ) super(BLModel, self).__init__()",
"if not isinstance(dist, BLModel): raise TypeError new_b_model = self.bernoulli >> dist.bernoulli new_l_model =",
"None else None ) self.lognormal = Lognormal( x=x[x > 0] if x is",
"if x is not None else None, mu=mu if mu is not None",
"x is not None else None, alpha=alpha if alpha is not None else",
") return new_bl def __mul__(self, k): if not isinstance(k, list): raise TypeError self.bernoulli.k",
"import Distribution from .distributions import Bernoulli, Lognormal class BLModel(Distribution): def __init__(self, x=None, mu=None,",
"BLModel(Distribution): def __init__(self, x=None, mu=None, std=None, alpha=None, n=None, k_b=None, k_l=None): self.bernoulli = Bernoulli(",
"Distribution from .distributions import Bernoulli, Lognormal class BLModel(Distribution): def __init__(self, x=None, mu=None, std=None,",
"self.bernoulli = Bernoulli( x=(x > 0) * 1 if x is not None",
"not None else None, std=std if std is not None else None, n=alpha",
"else None, mu=mu if mu is not None else None, std=std if std",
"= Lognormal( x=x[x > 0] if x is not None else None, mu=mu",
"def prod(args): return np.prod(args, axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k = self._set_k(k_b) self.lognormal.k = self._set_k(k_l)",
">> dist.lognormal new_bl = BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n ) return new_bl def",
"raise TypeError new_b_model = self.bernoulli >> dist.bernoulli new_l_model = self.lognormal >> dist.lognormal new_bl",
"None else None, std=std if std is not None else None, n=alpha if",
"= self.lognormal >> dist.lognormal new_bl = BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n ) return",
"1 if x is not None else None, alpha=alpha if alpha is not",
"axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k = self._set_k(k_b) self.lognormal.k = self._set_k(k_l) def __rshift__(self, dist): if",
"np.prod(args, axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k = self._set_k(k_b) self.lognormal.k = self._set_k(k_l) def __rshift__(self, dist):",
"'Product') self.bernoulli.k = self._set_k(k_b) self.lognormal.k = self._set_k(k_l) def __rshift__(self, dist): if not isinstance(dist,",
"dist.lognormal new_bl = BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n ) return new_bl def __mul__(self,",
"utf-8 -*- import numpy as np from .base import Distribution from .distributions import",
".distributions import Bernoulli, Lognormal class BLModel(Distribution): def __init__(self, x=None, mu=None, std=None, alpha=None, n=None,",
"else None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args): return np.prod(args, axis=0) self._set_parent_operation(prod,",
"else None, std=std if std is not None else None, n=alpha if alpha",
"__rshift__(self, dist): if not isinstance(dist, BLModel): raise TypeError new_b_model = self.bernoulli >> dist.bernoulli",
"alpha=alpha if alpha is not None else None, beta=n - alpha if n",
"None else None, beta=n - alpha if n is not None and alpha",
"else None, alpha=alpha if alpha is not None else None, beta=n - alpha",
"else None, beta=n - alpha if n is not None and alpha is",
">> dist.bernoulli new_l_model = self.lognormal >> dist.lognormal new_bl = BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha,",
"not None else None, mu=mu if mu is not None else None, std=std",
"dist.bernoulli new_l_model = self.lognormal >> dist.lognormal new_bl = BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n",
"is not None else None, n=alpha if alpha is not None else None",
"k_l=None): self.bernoulli = Bernoulli( x=(x > 0) * 1 if x is not",
"not None else None, alpha=alpha if alpha is not None else None, beta=n",
"None, mu=mu if mu is not None else None, std=std if std is",
"None, alpha=alpha if alpha is not None else None, beta=n - alpha if",
"> 0) * 1 if x is not None else None, alpha=alpha if",
"if alpha is not None else None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def",
"n=alpha if alpha is not None else None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal)",
"alpha if n is not None and alpha is not None else None",
"not None else None ) self.lognormal = Lognormal( x=x[x > 0] if x",
"x=None, mu=None, std=None, alpha=None, n=None, k_b=None, k_l=None): self.bernoulli = Bernoulli( x=(x > 0)",
"is not None else None ) self.lognormal = Lognormal( x=x[x > 0] if",
"n=None, k_b=None, k_l=None): self.bernoulli = Bernoulli( x=(x > 0) * 1 if x",
"is not None else None, std=std if std is not None else None,",
"-*- import numpy as np from .base import Distribution from .distributions import Bernoulli,",
"= BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n ) return new_bl def __mul__(self, k): if",
") self.lognormal = Lognormal( x=x[x > 0] if x is not None else",
"None, std=std if std is not None else None, n=alpha if alpha is",
"self._set_parents(self.bernoulli, self.lognormal) def prod(args): return np.prod(args, axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k = self._set_k(k_b) self.lognormal.k",
"self._set_k(k_b) self.lognormal.k = self._set_k(k_l) def __rshift__(self, dist): if not isinstance(dist, BLModel): raise TypeError",
"import Bernoulli, Lognormal class BLModel(Distribution): def __init__(self, x=None, mu=None, std=None, alpha=None, n=None, k_b=None,",
"alpha is not None else None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args):",
"new_bl = BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n ) return new_bl def __mul__(self, k):",
"None else None, alpha=alpha if alpha is not None else None, beta=n -",
"beta=n - alpha if n is not None and alpha is not None",
"prod(args): return np.prod(args, axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k = self._set_k(k_b) self.lognormal.k = self._set_k(k_l) def",
"is not None else None, beta=n - alpha if n is not None",
"as np from .base import Distribution from .distributions import Bernoulli, Lognormal class BLModel(Distribution):",
"mu=None, std=None, alpha=None, n=None, k_b=None, k_l=None): self.bernoulli = Bernoulli( x=(x > 0) *",
"if std is not None else None, n=alpha if alpha is not None",
"self.lognormal.k = self._set_k(k_l) def __rshift__(self, dist): if not isinstance(dist, BLModel): raise TypeError new_b_model",
"alpha=new_b_model.alpha, n=new_b_model.n ) return new_bl def __mul__(self, k): if not isinstance(k, list): raise",
"dist): if not isinstance(dist, BLModel): raise TypeError new_b_model = self.bernoulli >> dist.bernoulli new_l_model",
"BLModel): raise TypeError new_b_model = self.bernoulli >> dist.bernoulli new_l_model = self.lognormal >> dist.lognormal",
"std=None, alpha=None, n=None, k_b=None, k_l=None): self.bernoulli = Bernoulli( x=(x > 0) * 1",
"= self.bernoulli >> dist.bernoulli new_l_model = self.lognormal >> dist.lognormal new_bl = BLModel( mu=new_l_model.mu,",
"= Bernoulli( x=(x > 0) * 1 if x is not None else",
"Bernoulli( x=(x > 0) * 1 if x is not None else None,",
"alpha is not None else None, beta=n - alpha if n is not",
"def __init__(self, x=None, mu=None, std=None, alpha=None, n=None, k_b=None, k_l=None): self.bernoulli = Bernoulli( x=(x",
"None and alpha is not None else None ) self.lognormal = Lognormal( x=x[x",
"self.lognormal >> dist.lognormal new_bl = BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n ) return new_bl",
"return new_bl def __mul__(self, k): if not isinstance(k, list): raise TypeError self.bernoulli.k =",
"if n is not None and alpha is not None else None )",
"is not None else None, mu=mu if mu is not None else None,",
"isinstance(dist, BLModel): raise TypeError new_b_model = self.bernoulli >> dist.bernoulli new_l_model = self.lognormal >>",
"from .base import Distribution from .distributions import Bernoulli, Lognormal class BLModel(Distribution): def __init__(self,",
"import numpy as np from .base import Distribution from .distributions import Bernoulli, Lognormal",
"alpha is not None else None ) self.lognormal = Lognormal( x=x[x > 0]",
"not None else None, beta=n - alpha if n is not None and",
"else None ) self.lognormal = Lognormal( x=x[x > 0] if x is not",
"not None else None, n=alpha if alpha is not None else None )",
"not isinstance(dist, BLModel): raise TypeError new_b_model = self.bernoulli >> dist.bernoulli new_l_model = self.lognormal",
"coding: utf-8 -*- import numpy as np from .base import Distribution from .distributions",
"numpy as np from .base import Distribution from .distributions import Bernoulli, Lognormal class",
"x=x[x > 0] if x is not None else None, mu=mu if mu",
"mu is not None else None, std=std if std is not None else",
"return np.prod(args, axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k = self._set_k(k_b) self.lognormal.k = self._set_k(k_l) def __rshift__(self,",
"None else None ) super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args): return np.prod(args, axis=0)",
"and alpha is not None else None ) self.lognormal = Lognormal( x=x[x >",
"is not None else None, alpha=alpha if alpha is not None else None,",
"new_bl def __mul__(self, k): if not isinstance(k, list): raise TypeError self.bernoulli.k = self._set_k(k[0])",
"n=new_b_model.n ) return new_bl def __mul__(self, k): if not isinstance(k, list): raise TypeError",
"if mu is not None else None, std=std if std is not None",
"k): if not isinstance(k, list): raise TypeError self.bernoulli.k = self._set_k(k[0]) self.lognormal.k = self._set_k(k[1])",
"not None and alpha is not None else None ) self.lognormal = Lognormal(",
"std is not None else None, n=alpha if alpha is not None else",
"n is not None and alpha is not None else None ) self.lognormal",
"__mul__(self, k): if not isinstance(k, list): raise TypeError self.bernoulli.k = self._set_k(k[0]) self.lognormal.k =",
"x is not None else None, mu=mu if mu is not None else",
"- alpha if n is not None and alpha is not None else",
"x=(x > 0) * 1 if x is not None else None, alpha=alpha",
"self.lognormal = Lognormal( x=x[x > 0] if x is not None else None,",
"= self._set_k(k_b) self.lognormal.k = self._set_k(k_l) def __rshift__(self, dist): if not isinstance(dist, BLModel): raise",
"if x is not None else None, alpha=alpha if alpha is not None",
"super(BLModel, self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args): return np.prod(args, axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k =",
"-*- coding: utf-8 -*- import numpy as np from .base import Distribution from",
"BLModel( mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n ) return new_bl def __mul__(self, k): if not",
"Lognormal class BLModel(Distribution): def __init__(self, x=None, mu=None, std=None, alpha=None, n=None, k_b=None, k_l=None): self.bernoulli",
"> 0] if x is not None else None, mu=mu if mu is",
"self.bernoulli.k = self._set_k(k_b) self.lognormal.k = self._set_k(k_l) def __rshift__(self, dist): if not isinstance(dist, BLModel):",
"self._set_parent_operation(prod, 'Product') self.bernoulli.k = self._set_k(k_b) self.lognormal.k = self._set_k(k_l) def __rshift__(self, dist): if not",
"Bernoulli, Lognormal class BLModel(Distribution): def __init__(self, x=None, mu=None, std=None, alpha=None, n=None, k_b=None, k_l=None):",
"self).__init__() self._set_parents(self.bernoulli, self.lognormal) def prod(args): return np.prod(args, axis=0) self._set_parent_operation(prod, 'Product') self.bernoulli.k = self._set_k(k_b)",
"from .distributions import Bernoulli, Lognormal class BLModel(Distribution): def __init__(self, x=None, mu=None, std=None, alpha=None,",
"Lognormal( x=x[x > 0] if x is not None else None, mu=mu if",
"mu=new_l_model.mu, std=new_l_model.std, alpha=new_b_model.alpha, n=new_b_model.n ) return new_bl def __mul__(self, k): if not isinstance(k,",
"np from .base import Distribution from .distributions import Bernoulli, Lognormal class BLModel(Distribution): def",
"None else None, n=alpha if alpha is not None else None ) super(BLModel,",
"= self._set_k(k_l) def __rshift__(self, dist): if not isinstance(dist, BLModel): raise TypeError new_b_model =",
"0] if x is not None else None, mu=mu if mu is not"
] |
[
"from pydantic import BaseModel, Field class URL(BaseModel): \"\"\" FastAPI uses pydantic to validate",
"\"\"\" Simulate get from db like in sqlalchemy, where u can .get by",
"typing.List[URL]: \"\"\" To work with large collections of data better use generators, to",
"URL: \"\"\" DB create simulation. Better check 'code' in db for duplicate, but",
"at a time. Combo with asyncio allows async for loop. With real db",
"\"\"\" FastAPI uses pydantic to validate and represent data. Maybe dive deeper in",
"\"\"\" Fake db When using with real -- all CRUD should be awaited",
"next(item for item in self._items.values() if item.full_url == full_url or item.short_url_code == short_url_code)",
"for item in self._items.values() if item.full_url == full_url or item.short_url_code == short_url_code) except",
"With real db you will be awaiting reads from it. \"\"\" for url",
"awaiting reads from it. \"\"\" for url in self._items.values(): yield url async def",
"db for duplicate, but not here, cause it`s an example project. \"\"\" id",
"real -- all CRUD should be awaited \"\"\" def __init__(self): self._items: typing.Dict[int, URL]",
"full_url: str = Field(..., title=\"Full URL\") short_url_code: str = Field(..., title=\"Redirection code of",
"random import uuid from pydantic import BaseModel, Field class URL(BaseModel): \"\"\" FastAPI uses",
"class Database: \"\"\" Fake db When using with real -- all CRUD should",
"typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn means that method raises an error else it returns",
"class URL(BaseModel): \"\"\" FastAPI uses pydantic to validate and represent data. Maybe dive",
"validate and represent data. Maybe dive deeper in it. \"\"\" id: int =",
".get by 'key' \"\"\" if id: return self._items.get(id) try: return next(item for item",
"None]: \"\"\" typing.NoReturn means that method raises an error else it returns None",
"can .get by 'key' \"\"\" if id: return self._items.get(id) try: return next(item for",
"int: \"\"\" Create list from dict_keys, because it is not supported in random.choice",
"random.choice \"\"\" ids = list(self._items.keys()) return random.choice(ids) async def get_all(self) -> typing.List[URL]: \"\"\"",
"time. Combo with asyncio allows async for loop. With real db you will",
"item in self._items.values() if item.full_url == full_url or item.short_url_code == short_url_code) except StopIteration:",
"len(self._items) + 1 code = uuid.uuid4().hex[:8] new_url = URL(id=id, full_url=url, short_url_code=code) self._items[id] =",
"Field(..., title=\"Full URL\") short_url_code: str = Field(..., title=\"Redirection code of URL\") class Database:",
"db When using with real -- all CRUD should be awaited \"\"\" def",
"= len(self._items) + 1 code = uuid.uuid4().hex[:8] new_url = URL(id=id, full_url=url, short_url_code=code) self._items[id]",
"better use generators, to give an item one at a time. Combo with",
"self._items.get(id) try: return next(item for item in self._items.values() if item.full_url == full_url or",
"supported in random.choice \"\"\" ids = list(self._items.keys()) return random.choice(ids) async def get_all(self) ->",
"because it is not supported in random.choice \"\"\" ids = list(self._items.keys()) return random.choice(ids)",
"\"\"\" for url in self._items.values(): yield url async def get(self, id: typing.Optional[int] =",
"uuid from pydantic import BaseModel, Field class URL(BaseModel): \"\"\" FastAPI uses pydantic to",
"Combo with asyncio allows async for loop. With real db you will be",
"title=\"ID of URL\") full_url: str = Field(..., title=\"Full URL\") short_url_code: str = Field(...,",
"list(self._items.keys()) return random.choice(ids) async def get_all(self) -> typing.List[URL]: \"\"\" To work with large",
"return self._items.get(id) try: return next(item for item in self._items.values() if item.full_url == full_url",
"not supported in random.choice \"\"\" ids = list(self._items.keys()) return random.choice(ids) async def get_all(self)",
"returns None as any other method/function with no 'return' specified same as typing.Optional[typing.NoReturn]",
"example project. \"\"\" id = len(self._items) + 1 code = uuid.uuid4().hex[:8] new_url =",
"import BaseModel, Field class URL(BaseModel): \"\"\" FastAPI uses pydantic to validate and represent",
"one at a time. Combo with asyncio allows async for loop. With real",
"URL\") class Database: \"\"\" Fake db When using with real -- all CRUD",
"reads from it. \"\"\" for url in self._items.values(): yield url async def get(self,",
"URL(id=id, full_url=url, short_url_code=code) self._items[id] = new_url return new_url async def delete(self, id: int)",
"if id: return self._items.get(id) try: return next(item for item in self._items.values() if item.full_url",
"-> typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn means that method raises an error else it",
"generators, to give an item one at a time. Combo with asyncio allows",
"yield url async def get(self, id: typing.Optional[int] = None, full_url: typing.Optional[str] = None,",
"typing.Optional[typing.NoReturn] \"\"\" if id in self._items: del self._items[id] else: raise ValueError(\"URL doesn`t exist\")",
"title=\"Redirection code of URL\") class Database: \"\"\" Fake db When using with real",
"full_url: typing.Optional[str] = None, short_url_code: typing.Optional[str] = None) -> typing.Optional[URL]: \"\"\" Simulate get",
"check 'code' in db for duplicate, but not here, cause it`s an example",
"return next(item for item in self._items.values() if item.full_url == full_url or item.short_url_code ==",
"def get(self, id: typing.Optional[int] = None, full_url: typing.Optional[str] = None, short_url_code: typing.Optional[str] =",
"any other method/function with no 'return' specified same as typing.Optional[typing.NoReturn] \"\"\" if id",
"\"\"\" To work with large collections of data better use generators, to give",
"uses pydantic to validate and represent data. Maybe dive deeper in it. \"\"\"",
"= list(self._items.keys()) return random.choice(ids) async def get_all(self) -> typing.List[URL]: \"\"\" To work with",
"-- all CRUD should be awaited \"\"\" def __init__(self): self._items: typing.Dict[int, URL] =",
"get_all(self) -> typing.List[URL]: \"\"\" To work with large collections of data better use",
"should be awaited \"\"\" def __init__(self): self._items: typing.Dict[int, URL] = {} async def",
"as typing.Optional[typing.NoReturn] \"\"\" if id in self._items: del self._items[id] else: raise ValueError(\"URL doesn`t",
"str = Field(..., title=\"Full URL\") short_url_code: str = Field(..., title=\"Redirection code of URL\")",
"Create list from dict_keys, because it is not supported in random.choice \"\"\" ids",
"-> int: \"\"\" Create list from dict_keys, because it is not supported in",
"id = len(self._items) + 1 code = uuid.uuid4().hex[:8] new_url = URL(id=id, full_url=url, short_url_code=code)",
"of URL\") class Database: \"\"\" Fake db When using with real -- all",
"short_url_code: typing.Optional[str] = None) -> typing.Optional[URL]: \"\"\" Simulate get from db like in",
"in self._items.values() if item.full_url == full_url or item.short_url_code == short_url_code) except StopIteration: return",
"or item.short_url_code == short_url_code) except StopIteration: return None async def add(self, url: str)",
"\"\"\" id = len(self._items) + 1 code = uuid.uuid4().hex[:8] new_url = URL(id=id, full_url=url,",
"you will be awaiting reads from it. \"\"\" for url in self._items.values(): yield",
"typing.Dict[int, URL] = {} async def get_random(self) -> int: \"\"\" Create list from",
"else it returns None as any other method/function with no 'return' specified same",
"StopIteration: return None async def add(self, url: str) -> URL: \"\"\" DB create",
"error else it returns None as any other method/function with no 'return' specified",
"an item one at a time. Combo with asyncio allows async for loop.",
"= Field(..., title=\"Full URL\") short_url_code: str = Field(..., title=\"Redirection code of URL\") class",
"represent data. Maybe dive deeper in it. \"\"\" id: int = Field(..., title=\"ID",
"Fake db When using with real -- all CRUD should be awaited \"\"\"",
"= uuid.uuid4().hex[:8] new_url = URL(id=id, full_url=url, short_url_code=code) self._items[id] = new_url return new_url async",
"item.short_url_code == short_url_code) except StopIteration: return None async def add(self, url: str) ->",
"URL(BaseModel): \"\"\" FastAPI uses pydantic to validate and represent data. Maybe dive deeper",
"\"\"\" Create list from dict_keys, because it is not supported in random.choice \"\"\"",
"url async def get(self, id: typing.Optional[int] = None, full_url: typing.Optional[str] = None, short_url_code:",
"data. Maybe dive deeper in it. \"\"\" id: int = Field(..., title=\"ID of",
"Field(..., title=\"ID of URL\") full_url: str = Field(..., title=\"Full URL\") short_url_code: str =",
"if item.full_url == full_url or item.short_url_code == short_url_code) except StopIteration: return None async",
"it`s an example project. \"\"\" id = len(self._items) + 1 code = uuid.uuid4().hex[:8]",
"Better check 'code' in db for duplicate, but not here, cause it`s an",
"it. \"\"\" id: int = Field(..., title=\"ID of URL\") full_url: str = Field(...,",
"new_url = URL(id=id, full_url=url, short_url_code=code) self._items[id] = new_url return new_url async def delete(self,",
"= URL(id=id, full_url=url, short_url_code=code) self._items[id] = new_url return new_url async def delete(self, id:",
"sqlalchemy, where u can .get by 'key' \"\"\" if id: return self._items.get(id) try:",
"def get_all(self) -> typing.List[URL]: \"\"\" To work with large collections of data better",
"str = Field(..., title=\"Redirection code of URL\") class Database: \"\"\" Fake db When",
"get_random(self) -> int: \"\"\" Create list from dict_keys, because it is not supported",
"pydantic import BaseModel, Field class URL(BaseModel): \"\"\" FastAPI uses pydantic to validate and",
"u can .get by 'key' \"\"\" if id: return self._items.get(id) try: return next(item",
"self._items: typing.Dict[int, URL] = {} async def get_random(self) -> int: \"\"\" Create list",
"asyncio allows async for loop. With real db you will be awaiting reads",
"it. \"\"\" for url in self._items.values(): yield url async def get(self, id: typing.Optional[int]",
"here, cause it`s an example project. \"\"\" id = len(self._items) + 1 code",
"title=\"Full URL\") short_url_code: str = Field(..., title=\"Redirection code of URL\") class Database: \"\"\"",
"but not here, cause it`s an example project. \"\"\" id = len(self._items) +",
"code of URL\") class Database: \"\"\" Fake db When using with real --",
"using with real -- all CRUD should be awaited \"\"\" def __init__(self): self._items:",
"== short_url_code) except StopIteration: return None async def add(self, url: str) -> URL:",
"{} async def get_random(self) -> int: \"\"\" Create list from dict_keys, because it",
"create simulation. Better check 'code' in db for duplicate, but not here, cause",
"+ 1 code = uuid.uuid4().hex[:8] new_url = URL(id=id, full_url=url, short_url_code=code) self._items[id] = new_url",
"of URL\") full_url: str = Field(..., title=\"Full URL\") short_url_code: str = Field(..., title=\"Redirection",
"\"\"\" def __init__(self): self._items: typing.Dict[int, URL] = {} async def get_random(self) -> int:",
"to give an item one at a time. Combo with asyncio allows async",
"'return' specified same as typing.Optional[typing.NoReturn] \"\"\" if id in self._items: del self._items[id] else:",
"typing.Optional[int] = None, full_url: typing.Optional[str] = None, short_url_code: typing.Optional[str] = None) -> typing.Optional[URL]:",
"except StopIteration: return None async def add(self, url: str) -> URL: \"\"\" DB",
"When using with real -- all CRUD should be awaited \"\"\" def __init__(self):",
"where u can .get by 'key' \"\"\" if id: return self._items.get(id) try: return",
"an example project. \"\"\" id = len(self._items) + 1 code = uuid.uuid4().hex[:8] new_url",
"id: int = Field(..., title=\"ID of URL\") full_url: str = Field(..., title=\"Full URL\")",
"item one at a time. Combo with asyncio allows async for loop. With",
"db you will be awaiting reads from it. \"\"\" for url in self._items.values():",
"\"\"\" ids = list(self._items.keys()) return random.choice(ids) async def get_all(self) -> typing.List[URL]: \"\"\" To",
"of data better use generators, to give an item one at a time.",
"def add(self, url: str) -> URL: \"\"\" DB create simulation. Better check 'code'",
"Field(..., title=\"Redirection code of URL\") class Database: \"\"\" Fake db When using with",
"be awaited \"\"\" def __init__(self): self._items: typing.Dict[int, URL] = {} async def get_random(self)",
"\"\"\" DB create simulation. Better check 'code' in db for duplicate, but not",
"all CRUD should be awaited \"\"\" def __init__(self): self._items: typing.Dict[int, URL] = {}",
"short_url_code: str = Field(..., title=\"Redirection code of URL\") class Database: \"\"\" Fake db",
"return random.choice(ids) async def get_all(self) -> typing.List[URL]: \"\"\" To work with large collections",
"in it. \"\"\" id: int = Field(..., title=\"ID of URL\") full_url: str =",
"use generators, to give an item one at a time. Combo with asyncio",
"\"\"\" if id: return self._items.get(id) try: return next(item for item in self._items.values() if",
"typing.Optional[str] = None) -> typing.Optional[URL]: \"\"\" Simulate get from db like in sqlalchemy,",
"int) -> typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn means that method raises an error else",
"URL\") full_url: str = Field(..., title=\"Full URL\") short_url_code: str = Field(..., title=\"Redirection code",
"same as typing.Optional[typing.NoReturn] \"\"\" if id in self._items: del self._items[id] else: raise ValueError(\"URL",
"with asyncio allows async for loop. With real db you will be awaiting",
"will be awaiting reads from it. \"\"\" for url in self._items.values(): yield url",
"with real -- all CRUD should be awaited \"\"\" def __init__(self): self._items: typing.Dict[int,",
"typing.Optional[str] = None, short_url_code: typing.Optional[str] = None) -> typing.Optional[URL]: \"\"\" Simulate get from",
"= None, short_url_code: typing.Optional[str] = None) -> typing.Optional[URL]: \"\"\" Simulate get from db",
"is not supported in random.choice \"\"\" ids = list(self._items.keys()) return random.choice(ids) async def",
"URL] = {} async def get_random(self) -> int: \"\"\" Create list from dict_keys,",
"async def add(self, url: str) -> URL: \"\"\" DB create simulation. Better check",
"a time. Combo with asyncio allows async for loop. With real db you",
"self._items.values() if item.full_url == full_url or item.short_url_code == short_url_code) except StopIteration: return None",
"typing.NoReturn means that method raises an error else it returns None as any",
"ids = list(self._items.keys()) return random.choice(ids) async def get_all(self) -> typing.List[URL]: \"\"\" To work",
"collections of data better use generators, to give an item one at a",
"typing.Optional[URL]: \"\"\" Simulate get from db like in sqlalchemy, where u can .get",
"-> URL: \"\"\" DB create simulation. Better check 'code' in db for duplicate,",
"None) -> typing.Optional[URL]: \"\"\" Simulate get from db like in sqlalchemy, where u",
"that method raises an error else it returns None as any other method/function",
"method/function with no 'return' specified same as typing.Optional[typing.NoReturn] \"\"\" if id in self._items:",
"url: str) -> URL: \"\"\" DB create simulation. Better check 'code' in db",
"None async def add(self, url: str) -> URL: \"\"\" DB create simulation. Better",
"new_url return new_url async def delete(self, id: int) -> typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn",
"= Field(..., title=\"Redirection code of URL\") class Database: \"\"\" Fake db When using",
"short_url_code=code) self._items[id] = new_url return new_url async def delete(self, id: int) -> typing.Union[typing.NoReturn,",
"cause it`s an example project. \"\"\" id = len(self._items) + 1 code =",
"None as any other method/function with no 'return' specified same as typing.Optional[typing.NoReturn] \"\"\"",
"code = uuid.uuid4().hex[:8] new_url = URL(id=id, full_url=url, short_url_code=code) self._items[id] = new_url return new_url",
"async def get_random(self) -> int: \"\"\" Create list from dict_keys, because it is",
"in sqlalchemy, where u can .get by 'key' \"\"\" if id: return self._items.get(id)",
"real db you will be awaiting reads from it. \"\"\" for url in",
"async for loop. With real db you will be awaiting reads from it.",
"for url in self._items.values(): yield url async def get(self, id: typing.Optional[int] = None,",
"dive deeper in it. \"\"\" id: int = Field(..., title=\"ID of URL\") full_url:",
"allows async for loop. With real db you will be awaiting reads from",
"dict_keys, because it is not supported in random.choice \"\"\" ids = list(self._items.keys()) return",
"= Field(..., title=\"ID of URL\") full_url: str = Field(..., title=\"Full URL\") short_url_code: str",
"awaited \"\"\" def __init__(self): self._items: typing.Dict[int, URL] = {} async def get_random(self) ->",
"import random import uuid from pydantic import BaseModel, Field class URL(BaseModel): \"\"\" FastAPI",
"list from dict_keys, because it is not supported in random.choice \"\"\" ids =",
"1 code = uuid.uuid4().hex[:8] new_url = URL(id=id, full_url=url, short_url_code=code) self._items[id] = new_url return",
"Maybe dive deeper in it. \"\"\" id: int = Field(..., title=\"ID of URL\")",
"import uuid from pydantic import BaseModel, Field class URL(BaseModel): \"\"\" FastAPI uses pydantic",
"in random.choice \"\"\" ids = list(self._items.keys()) return random.choice(ids) async def get_all(self) -> typing.List[URL]:",
"get(self, id: typing.Optional[int] = None, full_url: typing.Optional[str] = None, short_url_code: typing.Optional[str] = None)",
"Field class URL(BaseModel): \"\"\" FastAPI uses pydantic to validate and represent data. Maybe",
"work with large collections of data better use generators, to give an item",
"try: return next(item for item in self._items.values() if item.full_url == full_url or item.short_url_code",
"for duplicate, but not here, cause it`s an example project. \"\"\" id =",
"it returns None as any other method/function with no 'return' specified same as",
"by 'key' \"\"\" if id: return self._items.get(id) try: return next(item for item in",
"import typing import random import uuid from pydantic import BaseModel, Field class URL(BaseModel):",
"CRUD should be awaited \"\"\" def __init__(self): self._items: typing.Dict[int, URL] = {} async",
"like in sqlalchemy, where u can .get by 'key' \"\"\" if id: return",
"BaseModel, Field class URL(BaseModel): \"\"\" FastAPI uses pydantic to validate and represent data.",
"id: return self._items.get(id) try: return next(item for item in self._items.values() if item.full_url ==",
"None, full_url: typing.Optional[str] = None, short_url_code: typing.Optional[str] = None) -> typing.Optional[URL]: \"\"\" Simulate",
"Simulate get from db like in sqlalchemy, where u can .get by 'key'",
"full_url or item.short_url_code == short_url_code) except StopIteration: return None async def add(self, url:",
"pydantic to validate and represent data. Maybe dive deeper in it. \"\"\" id:",
"with large collections of data better use generators, to give an item one",
"large collections of data better use generators, to give an item one at",
"delete(self, id: int) -> typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn means that method raises an",
"return new_url async def delete(self, id: int) -> typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn means",
"id: typing.Optional[int] = None, full_url: typing.Optional[str] = None, short_url_code: typing.Optional[str] = None) ->",
"project. \"\"\" id = len(self._items) + 1 code = uuid.uuid4().hex[:8] new_url = URL(id=id,",
"int = Field(..., title=\"ID of URL\") full_url: str = Field(..., title=\"Full URL\") short_url_code:",
"'key' \"\"\" if id: return self._items.get(id) try: return next(item for item in self._items.values()",
"random.choice(ids) async def get_all(self) -> typing.List[URL]: \"\"\" To work with large collections of",
"= None, full_url: typing.Optional[str] = None, short_url_code: typing.Optional[str] = None) -> typing.Optional[URL]: \"\"\"",
"\"\"\" typing.NoReturn means that method raises an error else it returns None as",
"None, short_url_code: typing.Optional[str] = None) -> typing.Optional[URL]: \"\"\" Simulate get from db like",
"means that method raises an error else it returns None as any other",
"as any other method/function with no 'return' specified same as typing.Optional[typing.NoReturn] \"\"\" if",
"uuid.uuid4().hex[:8] new_url = URL(id=id, full_url=url, short_url_code=code) self._items[id] = new_url return new_url async def",
"'code' in db for duplicate, but not here, cause it`s an example project.",
"specified same as typing.Optional[typing.NoReturn] \"\"\" if id in self._items: del self._items[id] else: raise",
"-> typing.List[URL]: \"\"\" To work with large collections of data better use generators,",
"from it. \"\"\" for url in self._items.values(): yield url async def get(self, id:",
"in self._items.values(): yield url async def get(self, id: typing.Optional[int] = None, full_url: typing.Optional[str]",
"method raises an error else it returns None as any other method/function with",
"no 'return' specified same as typing.Optional[typing.NoReturn] \"\"\" if id in self._items: del self._items[id]",
"async def delete(self, id: int) -> typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn means that method",
"raises an error else it returns None as any other method/function with no",
"with no 'return' specified same as typing.Optional[typing.NoReturn] \"\"\" if id in self._items: del",
"= {} async def get_random(self) -> int: \"\"\" Create list from dict_keys, because",
"self._items.values(): yield url async def get(self, id: typing.Optional[int] = None, full_url: typing.Optional[str] =",
"async def get(self, id: typing.Optional[int] = None, full_url: typing.Optional[str] = None, short_url_code: typing.Optional[str]",
"str) -> URL: \"\"\" DB create simulation. Better check 'code' in db for",
"= new_url return new_url async def delete(self, id: int) -> typing.Union[typing.NoReturn, None]: \"\"\"",
"To work with large collections of data better use generators, to give an",
"simulation. Better check 'code' in db for duplicate, but not here, cause it`s",
"and represent data. Maybe dive deeper in it. \"\"\" id: int = Field(...,",
"typing import random import uuid from pydantic import BaseModel, Field class URL(BaseModel): \"\"\"",
"data better use generators, to give an item one at a time. Combo",
"get from db like in sqlalchemy, where u can .get by 'key' \"\"\"",
"in db for duplicate, but not here, cause it`s an example project. \"\"\"",
"it is not supported in random.choice \"\"\" ids = list(self._items.keys()) return random.choice(ids) async",
"-> typing.Optional[URL]: \"\"\" Simulate get from db like in sqlalchemy, where u can",
"__init__(self): self._items: typing.Dict[int, URL] = {} async def get_random(self) -> int: \"\"\" Create",
"db like in sqlalchemy, where u can .get by 'key' \"\"\" if id:",
"url in self._items.values(): yield url async def get(self, id: typing.Optional[int] = None, full_url:",
"def get_random(self) -> int: \"\"\" Create list from dict_keys, because it is not",
"id: int) -> typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn means that method raises an error",
"Database: \"\"\" Fake db When using with real -- all CRUD should be",
"def delete(self, id: int) -> typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn means that method raises",
"for loop. With real db you will be awaiting reads from it. \"\"\"",
"give an item one at a time. Combo with asyncio allows async for",
"an error else it returns None as any other method/function with no 'return'",
"from dict_keys, because it is not supported in random.choice \"\"\" ids = list(self._items.keys())",
"URL\") short_url_code: str = Field(..., title=\"Redirection code of URL\") class Database: \"\"\" Fake",
"from db like in sqlalchemy, where u can .get by 'key' \"\"\" if",
"return None async def add(self, url: str) -> URL: \"\"\" DB create simulation.",
"def __init__(self): self._items: typing.Dict[int, URL] = {} async def get_random(self) -> int: \"\"\"",
"be awaiting reads from it. \"\"\" for url in self._items.values(): yield url async",
"short_url_code) except StopIteration: return None async def add(self, url: str) -> URL: \"\"\"",
"full_url=url, short_url_code=code) self._items[id] = new_url return new_url async def delete(self, id: int) ->",
"DB create simulation. Better check 'code' in db for duplicate, but not here,",
"other method/function with no 'return' specified same as typing.Optional[typing.NoReturn] \"\"\" if id in",
"FastAPI uses pydantic to validate and represent data. Maybe dive deeper in it.",
"async def get_all(self) -> typing.List[URL]: \"\"\" To work with large collections of data",
"new_url async def delete(self, id: int) -> typing.Union[typing.NoReturn, None]: \"\"\" typing.NoReturn means that",
"\"\"\" id: int = Field(..., title=\"ID of URL\") full_url: str = Field(..., title=\"Full",
"not here, cause it`s an example project. \"\"\" id = len(self._items) + 1",
"add(self, url: str) -> URL: \"\"\" DB create simulation. Better check 'code' in",
"= None) -> typing.Optional[URL]: \"\"\" Simulate get from db like in sqlalchemy, where",
"item.full_url == full_url or item.short_url_code == short_url_code) except StopIteration: return None async def",
"to validate and represent data. Maybe dive deeper in it. \"\"\" id: int",
"== full_url or item.short_url_code == short_url_code) except StopIteration: return None async def add(self,",
"self._items[id] = new_url return new_url async def delete(self, id: int) -> typing.Union[typing.NoReturn, None]:",
"deeper in it. \"\"\" id: int = Field(..., title=\"ID of URL\") full_url: str",
"duplicate, but not here, cause it`s an example project. \"\"\" id = len(self._items)",
"loop. With real db you will be awaiting reads from it. \"\"\" for"
] |
[
"simplified_params = module.get_graph_json(), module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\", \"microtvm\",",
"= \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1",
"tvm.relay.build(mod, target=target, params=params) graph_json, compiled_model, simplified_params = module.get_graph_json(), module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\"",
"\"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module = tvm.relay.build(mod, target=target, params=params) graph_json, compiled_model, simplified_params",
"from tvm import relay import onnx import tvm.micro from tvm.micro.contrib import zephyr import",
"as np model_path = \"add.onnx\" onnx_model = onnx.load(model_path) input1_name = \"Input1\" input2_name =",
"= module.get_graph_json(), module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\",",
"module = tvm.relay.build(mod, target=target, params=params) graph_json, compiled_model, simplified_params = module.get_graph_json(), module.get_lib(), module.get_params() repo_root",
"= tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts) dtype = \"float32\" with tvm.micro.Session(binary=micro_bin,",
"flasher=compiler.flasher()) as sess: m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1 = tvm.nd.array(np.array([4], dtype=dtype)) input2",
"import tvm.micro from tvm.micro.contrib import zephyr import os import numpy as np model_path",
"onnx_model = onnx.load(model_path) input1_name = \"Input1\" input2_name = \"Input2\" shape_dict = {input1_name: [1],",
"zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", ) opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True) micro_bin =",
"import zephyr import os import numpy as np model_path = \"add.onnx\" onnx_model =",
"repo_root = \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\") compiler = zephyr.ZephyrCompiler(",
"\"Input1\" input2_name = \"Input2\" shape_dict = {input1_name: [1], input2_name: [1]} mod, params =",
"zephyr_toolchain_variant=\"zephyr\", ) opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace, compiler, compiled_model,",
"tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1 = tvm.nd.array(np.array([4], dtype=dtype))",
"project_dir = os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\") compiler = zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\",",
"import relay import onnx import tvm.micro from tvm.micro.contrib import zephyr import os import",
"= \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\") compiler = zephyr.ZephyrCompiler( project_dir=project_dir,",
"True}): module = tvm.relay.build(mod, target=target, params=params) graph_json, compiled_model, simplified_params = module.get_graph_json(), module.get_lib(), module.get_params()",
"zephyr import os import numpy as np model_path = \"add.onnx\" onnx_model = onnx.load(model_path)",
"import numpy as np model_path = \"add.onnx\" onnx_model = onnx.load(model_path) input1_name = \"Input1\"",
"as sess: m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1 = tvm.nd.array(np.array([4], dtype=dtype)) input2 =",
"import os import numpy as np model_path = \"add.onnx\" onnx_model = onnx.load(model_path) input1_name",
"sess.get_system_lib(), sess.device) input1 = tvm.nd.array(np.array([4], dtype=dtype)) input2 = tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\", input1) m_.set_input(\"Input2\",",
"\"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1 =",
"input1_name = \"Input1\" input2_name = \"Input2\" shape_dict = {input1_name: [1], input2_name: [1]} mod,",
"tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts) dtype = \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher())",
"\"Input2\" shape_dict = {input1_name: [1], input2_name: [1]} mod, params = relay.frontend.from_onnx(onnx_model, shape_dict) target",
"onnx import tvm.micro from tvm.micro.contrib import zephyr import os import numpy as np",
"import tvm from tvm import relay import onnx import tvm.micro from tvm.micro.contrib import",
"\"demo_runtime\") compiler = zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", ) opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace =",
"= tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module = tvm.relay.build(mod, target=target,",
"tvm.nd.array(np.array([4], dtype=dtype)) input2 = tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\", input1) m_.set_input(\"Input2\", input2) m_.run() output =",
"= tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\", input1) m_.set_input(\"Input2\", input2) m_.run() output = m_.get_output(0).asnumpy() print('microTVM:', output)",
"input2 = tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\", input1) m_.set_input(\"Input2\", input2) m_.run() output = m_.get_output(0).asnumpy() print('microTVM:',",
"compiler, compiled_model, opts) dtype = \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_ =",
"input2_name: [1]} mod, params = relay.frontend.from_onnx(onnx_model, shape_dict) target = tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\"",
"opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts) dtype",
"compiled_model, opts) dtype = \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_ = tvm.micro.create_local_graph_executor(graph_json,",
"= \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module = tvm.relay.build(mod, target=target, params=params) graph_json, compiled_model,",
"shape_dict) target = tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module =",
"module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\") compiler",
"<reponame>mshr-h/nucleo-f746zg-microtvm-example import tvm from tvm import relay import onnx import tvm.micro from tvm.micro.contrib",
"input2_name = \"Input2\" shape_dict = {input1_name: [1], input2_name: [1]} mod, params = relay.frontend.from_onnx(onnx_model,",
"= zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", ) opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True) micro_bin",
"compiler = zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", ) opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True)",
"dtype=dtype)) input2 = tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\", input1) m_.set_input(\"Input2\", input2) m_.run() output = m_.get_output(0).asnumpy()",
"\"add.onnx\" onnx_model = onnx.load(model_path) input1_name = \"Input1\" input2_name = \"Input2\" shape_dict = {input1_name:",
"module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\") compiler =",
"tvm.micro from tvm.micro.contrib import zephyr import os import numpy as np model_path =",
"= tvm.relay.build(mod, target=target, params=params) graph_json, compiled_model, simplified_params = module.get_graph_json(), module.get_lib(), module.get_params() repo_root =",
"project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", ) opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace,",
"model_path = \"add.onnx\" onnx_model = onnx.load(model_path) input1_name = \"Input1\" input2_name = \"Input2\" shape_dict",
"np model_path = \"add.onnx\" onnx_model = onnx.load(model_path) input1_name = \"Input1\" input2_name = \"Input2\"",
"{input1_name: [1], input2_name: [1]} mod, params = relay.frontend.from_onnx(onnx_model, shape_dict) target = tvm.target.target.micro(\"stm32f746xx\") board",
"with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1 = tvm.nd.array(np.array([4],",
"= tvm.nd.array(np.array([4], dtype=dtype)) input2 = tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\", input1) m_.set_input(\"Input2\", input2) m_.run() output",
"dtype = \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device)",
"= \"add.onnx\" onnx_model = onnx.load(model_path) input1_name = \"Input1\" input2_name = \"Input2\" shape_dict =",
"compiled_model, simplified_params = module.get_graph_json(), module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\",",
"tvm import relay import onnx import tvm.micro from tvm.micro.contrib import zephyr import os",
"= \"Input2\" shape_dict = {input1_name: [1], input2_name: [1]} mod, params = relay.frontend.from_onnx(onnx_model, shape_dict)",
"sess: m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1 = tvm.nd.array(np.array([4], dtype=dtype)) input2 = tvm.nd.array(np.array([7],",
") opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts)",
"numpy as np model_path = \"add.onnx\" onnx_model = onnx.load(model_path) input1_name = \"Input1\" input2_name",
"[1], input2_name: [1]} mod, params = relay.frontend.from_onnx(onnx_model, shape_dict) target = tvm.target.target.micro(\"stm32f746xx\") board =",
"target = tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module = tvm.relay.build(mod,",
"params = relay.frontend.from_onnx(onnx_model, shape_dict) target = tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\":",
"micro_bin = tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts) dtype = \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as",
"relay import onnx import tvm.micro from tvm.micro.contrib import zephyr import os import numpy",
"= relay.frontend.from_onnx(onnx_model, shape_dict) target = tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):",
"board=board, zephyr_toolchain_variant=\"zephyr\", ) opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace, compiler,",
"workspace = tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts) dtype = \"float32\" with",
"= {input1_name: [1], input2_name: [1]} mod, params = relay.frontend.from_onnx(onnx_model, shape_dict) target = tvm.target.target.micro(\"stm32f746xx\")",
"config={\"tir.disable_vectorize\": True}): module = tvm.relay.build(mod, target=target, params=params) graph_json, compiled_model, simplified_params = module.get_graph_json(), module.get_lib(),",
"= tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1 = tvm.nd.array(np.array([4], dtype=dtype)) input2 = tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\",",
"module.get_graph_json(), module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\")",
"= \"Input1\" input2_name = \"Input2\" shape_dict = {input1_name: [1], input2_name: [1]} mod, params",
"= os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\") compiler = zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", )",
"sess.device) input1 = tvm.nd.array(np.array([4], dtype=dtype)) input2 = tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\", input1) m_.set_input(\"Input2\", input2)",
"os import numpy as np model_path = \"add.onnx\" onnx_model = onnx.load(model_path) input1_name =",
"params=params) graph_json, compiled_model, simplified_params = module.get_graph_json(), module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir =",
"\"microtvm\", \"zephyr\", \"demo_runtime\") compiler = zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", ) opts = tvm.micro.default_options(f\"{project_dir}/crt\")",
"tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts) dtype = \"float32\"",
"with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module = tvm.relay.build(mod, target=target, params=params) graph_json, compiled_model, simplified_params =",
"os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\") compiler = zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", ) opts",
"= onnx.load(model_path) input1_name = \"Input1\" input2_name = \"Input2\" shape_dict = {input1_name: [1], input2_name:",
"tvm from tvm import relay import onnx import tvm.micro from tvm.micro.contrib import zephyr",
"\"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root, \"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\") compiler = zephyr.ZephyrCompiler( project_dir=project_dir, board=board,",
"relay.frontend.from_onnx(onnx_model, shape_dict) target = tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module",
"tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts) dtype = \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_",
"input1 = tvm.nd.array(np.array([4], dtype=dtype)) input2 = tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\", input1) m_.set_input(\"Input2\", input2) m_.run()",
"import onnx import tvm.micro from tvm.micro.contrib import zephyr import os import numpy as",
"tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1 = tvm.nd.array(np.array([4], dtype=dtype)) input2 = tvm.nd.array(np.array([7], dtype=dtype)) m_.set_input(\"Input1\", input1)",
"tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module = tvm.relay.build(mod, target=target, params=params)",
"target=target, params=params) graph_json, compiled_model, simplified_params = module.get_graph_json(), module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir",
"m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(), sess.device) input1 = tvm.nd.array(np.array([4], dtype=dtype)) input2 = tvm.nd.array(np.array([7], dtype=dtype))",
"\"zephyr\", \"demo_runtime\") compiler = zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", ) opts = tvm.micro.default_options(f\"{project_dir}/crt\") workspace",
"opts) dtype = \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess: m_ = tvm.micro.create_local_graph_executor(graph_json, sess.get_system_lib(),",
"= tvm.micro.default_options(f\"{project_dir}/crt\") workspace = tvm.micro.Workspace(debug=True) micro_bin = tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts) dtype =",
"graph_json, compiled_model, simplified_params = module.get_graph_json(), module.get_lib(), module.get_params() repo_root = \"/home/ubuntu/workspace/tvm\" project_dir = os.path.join(repo_root,",
"tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module = tvm.relay.build(mod, target=target, params=params) graph_json, compiled_model, simplified_params = module.get_graph_json(),",
"onnx.load(model_path) input1_name = \"Input1\" input2_name = \"Input2\" shape_dict = {input1_name: [1], input2_name: [1]}",
"mod, params = relay.frontend.from_onnx(onnx_model, shape_dict) target = tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3,",
"= tvm.micro.build_static_runtime(workspace, compiler, compiled_model, opts) dtype = \"float32\" with tvm.micro.Session(binary=micro_bin, flasher=compiler.flasher()) as sess:",
"[1]} mod, params = relay.frontend.from_onnx(onnx_model, shape_dict) target = tvm.target.target.micro(\"stm32f746xx\") board = \"nucleo_f746zg\" with",
"board = \"nucleo_f746zg\" with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}): module = tvm.relay.build(mod, target=target, params=params) graph_json,",
"shape_dict = {input1_name: [1], input2_name: [1]} mod, params = relay.frontend.from_onnx(onnx_model, shape_dict) target =",
"tvm.micro.contrib import zephyr import os import numpy as np model_path = \"add.onnx\" onnx_model",
"\"apps\", \"microtvm\", \"zephyr\", \"demo_runtime\") compiler = zephyr.ZephyrCompiler( project_dir=project_dir, board=board, zephyr_toolchain_variant=\"zephyr\", ) opts =",
"from tvm.micro.contrib import zephyr import os import numpy as np model_path = \"add.onnx\""
] |
[
"# First check if the data has been generated # If not prompt",
"looks like no processed data has been generated.\\n', 'Please run the \\'data_generation.py\\' file",
"directory\\ in order to run these scripts. Type \\'pwd\\' in the command line\\",
"filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not appear to be in the correct directory,\\ you must",
"has been generated.\\n', 'Please run the \\'data_generation.py\\' file and follow the prompts.') sys.exit(1)",
"be used in the other scripts ''' # First check if the data",
"= pd.read_csv(token_data, header = 0) token_type = token_df['type'] token_posts = token_df['posts'] clean_df =",
"Personality Type Tweets Natural Language Processing # By <NAME> # Project can be",
"you are unsure of your location in the terminal.') sys.exit(1) raw_data = 'data/mbti_1.csv'",
"have various versions of our data: - Raw, unfiltered data - Tokenized data",
"check if the data has been generated # If not prompt user to",
"if the data has been generated # If not prompt user to make",
"#!/usr/bin/env python3 ################################################################ # <NAME> Personality Type Tweets Natural Language Processing # By",
"analysis raw_df = pd.read_csv(raw_data, header = 0) raw_type = raw_df['type'] raw_posts = raw_df['posts']",
"and follow the prompts.') sys.exit(1) # Declare different processed and unprocessed objects for",
"into various parts to be used in the other scripts ''' # First",
"sys.exit(1) raw_data = 'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv' columns = np.array(['type',",
"versions of our data for analysis ################################################## ''' Explanation ----------- Now we will",
"data has been generated.\\n', 'Please run the \\'data_generation.py\\' file and follow the prompts.')",
"prompts.') sys.exit(1) # Declare different processed and unprocessed objects for further analysis raw_df",
"X_train_token, X_test_token, y_train_token, y_test_token = train_test_split( token_posts, token_type, test_size = 0.30, random_state =",
"be found at: # https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110 ################################################################ ################## # Import packages",
"numpy as np import pandas as pd from sklearn.model_selection import train_test_split # Confirm",
"test_size = 0.30, random_state = 42) X_train_clean, X_test_clean, y_train_clean, y_test_clean = train_test_split( clean_posts,",
"be in the correct directory,\\ you must be in the \\'myersBriggsNLPAnalysis\\' directory\\ in",
"in the \\'myersBriggsNLPAnalysis\\' directory\\ in order to run these scripts. Type \\'pwd\\' in",
"correct directory,\\ you must be in the \\'myersBriggsNLPAnalysis\\' directory\\ in order to run",
"Tokenized data with hashtags, mentions, retweets, etc. - Cleaned tokenized data with stopwords",
"################################################################ ################## # Import packages ################## import sys, os import numpy as np",
"sys.exit(1) # Declare different processed and unprocessed objects for further analysis raw_df =",
"and prompt user to move to correct directory otherwise filepath = os.getcwd() if",
"file and follow the prompts.') sys.exit(1) # Declare different processed and unprocessed objects",
"Natural Language Processing # By <NAME> # Project can be found at: #",
"effectiveness of model training X_train_token, X_test_token, y_train_token, y_test_token = train_test_split( token_posts, token_type, test_size",
"training X_train_token, X_test_token, y_train_token, y_test_token = train_test_split( token_posts, token_type, test_size = 0.30, random_state",
"mentions, retweets, etc. - Cleaned tokenized data with stopwords removed We will now",
"42) X_train_clean, X_test_clean, y_train_clean, y_test_clean = train_test_split( clean_posts, clean_type, test_size = 0.30, random_state",
"First check if the data has been generated # If not prompt user",
"will now subset the data into various parts to be used in the",
"scripts ''' # First check if the data has been generated # If",
"must be in the \\'myersBriggsNLPAnalysis\\' directory\\ in order to run these scripts. Type",
"packages ################## import sys, os import numpy as np import pandas as pd",
"os import numpy as np import pandas as pd from sklearn.model_selection import train_test_split",
"up data into training and testing datasets # To evaluate effectiveness of model",
"the correct directory; break script and prompt user to move to correct directory",
"# https://www.inertia7.com/projects/110 ################################################################ ################## # Import packages ################## import sys, os import numpy",
"to make it token_file_exists = os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data) if not token_file_exists or",
"\\'myersBriggsNLPAnalysis\\' directory\\ in order to run these scripts. Type \\'pwd\\' in the command",
"python3 ################################################################ # <NAME> Personality Type Tweets Natural Language Processing # By <NAME>",
"break script and prompt user to move to correct directory otherwise filepath =",
"= 42) X_train_clean, X_test_clean, y_train_clean, y_test_clean = train_test_split( clean_posts, clean_type, test_size = 0.30,",
"print('It looks like no processed data has been generated.\\n', 'Please run the \\'data_generation.py\\'",
"directory otherwise filepath = os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not appear to",
"script and prompt user to move to correct directory otherwise filepath = os.getcwd()",
"clean_file_exists: print('It looks like no processed data has been generated.\\n', 'Please run the",
"Make different versions of our data for analysis ################################################## ''' Explanation ----------- Now",
"to move to correct directory otherwise filepath = os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou",
"clean_df['posts'] # Split up data into training and testing datasets # To evaluate",
"clean_file_exists = os.path.isfile(clean_data) if not token_file_exists or not clean_file_exists: print('It looks like no",
"sys, os import numpy as np import pandas as pd from sklearn.model_selection import",
"token_posts, token_type, test_size = 0.30, random_state = 42) X_train_clean, X_test_clean, y_train_clean, y_test_clean =",
"location in the terminal.') sys.exit(1) raw_data = 'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv' clean_data =",
"columns = np.array(['type', 'posts']) ################################################## # Make different versions of our data for",
"= 0) token_type = token_df['type'] token_posts = token_df['posts'] clean_df = pd.read_csv(clean_data, header =",
"different versions of our data for analysis ################################################## ''' Explanation ----------- Now we",
"various versions of our data: - Raw, unfiltered data - Tokenized data with",
"= raw_df['type'] raw_posts = raw_df['posts'] token_df = pd.read_csv(token_data, header = 0) token_type =",
"Declare different processed and unprocessed objects for further analysis raw_df = pd.read_csv(raw_data, header",
"Language Processing # By <NAME> # Project can be found at: # https://www.inertia7.com/projects/109",
"the correct directory,\\ you must be in the \\'myersBriggsNLPAnalysis\\' directory\\ in order to",
"been generated # If not prompt user to make it token_file_exists = os.path.isfile(token_data)",
"train_test_split( token_posts, token_type, test_size = 0.30, random_state = 42) X_train_clean, X_test_clean, y_train_clean, y_test_clean",
"run these scripts. Type \\'pwd\\' in the command line\\ if you are unsure",
"otherwise filepath = os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not appear to be",
"the terminal.') sys.exit(1) raw_data = 'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv' columns",
"generated # If not prompt user to make it token_file_exists = os.path.isfile(token_data) clean_file_exists",
"testing datasets # To evaluate effectiveness of model training X_train_token, X_test_token, y_train_token, y_test_token",
"'Please run the \\'data_generation.py\\' file and follow the prompts.') sys.exit(1) # Declare different",
"0) clean_type = clean_df['type'] clean_posts = clean_df['posts'] # Split up data into training",
"np.array(['type', 'posts']) ################################################## # Make different versions of our data for analysis ##################################################",
"Confirm the correct directory; break script and prompt user to move to correct",
"filepath = os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not appear to be in",
"analysis ################################################## ''' Explanation ----------- Now we will have various versions of our",
"the data has been generated # If not prompt user to make it",
"not clean_file_exists: print('It looks like no processed data has been generated.\\n', 'Please run",
"at: # https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110 ################################################################ ################## # Import packages ################## import",
"the prompts.') sys.exit(1) # Declare different processed and unprocessed objects for further analysis",
"prompt user to move to correct directory otherwise filepath = os.getcwd() if not",
"if you are unsure of your location in the terminal.') sys.exit(1) raw_data =",
"pandas as pd from sklearn.model_selection import train_test_split # Confirm the correct directory; break",
"in the terminal.') sys.exit(1) raw_data = 'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv'",
"'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv' columns = np.array(['type', 'posts']) ################################################## #",
"line\\ if you are unsure of your location in the terminal.') sys.exit(1) raw_data",
"unfiltered data - Tokenized data with hashtags, mentions, retweets, etc. - Cleaned tokenized",
"----------- Now we will have various versions of our data: - Raw, unfiltered",
"tokenized data with stopwords removed We will now subset the data into various",
"other scripts ''' # First check if the data has been generated #",
"= 'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv' columns = np.array(['type', 'posts']) ################################################## # Make different",
"= os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data) if not token_file_exists or not clean_file_exists: print('It looks",
"different processed and unprocessed objects for further analysis raw_df = pd.read_csv(raw_data, header =",
"objects for further analysis raw_df = pd.read_csv(raw_data, header = 0) raw_type = raw_df['type']",
"further analysis raw_df = pd.read_csv(raw_data, header = 0) raw_type = raw_df['type'] raw_posts =",
"for analysis ################################################## ''' Explanation ----------- Now we will have various versions of",
"data into training and testing datasets # To evaluate effectiveness of model training",
"prompt user to make it token_file_exists = os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data) if not",
"make it token_file_exists = os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data) if not token_file_exists or not",
"0) raw_type = raw_df['type'] raw_posts = raw_df['posts'] token_df = pd.read_csv(token_data, header = 0)",
"header = 0) clean_type = clean_df['type'] clean_posts = clean_df['posts'] # Split up data",
"our data for analysis ################################################## ''' Explanation ----------- Now we will have various",
"to be used in the other scripts ''' # First check if the",
"pd.read_csv(raw_data, header = 0) raw_type = raw_df['type'] raw_posts = raw_df['posts'] token_df = pd.read_csv(token_data,",
"token_type = token_df['type'] token_posts = token_df['posts'] clean_df = pd.read_csv(clean_data, header = 0) clean_type",
"'data/mbti_cleaned.csv' columns = np.array(['type', 'posts']) ################################################## # Make different versions of our data",
"in order to run these scripts. Type \\'pwd\\' in the command line\\ if",
"import train_test_split # Confirm the correct directory; break script and prompt user to",
"import pandas as pd from sklearn.model_selection import train_test_split # Confirm the correct directory;",
"are unsure of your location in the terminal.') sys.exit(1) raw_data = 'data/mbti_1.csv' token_data",
"= token_df['type'] token_posts = token_df['posts'] clean_df = pd.read_csv(clean_data, header = 0) clean_type =",
"token_df['type'] token_posts = token_df['posts'] clean_df = pd.read_csv(clean_data, header = 0) clean_type = clean_df['type']",
"correct directory otherwise filepath = os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not appear",
"token_data = 'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv' columns = np.array(['type', 'posts']) ################################################## # Make",
"<NAME> # Project can be found at: # https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110 ################################################################",
"Processing # By <NAME> # Project can be found at: # https://www.inertia7.com/projects/109 &",
"for further analysis raw_df = pd.read_csv(raw_data, header = 0) raw_type = raw_df['type'] raw_posts",
"= pd.read_csv(raw_data, header = 0) raw_type = raw_df['type'] raw_posts = raw_df['posts'] token_df =",
"datasets # To evaluate effectiveness of model training X_train_token, X_test_token, y_train_token, y_test_token =",
"= train_test_split( token_posts, token_type, test_size = 0.30, random_state = 42) X_train_clean, X_test_clean, y_train_clean,",
"= 'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv' columns = np.array(['type', 'posts']) ##################################################",
"and unprocessed objects for further analysis raw_df = pd.read_csv(raw_data, header = 0) raw_type",
"and testing datasets # To evaluate effectiveness of model training X_train_token, X_test_token, y_train_token,",
"raw_df = pd.read_csv(raw_data, header = 0) raw_type = raw_df['type'] raw_posts = raw_df['posts'] token_df",
"token_posts = token_df['posts'] clean_df = pd.read_csv(clean_data, header = 0) clean_type = clean_df['type'] clean_posts",
"y_test_token = train_test_split( token_posts, token_type, test_size = 0.30, random_state = 42) X_train_clean, X_test_clean,",
"https://www.inertia7.com/projects/110 ################################################################ ################## # Import packages ################## import sys, os import numpy as",
"model training X_train_token, X_test_token, y_train_token, y_test_token = train_test_split( token_posts, token_type, test_size = 0.30,",
"to run these scripts. Type \\'pwd\\' in the command line\\ if you are",
"not token_file_exists or not clean_file_exists: print('It looks like no processed data has been",
"of our data for analysis ################################################## ''' Explanation ----------- Now we will have",
"user to make it token_file_exists = os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data) if not token_file_exists",
"import sys, os import numpy as np import pandas as pd from sklearn.model_selection",
"0) token_type = token_df['type'] token_posts = token_df['posts'] clean_df = pd.read_csv(clean_data, header = 0)",
"Type Tweets Natural Language Processing # By <NAME> # Project can be found",
"- Raw, unfiltered data - Tokenized data with hashtags, mentions, retweets, etc. -",
"We will now subset the data into various parts to be used in",
"processed data has been generated.\\n', 'Please run the \\'data_generation.py\\' file and follow the",
"token_df = pd.read_csv(token_data, header = 0) token_type = token_df['type'] token_posts = token_df['posts'] clean_df",
"pd.read_csv(clean_data, header = 0) clean_type = clean_df['type'] clean_posts = clean_df['posts'] # Split up",
"clean_posts = clean_df['posts'] # Split up data into training and testing datasets #",
"# Project can be found at: # https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110 ################################################################ ##################",
"move to correct directory otherwise filepath = os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do",
"- Tokenized data with hashtags, mentions, retweets, etc. - Cleaned tokenized data with",
"not prompt user to make it token_file_exists = os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data) if",
"y_train_token, y_test_token = train_test_split( token_posts, token_type, test_size = 0.30, random_state = 42) X_train_clean,",
"= 0) raw_type = raw_df['type'] raw_posts = raw_df['posts'] token_df = pd.read_csv(token_data, header =",
"in the other scripts ''' # First check if the data has been",
"Split up data into training and testing datasets # To evaluate effectiveness of",
"= pd.read_csv(clean_data, header = 0) clean_type = clean_df['type'] clean_posts = clean_df['posts'] # Split",
"& # https://www.inertia7.com/projects/110 ################################################################ ################## # Import packages ################## import sys, os import",
"Explanation ----------- Now we will have various versions of our data: - Raw,",
"unsure of your location in the terminal.') sys.exit(1) raw_data = 'data/mbti_1.csv' token_data =",
"os.path.isfile(clean_data) if not token_file_exists or not clean_file_exists: print('It looks like no processed data",
"be in the \\'myersBriggsNLPAnalysis\\' directory\\ in order to run these scripts. Type \\'pwd\\'",
"found at: # https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110 ################################################################ ################## # Import packages ##################",
"data with stopwords removed We will now subset the data into various parts",
"clean_df['type'] clean_posts = clean_df['posts'] # Split up data into training and testing datasets",
"stopwords removed We will now subset the data into various parts to be",
"= np.array(['type', 'posts']) ################################################## # Make different versions of our data for analysis",
"'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv' columns = np.array(['type', 'posts']) ################################################## # Make different versions",
"################################################################ # <NAME> Personality Type Tweets Natural Language Processing # By <NAME> #",
"# https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110 ################################################################ ################## # Import packages ################## import sys,",
"Cleaned tokenized data with stopwords removed We will now subset the data into",
"these scripts. Type \\'pwd\\' in the command line\\ if you are unsure of",
"data - Tokenized data with hashtags, mentions, retweets, etc. - Cleaned tokenized data",
"token_type, test_size = 0.30, random_state = 42) X_train_clean, X_test_clean, y_train_clean, y_test_clean = train_test_split(",
"clean_data = 'data/mbti_cleaned.csv' columns = np.array(['type', 'posts']) ################################################## # Make different versions of",
"can be found at: # https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110 ################################################################ ################## # Import",
"our data: - Raw, unfiltered data - Tokenized data with hashtags, mentions, retweets,",
"evaluate effectiveness of model training X_train_token, X_test_token, y_train_token, y_test_token = train_test_split( token_posts, token_type,",
"X_train_clean, X_test_clean, y_train_clean, y_test_clean = train_test_split( clean_posts, clean_type, test_size = 0.30, random_state =",
"os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data) if not token_file_exists or not clean_file_exists: print('It looks like",
"generated.\\n', 'Please run the \\'data_generation.py\\' file and follow the prompts.') sys.exit(1) # Declare",
"raw_df['type'] raw_posts = raw_df['posts'] token_df = pd.read_csv(token_data, header = 0) token_type = token_df['type']",
"as pd from sklearn.model_selection import train_test_split # Confirm the correct directory; break script",
"processed and unprocessed objects for further analysis raw_df = pd.read_csv(raw_data, header = 0)",
"data has been generated # If not prompt user to make it token_file_exists",
"= clean_df['posts'] # Split up data into training and testing datasets # To",
"appear to be in the correct directory,\\ you must be in the \\'myersBriggsNLPAnalysis\\'",
"not appear to be in the correct directory,\\ you must be in the",
"\\'data_generation.py\\' file and follow the prompts.') sys.exit(1) # Declare different processed and unprocessed",
"follow the prompts.') sys.exit(1) # Declare different processed and unprocessed objects for further",
"raw_type = raw_df['type'] raw_posts = raw_df['posts'] token_df = pd.read_csv(token_data, header = 0) token_type",
"# Split up data into training and testing datasets # To evaluate effectiveness",
"If not prompt user to make it token_file_exists = os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data)",
"used in the other scripts ''' # First check if the data has",
"from sklearn.model_selection import train_test_split # Confirm the correct directory; break script and prompt",
"data with hashtags, mentions, retweets, etc. - Cleaned tokenized data with stopwords removed",
"= raw_df['posts'] token_df = pd.read_csv(token_data, header = 0) token_type = token_df['type'] token_posts =",
"clean_df = pd.read_csv(clean_data, header = 0) clean_type = clean_df['type'] clean_posts = clean_df['posts'] #",
"= 0) clean_type = clean_df['type'] clean_posts = clean_df['posts'] # Split up data into",
"subset the data into various parts to be used in the other scripts",
"if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not appear to be in the correct directory,\\",
"etc. - Cleaned tokenized data with stopwords removed We will now subset the",
"raw_df['posts'] token_df = pd.read_csv(token_data, header = 0) token_type = token_df['type'] token_posts = token_df['posts']",
"run the \\'data_generation.py\\' file and follow the prompts.') sys.exit(1) # Declare different processed",
"= token_df['posts'] clean_df = pd.read_csv(clean_data, header = 0) clean_type = clean_df['type'] clean_posts =",
"np import pandas as pd from sklearn.model_selection import train_test_split # Confirm the correct",
"in the correct directory,\\ you must be in the \\'myersBriggsNLPAnalysis\\' directory\\ in order",
"directory,\\ you must be in the \\'myersBriggsNLPAnalysis\\' directory\\ in order to run these",
"pd from sklearn.model_selection import train_test_split # Confirm the correct directory; break script and",
"0.30, random_state = 42) X_train_clean, X_test_clean, y_train_clean, y_test_clean = train_test_split( clean_posts, clean_type, test_size",
"# Confirm the correct directory; break script and prompt user to move to",
"X_test_token, y_train_token, y_test_token = train_test_split( token_posts, token_type, test_size = 0.30, random_state = 42)",
"to correct directory otherwise filepath = os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not",
"Project can be found at: # https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110 ################################################################ ################## #",
"directory; break script and prompt user to move to correct directory otherwise filepath",
"sklearn.model_selection import train_test_split # Confirm the correct directory; break script and prompt user",
"By <NAME> # Project can be found at: # https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110",
"been generated.\\n', 'Please run the \\'data_generation.py\\' file and follow the prompts.') sys.exit(1) #",
"import numpy as np import pandas as pd from sklearn.model_selection import train_test_split #",
"Import packages ################## import sys, os import numpy as np import pandas as",
"has been generated # If not prompt user to make it token_file_exists =",
"of your location in the terminal.') sys.exit(1) raw_data = 'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv'",
"if not token_file_exists or not clean_file_exists: print('It looks like no processed data has",
"print('\\nYou do not appear to be in the correct directory,\\ you must be",
"or not clean_file_exists: print('It looks like no processed data has been generated.\\n', 'Please",
"no processed data has been generated.\\n', 'Please run the \\'data_generation.py\\' file and follow",
"################## # Import packages ################## import sys, os import numpy as np import",
"Raw, unfiltered data - Tokenized data with hashtags, mentions, retweets, etc. - Cleaned",
"<NAME> Personality Type Tweets Natural Language Processing # By <NAME> # Project can",
"# If not prompt user to make it token_file_exists = os.path.isfile(token_data) clean_file_exists =",
"train_test_split # Confirm the correct directory; break script and prompt user to move",
"correct directory; break script and prompt user to move to correct directory otherwise",
"https://www.inertia7.com/projects/109 & # https://www.inertia7.com/projects/110 ################################################################ ################## # Import packages ################## import sys, os",
"To evaluate effectiveness of model training X_train_token, X_test_token, y_train_token, y_test_token = train_test_split( token_posts,",
"you must be in the \\'myersBriggsNLPAnalysis\\' directory\\ in order to run these scripts.",
"the data into various parts to be used in the other scripts '''",
"to be in the correct directory,\\ you must be in the \\'myersBriggsNLPAnalysis\\' directory\\",
"scripts. Type \\'pwd\\' in the command line\\ if you are unsure of your",
"Type \\'pwd\\' in the command line\\ if you are unsure of your location",
"raw_data = 'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv' columns = np.array(['type', 'posts'])",
"will have various versions of our data: - Raw, unfiltered data - Tokenized",
"various parts to be used in the other scripts ''' # First check",
"order to run these scripts. Type \\'pwd\\' in the command line\\ if you",
"parts to be used in the other scripts ''' # First check if",
"it token_file_exists = os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data) if not token_file_exists or not clean_file_exists:",
"Tweets Natural Language Processing # By <NAME> # Project can be found at:",
"like no processed data has been generated.\\n', 'Please run the \\'data_generation.py\\' file and",
"pd.read_csv(token_data, header = 0) token_type = token_df['type'] token_posts = token_df['posts'] clean_df = pd.read_csv(clean_data,",
"training and testing datasets # To evaluate effectiveness of model training X_train_token, X_test_token,",
"''' Explanation ----------- Now we will have various versions of our data: -",
"we will have various versions of our data: - Raw, unfiltered data -",
"- Cleaned tokenized data with stopwords removed We will now subset the data",
"# <NAME> Personality Type Tweets Natural Language Processing # By <NAME> # Project",
"token_file_exists = os.path.isfile(token_data) clean_file_exists = os.path.isfile(clean_data) if not token_file_exists or not clean_file_exists: print('It",
"the \\'data_generation.py\\' file and follow the prompts.') sys.exit(1) # Declare different processed and",
"token_file_exists or not clean_file_exists: print('It looks like no processed data has been generated.\\n',",
"command line\\ if you are unsure of your location in the terminal.') sys.exit(1)",
"# To evaluate effectiveness of model training X_train_token, X_test_token, y_train_token, y_test_token = train_test_split(",
"user to move to correct directory otherwise filepath = os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'):",
"your location in the terminal.') sys.exit(1) raw_data = 'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv' clean_data",
"unprocessed objects for further analysis raw_df = pd.read_csv(raw_data, header = 0) raw_type =",
"token_df['posts'] clean_df = pd.read_csv(clean_data, header = 0) clean_type = clean_df['type'] clean_posts = clean_df['posts']",
"not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not appear to be in the correct directory,\\ you",
"= clean_df['type'] clean_posts = clean_df['posts'] # Split up data into training and testing",
"as np import pandas as pd from sklearn.model_selection import train_test_split # Confirm the",
"terminal.') sys.exit(1) raw_data = 'data/mbti_1.csv' token_data = 'data/mbti_tokenized.csv' clean_data = 'data/mbti_cleaned.csv' columns =",
"# By <NAME> # Project can be found at: # https://www.inertia7.com/projects/109 & #",
"the \\'myersBriggsNLPAnalysis\\' directory\\ in order to run these scripts. Type \\'pwd\\' in the",
"with stopwords removed We will now subset the data into various parts to",
"################## import sys, os import numpy as np import pandas as pd from",
"removed We will now subset the data into various parts to be used",
"in the command line\\ if you are unsure of your location in the",
"################################################## ''' Explanation ----------- Now we will have various versions of our data:",
"header = 0) raw_type = raw_df['type'] raw_posts = raw_df['posts'] token_df = pd.read_csv(token_data, header",
"Now we will have various versions of our data: - Raw, unfiltered data",
"retweets, etc. - Cleaned tokenized data with stopwords removed We will now subset",
"= os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not appear to be in the",
"# Make different versions of our data for analysis ################################################## ''' Explanation -----------",
"of model training X_train_token, X_test_token, y_train_token, y_test_token = train_test_split( token_posts, token_type, test_size =",
"################################################## # Make different versions of our data for analysis ################################################## ''' Explanation",
"= 'data/mbti_cleaned.csv' columns = np.array(['type', 'posts']) ################################################## # Make different versions of our",
"''' # First check if the data has been generated # If not",
"clean_type = clean_df['type'] clean_posts = clean_df['posts'] # Split up data into training and",
"versions of our data: - Raw, unfiltered data - Tokenized data with hashtags,",
"random_state = 42) X_train_clean, X_test_clean, y_train_clean, y_test_clean = train_test_split( clean_posts, clean_type, test_size =",
"do not appear to be in the correct directory,\\ you must be in",
"data for analysis ################################################## ''' Explanation ----------- Now we will have various versions",
"\\'pwd\\' in the command line\\ if you are unsure of your location in",
"now subset the data into various parts to be used in the other",
"header = 0) token_type = token_df['type'] token_posts = token_df['posts'] clean_df = pd.read_csv(clean_data, header",
"data into various parts to be used in the other scripts ''' #",
"with hashtags, mentions, retweets, etc. - Cleaned tokenized data with stopwords removed We",
"hashtags, mentions, retweets, etc. - Cleaned tokenized data with stopwords removed We will",
"os.getcwd() if not filepath.endswith('myersBriggsNLPAnalysis'): print('\\nYou do not appear to be in the correct",
"'posts']) ################################################## # Make different versions of our data for analysis ################################################## '''",
"# Import packages ################## import sys, os import numpy as np import pandas",
"the other scripts ''' # First check if the data has been generated",
"raw_posts = raw_df['posts'] token_df = pd.read_csv(token_data, header = 0) token_type = token_df['type'] token_posts",
"into training and testing datasets # To evaluate effectiveness of model training X_train_token,",
"= os.path.isfile(clean_data) if not token_file_exists or not clean_file_exists: print('It looks like no processed",
"the command line\\ if you are unsure of your location in the terminal.')",
"X_test_clean, y_train_clean, y_test_clean = train_test_split( clean_posts, clean_type, test_size = 0.30, random_state = 42)",
"# Declare different processed and unprocessed objects for further analysis raw_df = pd.read_csv(raw_data,",
"= 0.30, random_state = 42) X_train_clean, X_test_clean, y_train_clean, y_test_clean = train_test_split( clean_posts, clean_type,",
"data: - Raw, unfiltered data - Tokenized data with hashtags, mentions, retweets, etc.",
"of our data: - Raw, unfiltered data - Tokenized data with hashtags, mentions,"
] |
[
"k):>6}|{scm(i, k):>6}|{(i * k):>6}\") # gcd(a, b) * scm(a, b) = |a *",
"return a def gcd_recursive(a: int, b: int): return gcd_recursive(b, a % b) if",
"int: while True: r = a % b a = b b =",
"else a def scm(a: int, b: int) -> int: # gcd(a, b) *",
"def parse_args(): parser = argparse.ArgumentParser(description='find greatest common divisor') parser.add_argument('-a', '--a', type=int, required=True, help='number",
"= argparse.ArgumentParser(description='find greatest common divisor') parser.add_argument('-a', '--a', type=int, required=True, help='number 1') parser.add_argument('-b', '--b',",
"because of the call stack the recursive function is normally slower, but better",
"argparse from utils import time_func def gcd_iterative(a: int, b: int) -> int: while",
"for i in range(30, 40 + 1): for k in range(i, 40 +",
"b) if b else a def scm(a: int, b: int) -> int: #",
"* scm(a, b) = |a * b| return abs(a * b) // gcd_iterative(a,",
"gcd_iterative(a, b) def parse_args(): parser = argparse.ArgumentParser(description='find greatest common divisor') parser.add_argument('-a', '--a', type=int,",
"# not r break return a def gcd_recursive(a: int, b: int): return gcd_recursive(b,",
"if __name__ == '__main__': args = parse_args() print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative, args.a, args.b)}')",
"% b) if b else a def scm(a: int, b: int) -> int:",
"1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i * k):>6}\") # gcd(a, b) * scm(a, b) =",
"def gcd_recursive(a: int, b: int): return gcd_recursive(b, a % b) if b else",
"required=True, help='number 1') parser.add_argument('-b', '--b', type=int, required=True, help='number 2') return parser.parse_args() if __name__",
"return gcd_recursive(b, a % b) if b else a def scm(a: int, b:",
"40 + 1): for k in range(i, 40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i",
"def scm(a: int, b: int) -> int: # gcd(a, b) * scm(a, b)",
"+ 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i * k):>6}\") # gcd(a, b) * scm(a, b)",
"'--b', type=int, required=True, help='number 2') return parser.parse_args() if __name__ == '__main__': args =",
"required=True, help='number 2') return parser.parse_args() if __name__ == '__main__': args = parse_args() print(f'gcd_iterative({args.a},",
"print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a},",
"args.b)}') # because of the call stack the recursive function is normally slower,",
"{args.b}) = {time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a}, {args.b})",
"but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i in range(30, 40 + 1): for",
"the recursive function is normally slower, but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i",
"args.a, args.b)}') print(f'scm({args.a}, {args.b}) = {time_func(scm, args.a, args.b)}') # because of the call",
"int: # gcd(a, b) * scm(a, b) = |a * b| return abs(a",
"args.b)}') print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a}, {args.b}) = {time_func(scm, args.a, args.b)}')",
"k in range(i, 40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i * k):>6}\") # gcd(a,",
"b) * scm(a, b) = |a * b| return abs(a * b) //",
"parse_args(): parser = argparse.ArgumentParser(description='find greatest common divisor') parser.add_argument('-a', '--a', type=int, required=True, help='number 1')",
"gcd_recursive(a: int, b: int): return gcd_recursive(b, a % b) if b else a",
"r break return a def gcd_recursive(a: int, b: int): return gcd_recursive(b, a %",
"argparse.ArgumentParser(description='find greatest common divisor') parser.add_argument('-a', '--a', type=int, required=True, help='number 1') parser.add_argument('-b', '--b', type=int,",
"= {time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a}, {args.b}) = {time_func(scm, args.a, args.b)}') # because of",
"a % b a = b b = r if r == 0:",
"help='number 1') parser.add_argument('-b', '--b', type=int, required=True, help='number 2') return parser.parse_args() if __name__ ==",
"== 0: # not r break return a def gcd_recursive(a: int, b: int):",
"b = r if r == 0: # not r break return a",
"range(i, 40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i * k):>6}\") # gcd(a, b) *",
"import argparse from utils import time_func def gcd_iterative(a: int, b: int) -> int:",
"a = b b = r if r == 0: # not r",
"args.b)}') print(f'scm({args.a}, {args.b}) = {time_func(scm, args.a, args.b)}') # because of the call stack",
"stack the recursive function is normally slower, but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for",
"int, b: int): return gcd_recursive(b, a % b) if b else a def",
"parse_args() print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive, args.a, args.b)}')",
"if r == 0: # not r break return a def gcd_recursive(a: int,",
"{time_func(scm, args.a, args.b)}') # because of the call stack the recursive function is",
"0: # not r break return a def gcd_recursive(a: int, b: int): return",
"parser.parse_args() if __name__ == '__main__': args = parse_args() print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative, args.a,",
"-> int: while True: r = a % b a = b b",
"= b b = r if r == 0: # not r break",
"a def scm(a: int, b: int) -> int: # gcd(a, b) * scm(a,",
"1') parser.add_argument('-b', '--b', type=int, required=True, help='number 2') return parser.parse_args() if __name__ == '__main__':",
"{args.b}) = {time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a}, {args.b}) = {time_func(scm, args.a, args.b)}') # because",
"better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i in range(30, 40 + 1): for k",
"print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i in range(30, 40 + 1): for k in range(i,",
"common divisor') parser.add_argument('-a', '--a', type=int, required=True, help='number 1') parser.add_argument('-b', '--b', type=int, required=True, help='number",
"b) def parse_args(): parser = argparse.ArgumentParser(description='find greatest common divisor') parser.add_argument('-a', '--a', type=int, required=True,",
"while True: r = a % b a = b b = r",
"// gcd_iterative(a, b) def parse_args(): parser = argparse.ArgumentParser(description='find greatest common divisor') parser.add_argument('-a', '--a',",
"* b| return abs(a * b) // gcd_iterative(a, b) def parse_args(): parser =",
"b) // gcd_iterative(a, b) def parse_args(): parser = argparse.ArgumentParser(description='find greatest common divisor') parser.add_argument('-a',",
"normally slower, but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i in range(30, 40 +",
"gcd_recursive(b, a % b) if b else a def scm(a: int, b: int)",
"% b a = b b = r if r == 0: #",
"abs(a * b) // gcd_iterative(a, b) def parse_args(): parser = argparse.ArgumentParser(description='find greatest common",
"type=int, required=True, help='number 1') parser.add_argument('-b', '--b', type=int, required=True, help='number 2') return parser.parse_args() if",
"return parser.parse_args() if __name__ == '__main__': args = parse_args() print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative,",
"= parse_args() print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive, args.a,",
"in range(30, 40 + 1): for k in range(i, 40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i,",
"= {time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a}, {args.b}) =",
"<filename>e1/p1.py import argparse from utils import time_func def gcd_iterative(a: int, b: int) ->",
"|a * b| return abs(a * b) // gcd_iterative(a, b) def parse_args(): parser",
"recursive function is normally slower, but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i in",
"args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a}, {args.b}) = {time_func(scm, args.a,",
"help='number 2') return parser.parse_args() if __name__ == '__main__': args = parse_args() print(f'gcd_iterative({args.a}, {args.b})",
"args.a, args.b)}') # because of the call stack the recursive function is normally",
"import time_func def gcd_iterative(a: int, b: int) -> int: while True: r =",
"b else a def scm(a: int, b: int) -> int: # gcd(a, b)",
"a def gcd_recursive(a: int, b: int): return gcd_recursive(b, a % b) if b",
"for k in range(i, 40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i * k):>6}\") #",
"readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i in range(30, 40 + 1): for k in",
"break return a def gcd_recursive(a: int, b: int): return gcd_recursive(b, a % b)",
"{time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a}, {args.b}) = {time_func(scm,",
"int, b: int) -> int: # gcd(a, b) * scm(a, b) = |a",
"divisor') parser.add_argument('-a', '--a', type=int, required=True, help='number 1') parser.add_argument('-b', '--b', type=int, required=True, help='number 2')",
"call stack the recursive function is normally slower, but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\")",
"a % b) if b else a def scm(a: int, b: int) ->",
"-> int: # gcd(a, b) * scm(a, b) = |a * b| return",
"= |a * b| return abs(a * b) // gcd_iterative(a, b) def parse_args():",
"True: r = a % b a = b b = r if",
"r == 0: # not r break return a def gcd_recursive(a: int, b:",
"k):>6}|{(i * k):>6}\") # gcd(a, b) * scm(a, b) = |a * b|",
"scm(a: int, b: int) -> int: # gcd(a, b) * scm(a, b) =",
"= r if r == 0: # not r break return a def",
"{time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a}, {args.b}) = {time_func(scm, args.a, args.b)}') # because of the",
"# gcd(a, b) * scm(a, b) = |a * b| return abs(a *",
"not r break return a def gcd_recursive(a: int, b: int): return gcd_recursive(b, a",
"function is normally slower, but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i in range(30,",
"scm(a, b) = |a * b| return abs(a * b) // gcd_iterative(a, b)",
"# because of the call stack the recursive function is normally slower, but",
"= {time_func(scm, args.a, args.b)}') # because of the call stack the recursive function",
"print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive, args.a, args.b)}') print(f'scm({args.a}, {args.b}) = {time_func(scm, args.a, args.b)}') #",
"print(f\"{'':-^28}\") for i in range(30, 40 + 1): for k in range(i, 40",
"* b) // gcd_iterative(a, b) def parse_args(): parser = argparse.ArgumentParser(description='find greatest common divisor')",
"parser.add_argument('-b', '--b', type=int, required=True, help='number 2') return parser.parse_args() if __name__ == '__main__': args",
"in range(i, 40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i * k):>6}\") # gcd(a, b)",
"parser.add_argument('-a', '--a', type=int, required=True, help='number 1') parser.add_argument('-b', '--b', type=int, required=True, help='number 2') return",
"i in range(30, 40 + 1): for k in range(i, 40 + 1):",
"b: int) -> int: # gcd(a, b) * scm(a, b) = |a *",
"'__main__': args = parse_args() print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b}) =",
"args = parse_args() print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b}) = {time_func(gcd_recursive,",
"int) -> int: # gcd(a, b) * scm(a, b) = |a * b|",
"the call stack the recursive function is normally slower, but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\")",
"utils import time_func def gcd_iterative(a: int, b: int) -> int: while True: r",
"2') return parser.parse_args() if __name__ == '__main__': args = parse_args() print(f'gcd_iterative({args.a}, {args.b}) =",
"b: int) -> int: while True: r = a % b a =",
"def gcd_iterative(a: int, b: int) -> int: while True: r = a %",
"time_func def gcd_iterative(a: int, b: int) -> int: while True: r = a",
"b) = |a * b| return abs(a * b) // gcd_iterative(a, b) def",
"from utils import time_func def gcd_iterative(a: int, b: int) -> int: while True:",
"int) -> int: while True: r = a % b a = b",
"b a = b b = r if r == 0: # not",
"r if r == 0: # not r break return a def gcd_recursive(a:",
"print(f'scm({args.a}, {args.b}) = {time_func(scm, args.a, args.b)}') # because of the call stack the",
"range(30, 40 + 1): for k in range(i, 40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i,",
"int): return gcd_recursive(b, a % b) if b else a def scm(a: int,",
"b| return abs(a * b) // gcd_iterative(a, b) def parse_args(): parser = argparse.ArgumentParser(description='find",
"gcd_iterative(a: int, b: int) -> int: while True: r = a % b",
"parser = argparse.ArgumentParser(description='find greatest common divisor') parser.add_argument('-a', '--a', type=int, required=True, help='number 1') parser.add_argument('-b',",
"+ 1): for k in range(i, 40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i *",
"'--a', type=int, required=True, help='number 1') parser.add_argument('-b', '--b', type=int, required=True, help='number 2') return parser.parse_args()",
"return abs(a * b) // gcd_iterative(a, b) def parse_args(): parser = argparse.ArgumentParser(description='find greatest",
"b b = r if r == 0: # not r break return",
"gcd(a, b) * scm(a, b) = |a * b| return abs(a * b)",
"print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i * k):>6}\") # gcd(a, b) * scm(a, b) = |a",
"type=int, required=True, help='number 2') return parser.parse_args() if __name__ == '__main__': args = parse_args()",
"of the call stack the recursive function is normally slower, but better readable",
"__name__ == '__main__': args = parse_args() print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a},",
"b: int): return gcd_recursive(b, a % b) if b else a def scm(a:",
"greatest common divisor') parser.add_argument('-a', '--a', type=int, required=True, help='number 1') parser.add_argument('-b', '--b', type=int, required=True,",
"1): for k in range(i, 40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i * k):>6}\")",
"40 + 1): print(f\"{i:>3}|{k:>3}|{gcd_iterative(i, k):>6}|{scm(i, k):>6}|{(i * k):>6}\") # gcd(a, b) * scm(a,",
"{args.b}) = {time_func(scm, args.a, args.b)}') # because of the call stack the recursive",
"r = a % b a = b b = r if r",
"if b else a def scm(a: int, b: int) -> int: # gcd(a,",
"is normally slower, but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i in range(30, 40",
"= a % b a = b b = r if r ==",
"slower, but better readable print(f\"{'a':^3}|{'b':^3}|{'gcd':^6}|{'kcm':^6}|{'a*b':^6}\") print(f\"{'':-^28}\") for i in range(30, 40 + 1):",
"int, b: int) -> int: while True: r = a % b a",
"== '__main__': args = parse_args() print(f'gcd_iterative({args.a}, {args.b}) = {time_func(gcd_iterative, args.a, args.b)}') print(f'gcd_recursive({args.a}, {args.b})"
] |
[
"= [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================')",
"[graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] _, loss_val, train_summary, step = sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step)",
"accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================') print('the step {0}",
"-*- coding: utf-8 -*- import os import time import tensorflow as tf from",
"sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/val') # restore model if FLAGS.restore: ckpt =",
"time.time() feed_dict = {graph['images']: x_batch, graph['labels']: y_batch, graph['keep_prob']: 0.8, graph['is_training']: True} train_opts =",
"= time.time() print(\"the step {0} takes {1} loss {2}\".format(step, end_time - start_time, loss_val))",
"[graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================') print('the",
"# save stage if step % FLAGS.save_steps == 0 and step > FLAGS.min_save_steps:",
"x_batch, graph['labels']: y_batch, graph['keep_prob']: 0.8, graph['is_training']: True} train_opts = [graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']]",
"_, loss_val, train_summary, step = sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time = time.time() print(\"the",
"(x_batch, y_batch) in enumerate(train_data_iterator()): start_time = time.time() feed_dict = {graph['images']: x_batch, graph['labels']: y_batch,",
"= sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================') print('the step {0} test accuracy:",
"y_batch) in enumerate(train_data_iterator()): start_time = time.time() feed_dict = {graph['images']: x_batch, graph['labels']: y_batch, graph['keep_prob']:",
"train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/val') # restore",
"# eval stage if step % FLAGS.eval_steps == 0: x_batch_test, y_batch_test = test_data_helper(128)",
"batch=======================') # save stage if step % FLAGS.save_steps == 0 and step >",
"coding: utf-8 -*- import os import time import tensorflow as tf from config",
"0: x_batch_test, y_batch_test = test_data_helper(128) feed_dict = {graph['images']: x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']: 1.0,",
"end_time = time.time() print(\"the step {0} takes {1} loss {2}\".format(step, end_time - start_time,",
"= [graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] _, loss_val, train_summary, step = sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary,",
"# initialization graph = build_graph(top_k=1) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi thread coord",
"coord.should_stop(): for step, (x_batch, y_batch) in enumerate(train_data_iterator()): start_time = time.time() feed_dict = {graph['images']:",
"loss_val, train_summary, step = sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time = time.time() print(\"the step",
"{0} takes {1} loss {2}\".format(step, end_time - start_time, loss_val)) # eval stage if",
"feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time = time.time() print(\"the step {0} takes {1} loss {2}\".format(step,",
"if step % FLAGS.eval_steps == 0: x_batch_test, y_batch_test = test_data_helper(128) feed_dict = {graph['images']:",
"step > FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir,",
"= tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/val') # restore model",
"tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess, ckpt) print(\"restore from the checkpoint {}\".format(ckpt)) # training begins",
"x_batch_test, y_batch_test = test_data_helper(128) feed_dict = {graph['images']: x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']: 1.0, graph['is_training']:",
"coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) # log writer train_writer = tf.summary.FileWriter(FLAGS.log_dir",
"tf.summary.FileWriter(FLAGS.log_dir + '/val') # restore model if FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt:",
"sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time = time.time() print(\"the step {0} takes {1} loss",
"% FLAGS.save_steps == 0 and step > FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except",
"+ '/val') # restore model if FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess,",
"{2}\".format(step, end_time - start_time, loss_val)) # eval stage if step % FLAGS.eval_steps ==",
"a batch=======================') print('the step {0} test accuracy: {1}'.format(step, accuracy_test)) print('===============Eval a batch=======================') #",
"print('the step {0} test accuracy: {1}'.format(step, accuracy_test)) print('===============Eval a batch=======================') # save stage",
"while not coord.should_stop(): for step, (x_batch, y_batch) in enumerate(train_data_iterator()): start_time = time.time() feed_dict",
"0 and step > FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train Finished================')",
"test accuracy: {1}'.format(step, accuracy_test)) print('===============Eval a batch=======================') # save stage if step %",
"start_time, loss_val)) # eval stage if step % FLAGS.eval_steps == 0: x_batch_test, y_batch_test",
"the checkpoint {}\".format(ckpt)) # training begins try: while not coord.should_stop(): for step, (x_batch,",
"x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']: 1.0, graph['is_training']: False} test_opts = [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary",
"step % FLAGS.save_steps == 0 and step > FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step'])",
"from preprocess import train_data_iterator, test_data_helper def train(): with tf.Session() as sess: # initialization",
"print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) finally: coord.request_stop() coord.join(threads) if __name__ == '__main__':",
"train_data_iterator, test_data_helper def train(): with tf.Session() as sess: # initialization graph = build_graph(top_k=1)",
"saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi thread coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess,",
"start_time = time.time() feed_dict = {graph['images']: x_batch, graph['labels']: y_batch, graph['keep_prob']: 0.8, graph['is_training']: True}",
"step % FLAGS.eval_steps == 0: x_batch_test, y_batch_test = test_data_helper(128) feed_dict = {graph['images']: x_batch_test,",
"FLAGS.eval_steps == 0: x_batch_test, y_batch_test = test_data_helper(128) feed_dict = {graph['images']: x_batch_test, graph['labels']: y_batch_test,",
"graph['is_training']: False} test_opts = [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step)",
"graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================') print('the step",
"os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) finally: coord.request_stop()",
"test_data_helper(128) feed_dict = {graph['images']: x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']: 1.0, graph['is_training']: False} test_opts =",
"{1} loss {2}\".format(step, end_time - start_time, loss_val)) # eval stage if step %",
"if ckpt: saver.restore(sess, ckpt) print(\"restore from the checkpoint {}\".format(ckpt)) # training begins try:",
"tensorflow as tf from config import FLAGS from model import build_graph from preprocess",
"= time.time() feed_dict = {graph['images']: x_batch, graph['labels']: y_batch, graph['keep_prob']: 0.8, graph['is_training']: True} train_opts",
"test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================') print('the step {0} test accuracy: {1}'.format(step, accuracy_test)) print('===============Eval",
"= test_data_helper(128) feed_dict = {graph['images']: x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']: 1.0, graph['is_training']: False} test_opts",
"import build_graph from preprocess import train_data_iterator, test_data_helper def train(): with tf.Session() as sess:",
"-*- import os import time import tensorflow as tf from config import FLAGS",
"sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================') print('the step {0} test accuracy: {1}'.format(step,",
"== 0: x_batch_test, y_batch_test = test_data_helper(128) feed_dict = {graph['images']: x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']:",
"graph['keep_prob']: 0.8, graph['is_training']: True} train_opts = [graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] _, loss_val, train_summary,",
"initialization graph = build_graph(top_k=1) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi thread coord =",
"as tf from config import FLAGS from model import build_graph from preprocess import",
"utf-8 -*- import os import time import tensorflow as tf from config import",
"build_graph from preprocess import train_data_iterator, test_data_helper def train(): with tf.Session() as sess: #",
"sess: # initialization graph = build_graph(top_k=1) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi thread",
"multi thread coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) # log writer train_writer",
"in enumerate(train_data_iterator()): start_time = time.time() feed_dict = {graph['images']: x_batch, graph['labels']: y_batch, graph['keep_prob']: 0.8,",
"graph['labels']: y_batch, graph['keep_prob']: 0.8, graph['is_training']: True} train_opts = [graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] _,",
"coord=coord) # log writer train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir",
"model import build_graph from preprocess import train_data_iterator, test_data_helper def train(): with tf.Session() as",
"ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess, ckpt) print(\"restore from the checkpoint {}\".format(ckpt)) #",
"a batch=======================') # save stage if step % FLAGS.save_steps == 0 and step",
"training begins try: while not coord.should_stop(): for step, (x_batch, y_batch) in enumerate(train_data_iterator()): start_time",
"time import tensorflow as tf from config import FLAGS from model import build_graph",
"step {0} takes {1} loss {2}\".format(step, end_time - start_time, loss_val)) # eval stage",
"from model import build_graph from preprocess import train_data_iterator, test_data_helper def train(): with tf.Session()",
"= build_graph(top_k=1) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi thread coord = tf.train.Coordinator() threads",
"and step > FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess,",
"{}\".format(ckpt)) # training begins try: while not coord.should_stop(): for step, (x_batch, y_batch) in",
"0.8, graph['is_training']: True} train_opts = [graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] _, loss_val, train_summary, step",
"graph['merged_summary_op'], graph['global_step']] _, loss_val, train_summary, step = sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time =",
"except tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) finally: coord.request_stop() coord.join(threads) if __name__",
"# -*- coding: utf-8 -*- import os import time import tensorflow as tf",
"FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step'])",
"os import time import tensorflow as tf from config import FLAGS from model",
"batch=======================') print('the step {0} test accuracy: {1}'.format(step, accuracy_test)) print('===============Eval a batch=======================') # save",
"train_summary, step = sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time = time.time() print(\"the step {0}",
"thread coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) # log writer train_writer =",
"build_graph(top_k=1) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi thread coord = tf.train.Coordinator() threads =",
"threads = tf.train.start_queue_runners(sess=sess, coord=coord) # log writer train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph)",
"step) end_time = time.time() print(\"the step {0} takes {1} loss {2}\".format(step, end_time -",
"graph['keep_prob']: 1.0, graph['is_training']: False} test_opts = [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict)",
"save stage if step % FLAGS.save_steps == 0 and step > FLAGS.min_save_steps: saver.save(sess,",
"FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) finally: coord.request_stop() coord.join(threads)",
"writer train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/val') #",
"# multi thread coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) # log writer",
"feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================') print('the step {0} test accuracy: {1}'.format(step, accuracy_test))",
"= tf.train.start_queue_runners(sess=sess, coord=coord) # log writer train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) test_writer",
"1.0, graph['is_training']: False} test_opts = [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary,",
"ckpt) print(\"restore from the checkpoint {}\".format(ckpt)) # training begins try: while not coord.should_stop():",
"config import FLAGS from model import build_graph from preprocess import train_data_iterator, test_data_helper def",
"{1}'.format(step, accuracy_test)) print('===============Eval a batch=======================') # save stage if step % FLAGS.save_steps ==",
"accuracy_test)) print('===============Eval a batch=======================') # save stage if step % FLAGS.save_steps == 0",
"accuracy: {1}'.format(step, accuracy_test)) print('===============Eval a batch=======================') # save stage if step % FLAGS.save_steps",
"global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) finally: coord.request_stop() coord.join(threads) if",
"= tf.summary.FileWriter(FLAGS.log_dir + '/val') # restore model if FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if",
"print(\"restore from the checkpoint {}\".format(ckpt)) # training begins try: while not coord.should_stop(): for",
"step = sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time = time.time() print(\"the step {0} takes",
"feed_dict = {graph['images']: x_batch, graph['labels']: y_batch, graph['keep_prob']: 0.8, graph['is_training']: True} train_opts = [graph['train_op'],",
"test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a batch=======================') print('the step {0} test",
"begins try: while not coord.should_stop(): for step, (x_batch, y_batch) in enumerate(train_data_iterator()): start_time =",
"- start_time, loss_val)) # eval stage if step % FLAGS.eval_steps == 0: x_batch_test,",
"checkpoint {}\".format(ckpt)) # training begins try: while not coord.should_stop(): for step, (x_batch, y_batch)",
"from config import FLAGS from model import build_graph from preprocess import train_data_iterator, test_data_helper",
"{0} test accuracy: {1}'.format(step, accuracy_test)) print('===============Eval a batch=======================') # save stage if step",
"tf.Session() as sess: # initialization graph = build_graph(top_k=1) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) #",
"print('===============Eval a batch=======================') # save stage if step % FLAGS.save_steps == 0 and",
"# training begins try: while not coord.should_stop(): for step, (x_batch, y_batch) in enumerate(train_data_iterator()):",
"y_batch, graph['keep_prob']: 0.8, graph['is_training']: True} train_opts = [graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] _, loss_val,",
"tf from config import FLAGS from model import build_graph from preprocess import train_data_iterator,",
"restore model if FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess, ckpt) print(\"restore from",
"import tensorflow as tf from config import FLAGS from model import build_graph from",
"train_writer.add_summary(train_summary, step) end_time = time.time() print(\"the step {0} takes {1} loss {2}\".format(step, end_time",
"with tf.Session() as sess: # initialization graph = build_graph(top_k=1) saver = tf.train.Saver() sess.run(tf.global_variables_initializer())",
"tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi thread coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) #",
"preprocess import train_data_iterator, test_data_helper def train(): with tf.Session() as sess: # initialization graph",
"import train_data_iterator, test_data_helper def train(): with tf.Session() as sess: # initialization graph =",
"sess.run(tf.global_variables_initializer()) # multi thread coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) # log",
"graph = build_graph(top_k=1) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi thread coord = tf.train.Coordinator()",
"% FLAGS.eval_steps == 0: x_batch_test, y_batch_test = test_data_helper(128) feed_dict = {graph['images']: x_batch_test, graph['labels']:",
"y_batch_test = test_data_helper(128) feed_dict = {graph['images']: x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']: 1.0, graph['is_training']: False}",
"log writer train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/val')",
"test_opts = [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval a",
"as sess: # initialization graph = build_graph(top_k=1) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi",
"'/train', sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/val') # restore model if FLAGS.restore: ckpt",
"= {graph['images']: x_batch, graph['labels']: y_batch, graph['keep_prob']: 0.8, graph['is_training']: True} train_opts = [graph['train_op'], graph['loss'],",
"graph['global_step']] _, loss_val, train_summary, step = sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time = time.time()",
"def train(): with tf.Session() as sess: # initialization graph = build_graph(top_k=1) saver =",
"# log writer train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir +",
"= {graph['images']: x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']: 1.0, graph['is_training']: False} test_opts = [graph['accuracy'], graph['merged_summary_op']]",
"print(\"the step {0} takes {1} loss {2}\".format(step, end_time - start_time, loss_val)) # eval",
"import time import tensorflow as tf from config import FLAGS from model import",
"eval stage if step % FLAGS.eval_steps == 0: x_batch_test, y_batch_test = test_data_helper(128) feed_dict",
"tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/val') # restore model if",
"# restore model if FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess, ckpt) print(\"restore",
"= tf.train.Saver() sess.run(tf.global_variables_initializer()) # multi thread coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord)",
"FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess, ckpt) print(\"restore from the checkpoint {}\".format(ckpt))",
"= sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time = time.time() print(\"the step {0} takes {1}",
"train_opts = [graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] _, loss_val, train_summary, step = sess.run(train_opts, feed_dict=feed_dict)",
"time.time() print(\"the step {0} takes {1} loss {2}\".format(step, end_time - start_time, loss_val)) #",
"saver.restore(sess, ckpt) print(\"restore from the checkpoint {}\".format(ckpt)) # training begins try: while not",
"model if FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess, ckpt) print(\"restore from the",
"FLAGS from model import build_graph from preprocess import train_data_iterator, test_data_helper def train(): with",
"enumerate(train_data_iterator()): start_time = time.time() feed_dict = {graph['images']: x_batch, graph['labels']: y_batch, graph['keep_prob']: 0.8, graph['is_training']:",
"{graph['images']: x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']: 1.0, graph['is_training']: False} test_opts = [graph['accuracy'], graph['merged_summary_op']] accuracy_test,",
"step, (x_batch, y_batch) in enumerate(train_data_iterator()): start_time = time.time() feed_dict = {graph['images']: x_batch, graph['labels']:",
"stage if step % FLAGS.save_steps == 0 and step > FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir,",
"loss {2}\".format(step, end_time - start_time, loss_val)) # eval stage if step % FLAGS.eval_steps",
"Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) finally: coord.request_stop() coord.join(threads) if __name__ == '__main__': train()",
"saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) finally:",
"not coord.should_stop(): for step, (x_batch, y_batch) in enumerate(train_data_iterator()): start_time = time.time() feed_dict =",
"== 0 and step > FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train",
"stage if step % FLAGS.eval_steps == 0: x_batch_test, y_batch_test = test_data_helper(128) feed_dict =",
"= tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) # log writer train_writer = tf.summary.FileWriter(FLAGS.log_dir +",
"test_data_helper def train(): with tf.Session() as sess: # initialization graph = build_graph(top_k=1) saver",
"y_batch_test, graph['keep_prob']: 1.0, graph['is_training']: False} test_opts = [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts,",
"step) print('===============Eval a batch=======================') print('the step {0} test accuracy: {1}'.format(step, accuracy_test)) print('===============Eval a",
"end_time - start_time, loss_val)) # eval stage if step % FLAGS.eval_steps == 0:",
"try: while not coord.should_stop(): for step, (x_batch, y_batch) in enumerate(train_data_iterator()): start_time = time.time()",
"tf.train.start_queue_runners(sess=sess, coord=coord) # log writer train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) test_writer =",
"import os import time import tensorflow as tf from config import FLAGS from",
"= tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess, ckpt) print(\"restore from the checkpoint {}\".format(ckpt)) # training",
"print('===============Eval a batch=======================') print('the step {0} test accuracy: {1}'.format(step, accuracy_test)) print('===============Eval a batch=======================')",
"FLAGS.save_steps == 0 and step > FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError:",
"ckpt: saver.restore(sess, ckpt) print(\"restore from the checkpoint {}\".format(ckpt)) # training begins try: while",
"> FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) except tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name),",
"loss_val)) # eval stage if step % FLAGS.eval_steps == 0: x_batch_test, y_batch_test =",
"import FLAGS from model import build_graph from preprocess import train_data_iterator, test_data_helper def train():",
"if FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess, ckpt) print(\"restore from the checkpoint",
"graph['loss'], graph['merged_summary_op'], graph['global_step']] _, loss_val, train_summary, step = sess.run(train_opts, feed_dict=feed_dict) train_writer.add_summary(train_summary, step) end_time",
"takes {1} loss {2}\".format(step, end_time - start_time, loss_val)) # eval stage if step",
"graph['labels']: y_batch_test, graph['keep_prob']: 1.0, graph['is_training']: False} test_opts = [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary =",
"'/val') # restore model if FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) if ckpt: saver.restore(sess, ckpt)",
"step {0} test accuracy: {1}'.format(step, accuracy_test)) print('===============Eval a batch=======================') # save stage if",
"tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) # log writer train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train',",
"for step, (x_batch, y_batch) in enumerate(train_data_iterator()): start_time = time.time() feed_dict = {graph['images']: x_batch,",
"True} train_opts = [graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] _, loss_val, train_summary, step = sess.run(train_opts,",
"if step % FLAGS.save_steps == 0 and step > FLAGS.min_save_steps: saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name),",
"train(): with tf.Session() as sess: # initialization graph = build_graph(top_k=1) saver = tf.train.Saver()",
"from the checkpoint {}\".format(ckpt)) # training begins try: while not coord.should_stop(): for step,",
"{graph['images']: x_batch, graph['labels']: y_batch, graph['keep_prob']: 0.8, graph['is_training']: True} train_opts = [graph['train_op'], graph['loss'], graph['merged_summary_op'],",
"graph['is_training']: True} train_opts = [graph['train_op'], graph['loss'], graph['merged_summary_op'], graph['global_step']] _, loss_val, train_summary, step =",
"False} test_opts = [graph['accuracy'], graph['merged_summary_op']] accuracy_test, test_summary = sess.run(test_opts, feed_dict=feed_dict) test_writer.add_summary(test_summary, step) print('===============Eval",
"tf.errors.OutOfRangeError: print('==================Train Finished================') saver.save(sess, os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name), global_step=graph['global_step']) finally: coord.request_stop() coord.join(threads) if __name__ ==",
"+ '/train', sess.graph) test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/val') # restore model if FLAGS.restore:",
"feed_dict = {graph['images']: x_batch_test, graph['labels']: y_batch_test, graph['keep_prob']: 1.0, graph['is_training']: False} test_opts = [graph['accuracy'],",
"test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/val') # restore model if FLAGS.restore: ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)"
] |
[
"huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes)",
"ad minim veniam, quis nostrud exercitation \" b\"ullamco laboris nisi ut aliquip ex",
"deserunt \" b\"mollit anim id est laborum.\") lorem_codes = { \" \": \"001\",",
"\"L\": \"11111011\", \"U\": \"11111010\", \"a\": \"0111\", \"b\": \"1111100\", \"c\": \"01001\", \"d\": \"00011\", \"e\":",
"\"10010111\", \"i\": \"110\", \"l\": \"1110\", \"m\": \"01000\", \"n\": \"1010\", \"o\": \"0110\", \"p\": \"11110\",",
"{chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_tree_from_binary(): tree",
"\"q\": \"100111\", \"r\": \"1011\", \"s\": \"00010\", \"t\": \"0101\", \"u\": \"1000\", \"v\": \"1001010\", \"x\":",
"\"0101\", \"u\": \"1000\", \"v\": \"1001010\", \"x\": \"1001001\" } lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\")",
"symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree) codes",
"\"00010\", \"t\": \"0101\", \"u\": \"1000\", \"v\": \"1001010\", \"x\": \"1001001\" } lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\"",
"} lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\"",
"= huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes ==",
"\"1011\", \"s\": \"00010\", \"t\": \"0101\", \"u\": \"1000\", \"v\": \"1001010\", \"x\": \"1001001\" } lorem_tree",
"\"1110\", \"m\": \"01000\", \"n\": \"1010\", \"o\": \"0110\", \"p\": \"11110\", \"q\": \"100111\", \"r\": \"1011\",",
"{chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_compression(): compressed",
"test_tree_from_data(): tree = huffman.Node.from_data(simple) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()}",
"\"1001010\", \"x\": \"1001001\" } lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\"",
"code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_compression(): compressed =",
"eiusmod tempor incididunt ut labore et dolore magna \" b\"aliqua. Ut enim ad",
"data = huffman.decompress(lorem_compressed) assert(data == lorem) def test_both(): compressed = huffman.compress(simple) data =",
"huffman.decompress(compressed) assert(data == simple) compressed = huffman.compress(lorem) data = huffman.decompress(compressed) assert(data == lorem)",
"huffman.decompress(lorem_compressed) assert(data == lorem) def test_both(): compressed = huffman.compress(simple) data = huffman.decompress(compressed) assert(data",
"voluptate velit esse cillum \" b\"dolore eu fugiat nulla pariatur. Excepteur sint occaecat",
"tree = huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes",
"velit esse cillum \" b\"dolore eu fugiat nulla pariatur. Excepteur sint occaecat \"",
"assert(codes == lorem_codes) def test_compression(): compressed = huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed) compressed =",
"code in tree.codes().items()} assert(codes == lorem_codes) def test_compression(): compressed = huffman.compress(simple) assert(bitstring.Bits(compressed) ==",
"dolore magna \" b\"aliqua. Ut enim ad minim veniam, quis nostrud exercitation \"",
"ut labore et dolore magna \" b\"aliqua. Ut enim ad minim veniam, quis",
"\"x\": \"1001001\" } lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\"",
"from compression import huffman simple = b\"122333\" simple_codes = { \"1\": \"11\", \"2\":",
"bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data(): tree =",
"test_decompression(): data = huffman.decompress(simple_compressed) assert(data == simple) data = huffman.decompress(lorem_compressed) assert(data == lorem)",
"\"11111010\", \"a\": \"0111\", \"b\": \"1111100\", \"c\": \"01001\", \"d\": \"00011\", \"e\": \"0000\", \"f\": \"1001101\",",
"} simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem ipsum dolor sit",
"veniam, quis nostrud exercitation \" b\"ullamco laboris nisi ut aliquip ex ea commodo",
"\"110\", \"l\": \"1110\", \"m\": \"01000\", \"n\": \"1010\", \"o\": \"0110\", \"p\": \"11110\", \"q\": \"100111\",",
"\" b\"mollit anim id est laborum.\") lorem_codes = { \" \": \"001\", \",\":",
"\": \"001\", \",\": \"1001000\", \".\": \"111111\", \"D\": \"100101101\", \"E\": \"100101100\", \"L\": \"11111011\", \"U\":",
"\",\": \"1001000\", \".\": \"111111\", \"D\": \"100101101\", \"E\": \"100101100\", \"L\": \"11111011\", \"U\": \"11111010\", \"a\":",
"huffman.decompress(simple_compressed) assert(data == simple) data = huffman.decompress(lorem_compressed) assert(data == lorem) def test_both(): compressed",
"== lorem) def test_both(): compressed = huffman.compress(simple) data = huffman.decompress(compressed) assert(data == simple)",
"assert(codes == lorem_codes) def test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for",
"\"r\": \"1011\", \"s\": \"00010\", \"t\": \"0101\", \"u\": \"1000\", \"v\": \"1001010\", \"x\": \"1001001\" }",
"qui officia deserunt \" b\"mollit anim id est laborum.\") lorem_codes = { \"",
"= huffman.Node.from_data(simple) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes ==",
"aliquip ex ea commodo consequat. Duis \" b\"aute irure dolor in reprehenderit in",
"\"1001100\", \"h\": \"10010111\", \"i\": \"110\", \"l\": \"1110\", \"m\": \"01000\", \"n\": \"1010\", \"o\": \"0110\",",
"pariatur. Excepteur sint occaecat \" b\"cupidatat non proident, sunt in culpa qui officia",
"nisi ut aliquip ex ea commodo consequat. Duis \" b\"aute irure dolor in",
"lorem_codes) def test_compression(): compressed = huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed) compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed)",
"test_both(): compressed = huffman.compress(simple) data = huffman.decompress(compressed) assert(data == simple) compressed = huffman.compress(lorem)",
"\" b\"elit, sed do eiusmod tempor incididunt ut labore et dolore magna \"",
"code in tree.codes().items()} assert(codes == lorem_codes) def test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree) codes =",
"culpa qui officia deserunt \" b\"mollit anim id est laborum.\") lorem_codes = {",
"\"100101101\", \"E\": \"100101100\", \"L\": \"11111011\", \"U\": \"11111010\", \"a\": \"0111\", \"b\": \"1111100\", \"c\": \"01001\",",
"\"e\": \"0000\", \"f\": \"1001101\", \"g\": \"1001100\", \"h\": \"10010111\", \"i\": \"110\", \"l\": \"1110\", \"m\":",
"compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed) def test_decompression(): data = huffman.decompress(simple_compressed) assert(data ==",
"huffman.Node.from_data(lorem) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes)",
"symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_compression(): compressed = huffman.compress(simple) assert(bitstring.Bits(compressed)",
"in tree.codes().items()} assert(codes == lorem_codes) def test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree) codes = {chr(symbol):",
"def test_compression(): compressed = huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed) compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed) ==",
"= huffman.compress(simple) data = huffman.decompress(compressed) assert(data == simple) compressed = huffman.compress(lorem) data =",
"= huffman.Node.from_binary(simple_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes ==",
"non proident, sunt in culpa qui officia deserunt \" b\"mollit anim id est",
"\" b\"ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis \" b\"aute",
"dolor in reprehenderit in voluptate velit esse cillum \" b\"dolore eu fugiat nulla",
"codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes) def",
"= {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_compression():",
"== simple) data = huffman.decompress(lorem_compressed) assert(data == lorem) def test_both(): compressed = huffman.compress(simple)",
"= bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem ipsum dolor sit amet, consectetur adipisicing \" b\"elit,",
"\"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data(): tree = huffman.Node.from_data(simple)",
"compression import huffman simple = b\"122333\" simple_codes = { \"1\": \"11\", \"2\": \"10\",",
"minim veniam, quis nostrud exercitation \" b\"ullamco laboris nisi ut aliquip ex ea",
"\"p\": \"11110\", \"q\": \"100111\", \"r\": \"1011\", \"s\": \"00010\", \"t\": \"0101\", \"u\": \"1000\", \"v\":",
"(b\"Lorem ipsum dolor sit amet, consectetur adipisicing \" b\"elit, sed do eiusmod tempor",
"= {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_tree_from_binary():",
"code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_tree_from_binary(): tree =",
"huffman.Node.from_binary(simple_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == simple_codes)",
"amet, consectetur adipisicing \" b\"elit, sed do eiusmod tempor incididunt ut labore et",
"\"n\": \"1010\", \"o\": \"0110\", \"p\": \"11110\", \"q\": \"100111\", \"r\": \"1011\", \"s\": \"00010\", \"t\":",
"\"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data(): tree = huffman.Node.from_data(simple) codes",
"def test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in",
"def test_tree_from_data(): tree = huffman.Node.from_data(simple) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in",
"huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed) def test_decompression(): data = huffman.decompress(simple_compressed) assert(data == simple) data",
"in tree.codes().items()} assert(codes == lorem_codes) def test_compression(): compressed = huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed)",
"\"i\": \"110\", \"l\": \"1110\", \"m\": \"01000\", \"n\": \"1010\", \"o\": \"0110\", \"p\": \"11110\", \"q\":",
"= { \"1\": \"11\", \"2\": \"10\", \"3\": \"0\" } simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed",
"b\"dolore eu fugiat nulla pariatur. Excepteur sint occaecat \" b\"cupidatat non proident, sunt",
"simple_codes) tree = huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()}",
"\"1\": \"11\", \"2\": \"10\", \"3\": \"0\" } simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\")",
"bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem ipsum dolor sit amet, consectetur adipisicing \" b\"elit, sed",
"{ \"1\": \"11\", \"2\": \"10\", \"3\": \"0\" } simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed =",
"anim id est laborum.\") lorem_codes = { \" \": \"001\", \",\": \"1001000\", \".\":",
"\"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data(): tree = huffman.Node.from_data(simple) codes = {chr(symbol):",
"lorem = (b\"Lorem ipsum dolor sit amet, consectetur adipisicing \" b\"elit, sed do",
"\"l\": \"1110\", \"m\": \"01000\", \"n\": \"1010\", \"o\": \"0110\", \"p\": \"11110\", \"q\": \"100111\", \"r\":",
"code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_data(lorem) codes",
"= huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed) compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed) def test_decompression():",
"code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_data(lorem) codes = {chr(symbol): code.unpack(\"bin\")[0]",
"for symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree)",
"simple) data = huffman.decompress(lorem_compressed) assert(data == lorem) def test_both(): compressed = huffman.compress(simple) data",
"\"0111\", \"b\": \"1111100\", \"c\": \"01001\", \"d\": \"00011\", \"e\": \"0000\", \"f\": \"1001101\", \"g\": \"1001100\",",
"huffman.Node.from_data(simple) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == simple_codes)",
"in reprehenderit in voluptate velit esse cillum \" b\"dolore eu fugiat nulla pariatur.",
"lorem_codes) def test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code",
"in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for",
"\"3\": \"0\" } simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem ipsum",
"lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\"",
"== lorem_codes) def test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol,",
"\"h\": \"10010111\", \"i\": \"110\", \"l\": \"1110\", \"m\": \"01000\", \"n\": \"1010\", \"o\": \"0110\", \"p\":",
"python3 import bitstring from compression import huffman simple = b\"122333\" simple_codes = {",
"test_compression(): compressed = huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed) compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed)",
"consectetur adipisicing \" b\"elit, sed do eiusmod tempor incididunt ut labore et dolore",
"enim ad minim veniam, quis nostrud exercitation \" b\"ullamco laboris nisi ut aliquip",
"\"01001\", \"d\": \"00011\", \"e\": \"0000\", \"f\": \"1001101\", \"g\": \"1001100\", \"h\": \"10010111\", \"i\": \"110\",",
"eu fugiat nulla pariatur. Excepteur sint occaecat \" b\"cupidatat non proident, sunt in",
"\"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data(): tree = huffman.Node.from_data(simple) codes = {chr(symbol): code.unpack(\"bin\")[0] for",
"in voluptate velit esse cillum \" b\"dolore eu fugiat nulla pariatur. Excepteur sint",
"= huffman.decompress(lorem_compressed) assert(data == lorem) def test_both(): compressed = huffman.compress(simple) data = huffman.decompress(compressed)",
"== lorem_codes) def test_compression(): compressed = huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed) compressed = huffman.compress(lorem)",
"def test_decompression(): data = huffman.decompress(simple_compressed) assert(data == simple) data = huffman.decompress(lorem_compressed) assert(data ==",
"huffman.compress(simple) data = huffman.decompress(compressed) assert(data == simple) compressed = huffman.compress(lorem) data = huffman.decompress(compressed)",
"= { \" \": \"001\", \",\": \"1001000\", \".\": \"111111\", \"D\": \"100101101\", \"E\": \"100101100\",",
"\"111111\", \"D\": \"100101101\", \"E\": \"100101100\", \"L\": \"11111011\", \"U\": \"11111010\", \"a\": \"0111\", \"b\": \"1111100\",",
"tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_data(lorem) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol,",
"\" b\"aute irure dolor in reprehenderit in voluptate velit esse cillum \" b\"dolore",
"\" b\"cupidatat non proident, sunt in culpa qui officia deserunt \" b\"mollit anim",
"0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def",
"adipisicing \" b\"elit, sed do eiusmod tempor incididunt ut labore et dolore magna",
"b\"ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis \" b\"aute irure",
"\" \": \"001\", \",\": \"1001000\", \".\": \"111111\", \"D\": \"100101101\", \"E\": \"100101100\", \"L\": \"11111011\",",
"simple_codes) tree = huffman.Node.from_data(lorem) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()}",
"test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()}",
"Excepteur sint occaecat \" b\"cupidatat non proident, sunt in culpa qui officia deserunt",
"\"01000\", \"n\": \"1010\", \"o\": \"0110\", \"p\": \"11110\", \"q\": \"100111\", \"r\": \"1011\", \"s\": \"00010\",",
"\"2\": \"10\", \"3\": \"0\" } simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem =",
"= (b\"Lorem ipsum dolor sit amet, consectetur adipisicing \" b\"elit, sed do eiusmod",
"{chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_binary(lorem_tree)",
"for symbol, code in tree.codes().items()} assert(codes == lorem_codes) def test_compression(): compressed = huffman.compress(simple)",
"tree.codes().items()} assert(codes == lorem_codes) def test_compression(): compressed = huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed) compressed",
"officia deserunt \" b\"mollit anim id est laborum.\") lorem_codes = { \" \":",
"\"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data(): tree = huffman.Node.from_data(simple) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol,",
"proident, sunt in culpa qui officia deserunt \" b\"mollit anim id est laborum.\")",
"\"00011\", \"e\": \"0000\", \"f\": \"1001101\", \"g\": \"1001100\", \"h\": \"10010111\", \"i\": \"110\", \"l\": \"1110\",",
"symbol, code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_binary(lorem_tree) codes = {chr(symbol):",
"== simple_codes) tree = huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in",
"sit amet, consectetur adipisicing \" b\"elit, sed do eiusmod tempor incididunt ut labore",
"for symbol, code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_data(lorem) codes =",
"ut aliquip ex ea commodo consequat. Duis \" b\"aute irure dolor in reprehenderit",
"\" b\"aliqua. Ut enim ad minim veniam, quis nostrud exercitation \" b\"ullamco laboris",
"\"a\": \"0111\", \"b\": \"1111100\", \"c\": \"01001\", \"d\": \"00011\", \"e\": \"0000\", \"f\": \"1001101\", \"g\":",
"= huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed) def test_decompression(): data = huffman.decompress(simple_compressed) assert(data == simple)",
"lorem_compressed) def test_decompression(): data = huffman.decompress(simple_compressed) assert(data == simple) data = huffman.decompress(lorem_compressed) assert(data",
"= huffman.decompress(simple_compressed) assert(data == simple) data = huffman.decompress(lorem_compressed) assert(data == lorem) def test_both():",
"\"0110\", \"p\": \"11110\", \"q\": \"100111\", \"r\": \"1011\", \"s\": \"00010\", \"t\": \"0101\", \"u\": \"1000\",",
"\"E\": \"100101100\", \"L\": \"11111011\", \"U\": \"11111010\", \"a\": \"0111\", \"b\": \"1111100\", \"c\": \"01001\", \"d\":",
"\"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data(): tree = huffman.Node.from_data(simple) codes =",
"bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\"",
"lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data():",
"data = huffman.decompress(simple_compressed) assert(data == simple) data = huffman.decompress(lorem_compressed) assert(data == lorem) def",
"bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem ipsum dolor sit amet, consectetur adipisicing",
"\"1001101\", \"g\": \"1001100\", \"h\": \"10010111\", \"i\": \"110\", \"l\": \"1110\", \"m\": \"01000\", \"n\": \"1010\",",
"\" b\"dolore eu fugiat nulla pariatur. Excepteur sint occaecat \" b\"cupidatat non proident,",
"simple_codes = { \"1\": \"11\", \"2\": \"10\", \"3\": \"0\" } simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\")",
"= bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem ipsum dolor sit amet, consectetur",
"nostrud exercitation \" b\"ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis",
"consequat. Duis \" b\"aute irure dolor in reprehenderit in voluptate velit esse cillum",
"tree = huffman.Node.from_data(simple) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes",
"for symbol, code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_binary(lorem_tree) codes =",
"\"s\": \"00010\", \"t\": \"0101\", \"u\": \"1000\", \"v\": \"1001010\", \"x\": \"1001001\" } lorem_tree =",
"assert(bitstring.Bits(compressed) == simple_compressed) compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed) def test_decompression(): data =",
"\"11110\", \"q\": \"100111\", \"r\": \"1011\", \"s\": \"00010\", \"t\": \"0101\", \"u\": \"1000\", \"v\": \"1001010\",",
"\"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\")",
"compressed = huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed) compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed) def",
"\"100101100\", \"L\": \"11111011\", \"U\": \"11111010\", \"a\": \"0111\", \"b\": \"1111100\", \"c\": \"01001\", \"d\": \"00011\",",
"= bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data(): tree",
"\"0\" } simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem ipsum dolor",
"\"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\" \"3757534d47d6d8614b208a294ea298ef399e3169b37273918082e294a1bbb297ac838\" \"6404a79fe35c23f\") def test_tree_from_data(): tree = huffman.Node.from_data(simple) codes = {chr(symbol): code.unpack(\"bin\")[0]",
"assert(data == lorem) def test_both(): compressed = huffman.compress(simple) data = huffman.decompress(compressed) assert(data ==",
"nulla pariatur. Excepteur sint occaecat \" b\"cupidatat non proident, sunt in culpa qui",
"lorem) def test_both(): compressed = huffman.compress(simple) data = huffman.decompress(compressed) assert(data == simple) compressed",
"dolor sit amet, consectetur adipisicing \" b\"elit, sed do eiusmod tempor incididunt ut",
"tree.codes().items()} assert(codes == lorem_codes) def test_tree_from_binary(): tree = huffman.Node.from_binary(simple_tree) codes = {chr(symbol): code.unpack(\"bin\")[0]",
"cillum \" b\"dolore eu fugiat nulla pariatur. Excepteur sint occaecat \" b\"cupidatat non",
"et dolore magna \" b\"aliqua. Ut enim ad minim veniam, quis nostrud exercitation",
"sed do eiusmod tempor incididunt ut labore et dolore magna \" b\"aliqua. Ut",
"{ \" \": \"001\", \",\": \"1001000\", \".\": \"111111\", \"D\": \"100101101\", \"E\": \"100101100\", \"L\":",
"\"11\", \"2\": \"10\", \"3\": \"0\" } simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem",
"est laborum.\") lorem_codes = { \" \": \"001\", \",\": \"1001000\", \".\": \"111111\", \"D\":",
"\"001\", \",\": \"1001000\", \".\": \"111111\", \"D\": \"100101101\", \"E\": \"100101100\", \"L\": \"11111011\", \"U\": \"11111010\",",
"\"1001000\", \".\": \"111111\", \"D\": \"100101101\", \"E\": \"100101100\", \"L\": \"11111011\", \"U\": \"11111010\", \"a\": \"0111\",",
"\"1000\", \"v\": \"1001010\", \"x\": \"1001001\" } lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed =",
"b\"aute irure dolor in reprehenderit in voluptate velit esse cillum \" b\"dolore eu",
"\"1111100\", \"c\": \"01001\", \"d\": \"00011\", \"e\": \"0000\", \"f\": \"1001101\", \"g\": \"1001100\", \"h\": \"10010111\",",
"= huffman.decompress(compressed) assert(data == simple) compressed = huffman.compress(lorem) data = huffman.decompress(compressed) assert(data ==",
"\"0000\", \"f\": \"1001101\", \"g\": \"1001100\", \"h\": \"10010111\", \"i\": \"110\", \"l\": \"1110\", \"m\": \"01000\",",
"\"10\", \"3\": \"0\" } simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem",
"Ut enim ad minim veniam, quis nostrud exercitation \" b\"ullamco laboris nisi ut",
"esse cillum \" b\"dolore eu fugiat nulla pariatur. Excepteur sint occaecat \" b\"cupidatat",
"bitstring from compression import huffman simple = b\"122333\" simple_codes = { \"1\": \"11\",",
"\"6404a79fe35c23f\") def test_tree_from_data(): tree = huffman.Node.from_data(simple) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code",
"in culpa qui officia deserunt \" b\"mollit anim id est laborum.\") lorem_codes =",
"reprehenderit in voluptate velit esse cillum \" b\"dolore eu fugiat nulla pariatur. Excepteur",
"in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_data(lorem) codes = {chr(symbol): code.unpack(\"bin\")[0] for",
"ea commodo consequat. Duis \" b\"aute irure dolor in reprehenderit in voluptate velit",
"\"D\": \"100101101\", \"E\": \"100101100\", \"L\": \"11111011\", \"U\": \"11111010\", \"a\": \"0111\", \"b\": \"1111100\", \"c\":",
"tree = huffman.Node.from_binary(simple_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes",
"lorem_codes = { \" \": \"001\", \",\": \"1001000\", \".\": \"111111\", \"D\": \"100101101\", \"E\":",
"commodo consequat. Duis \" b\"aute irure dolor in reprehenderit in voluptate velit esse",
"symbol, code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_data(lorem) codes = {chr(symbol):",
"\"c\": \"01001\", \"d\": \"00011\", \"e\": \"0000\", \"f\": \"1001101\", \"g\": \"1001100\", \"h\": \"10010111\", \"i\":",
"ex ea commodo consequat. Duis \" b\"aute irure dolor in reprehenderit in voluptate",
"huffman simple = b\"122333\" simple_codes = { \"1\": \"11\", \"2\": \"10\", \"3\": \"0\"",
"\"o\": \"0110\", \"p\": \"11110\", \"q\": \"100111\", \"r\": \"1011\", \"s\": \"00010\", \"t\": \"0101\", \"u\":",
"do eiusmod tempor incididunt ut labore et dolore magna \" b\"aliqua. Ut enim",
"labore et dolore magna \" b\"aliqua. Ut enim ad minim veniam, quis nostrud",
"simple_compressed) compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed) def test_decompression(): data = huffman.decompress(simple_compressed) assert(data",
"ipsum dolor sit amet, consectetur adipisicing \" b\"elit, sed do eiusmod tempor incididunt",
"Duis \" b\"aute irure dolor in reprehenderit in voluptate velit esse cillum \"",
"b\"122333\" simple_codes = { \"1\": \"11\", \"2\": \"10\", \"3\": \"0\" } simple_tree =",
"b\"cupidatat non proident, sunt in culpa qui officia deserunt \" b\"mollit anim id",
"\"f\": \"1001101\", \"g\": \"1001100\", \"h\": \"10010111\", \"i\": \"110\", \"l\": \"1110\", \"m\": \"01000\", \"n\":",
"fugiat nulla pariatur. Excepteur sint occaecat \" b\"cupidatat non proident, sunt in culpa",
"\"1010\", \"o\": \"0110\", \"p\": \"11110\", \"q\": \"100111\", \"r\": \"1011\", \"s\": \"00010\", \"t\": \"0101\",",
"= bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\" \"90b4e575cd463b9d0963cff1af08d61630a5fb4f1bc42490729642186c52d4209e1d7\" \"f32d8c22f0a075c5811b7359d46c3d612e1430bca75194dd1e57503283b2901080a77\" \"74208db9ac08419b1333a9a8ee73e7bceb17f996494879422c8b52964a5c12ea531ec\"",
"\"11111011\", \"U\": \"11111010\", \"a\": \"0111\", \"b\": \"1111100\", \"c\": \"01001\", \"d\": \"00011\", \"e\": \"0000\",",
"\"g\": \"1001100\", \"h\": \"10010111\", \"i\": \"110\", \"l\": \"1110\", \"m\": \"01000\", \"n\": \"1010\", \"o\":",
"sunt in culpa qui officia deserunt \" b\"mollit anim id est laborum.\") lorem_codes",
"huffman.compress(simple) assert(bitstring.Bits(compressed) == simple_compressed) compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed) def test_decompression(): data",
"magna \" b\"aliqua. Ut enim ad minim veniam, quis nostrud exercitation \" b\"ullamco",
"codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == simple_codes) tree",
"\"t\": \"0101\", \"u\": \"1000\", \"v\": \"1001010\", \"x\": \"1001001\" } lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec,",
"b\"aliqua. Ut enim ad minim veniam, quis nostrud exercitation \" b\"ullamco laboris nisi",
"simple_tree = bitstring.Bits(\"0b00100110001100110010100110011\") simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem ipsum dolor sit amet,",
"= huffman.Node.from_data(lorem) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes ==",
"b\"elit, sed do eiusmod tempor incididunt ut labore et dolore magna \" b\"aliqua.",
"\"1001001\" } lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\" \"8945bb2f12cba8b0dbd7458eda90164b9d97edac10778508236e6b22ca5d00b20a5a8\" \"4095058b2e3dec2c9d530876590440323621a04861950479acea4e1e1c529853cff1a\" \"c08291b7358143cca72fda787fcfd290ac82e328d59065056744833c611a612dc0c84\"",
"= b\"122333\" simple_codes = { \"1\": \"11\", \"2\": \"10\", \"3\": \"0\" } simple_tree",
"\".\": \"111111\", \"D\": \"100101101\", \"E\": \"100101100\", \"L\": \"11111011\", \"U\": \"11111010\", \"a\": \"0111\", \"b\":",
"assert(bitstring.Bits(compressed) == lorem_compressed) def test_decompression(): data = huffman.decompress(simple_compressed) assert(data == simple) data =",
"incididunt ut labore et dolore magna \" b\"aliqua. Ut enim ad minim veniam,",
"tree = huffman.Node.from_data(lorem) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes",
"\"b\": \"1111100\", \"c\": \"01001\", \"d\": \"00011\", \"e\": \"0000\", \"f\": \"1001101\", \"g\": \"1001100\", \"h\":",
"compressed = huffman.compress(simple) data = huffman.decompress(compressed) assert(data == simple) compressed = huffman.compress(lorem) data",
"b\"mollit anim id est laborum.\") lorem_codes = { \" \": \"001\", \",\": \"1001000\",",
"= {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == simple_codes) tree =",
"{chr(symbol): code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_data(lorem)",
"\"u\": \"1000\", \"v\": \"1001010\", \"x\": \"1001001\" } lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed",
"def test_both(): compressed = huffman.compress(simple) data = huffman.decompress(compressed) assert(data == simple) compressed =",
"quis nostrud exercitation \" b\"ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"== simple_compressed) compressed = huffman.compress(lorem) assert(bitstring.Bits(compressed) == lorem_compressed) def test_decompression(): data = huffman.decompress(simple_compressed)",
"code.unpack(\"bin\")[0] for symbol, code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_binary(lorem_tree) codes",
"exercitation \" b\"ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis \"",
"assert(codes == simple_codes) tree = huffman.Node.from_data(lorem) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code",
"simple = b\"122333\" simple_codes = { \"1\": \"11\", \"2\": \"10\", \"3\": \"0\" }",
"irure dolor in reprehenderit in voluptate velit esse cillum \" b\"dolore eu fugiat",
"\"d\": \"00011\", \"e\": \"0000\", \"f\": \"1001101\", \"g\": \"1001100\", \"h\": \"10010111\", \"i\": \"110\", \"l\":",
"assert(codes == simple_codes) tree = huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code",
"#!/usr/bin/env python3 import bitstring from compression import huffman simple = b\"122333\" simple_codes =",
"\"100111\", \"r\": \"1011\", \"s\": \"00010\", \"t\": \"0101\", \"u\": \"1000\", \"v\": \"1001010\", \"x\": \"1001001\"",
"import bitstring from compression import huffman simple = b\"122333\" simple_codes = { \"1\":",
"\"m\": \"01000\", \"n\": \"1010\", \"o\": \"0110\", \"p\": \"11110\", \"q\": \"100111\", \"r\": \"1011\", \"s\":",
"laboris nisi ut aliquip ex ea commodo consequat. Duis \" b\"aute irure dolor",
"code in tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0]",
"data = huffman.decompress(compressed) assert(data == simple) compressed = huffman.compress(lorem) data = huffman.decompress(compressed) assert(data",
"import huffman simple = b\"122333\" simple_codes = { \"1\": \"11\", \"2\": \"10\", \"3\":",
"occaecat \" b\"cupidatat non proident, sunt in culpa qui officia deserunt \" b\"mollit",
"sint occaecat \" b\"cupidatat non proident, sunt in culpa qui officia deserunt \"",
"\"U\": \"11111010\", \"a\": \"0111\", \"b\": \"1111100\", \"c\": \"01001\", \"d\": \"00011\", \"e\": \"0000\", \"f\":",
"tree.codes().items()} assert(codes == simple_codes) tree = huffman.Node.from_binary(lorem_tree) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol,",
"== lorem_compressed) def test_decompression(): data = huffman.decompress(simple_compressed) assert(data == simple) data = huffman.decompress(lorem_compressed)",
"== simple_codes) tree = huffman.Node.from_data(lorem) codes = {chr(symbol): code.unpack(\"bin\")[0] for symbol, code in",
"assert(data == simple) data = huffman.decompress(lorem_compressed) assert(data == lorem) def test_both(): compressed =",
"tempor incididunt ut labore et dolore magna \" b\"aliqua. Ut enim ad minim",
"laborum.\") lorem_codes = { \" \": \"001\", \",\": \"1001000\", \".\": \"111111\", \"D\": \"100101101\",",
"simple_compressed = bitstring.Bits(\"0x498cca67d0\") lorem = (b\"Lorem ipsum dolor sit amet, consectetur adipisicing \"",
"\"v\": \"1001010\", \"x\": \"1001001\" } lorem_tree = bitstring.Bits(\"0x025c532ab62b85b2d25cadc2e2b359c5a144a2dd97\" \"8965d4586deba2c76d480b25cec, 0b101\") lorem_compressed = bitstring.Bits(\"0x0204b8a6556c570b65a4b95b85c566b38b42\"",
"id est laborum.\") lorem_codes = { \" \": \"001\", \",\": \"1001000\", \".\": \"111111\","
] |
[
"if not action: action = self.try_merge() #if not action: # action = self.try_dependent()",
"alignment empty (or singleton) if len(tok_alignment) <= 1: return None # check if",
"+ 1) if not cur_alignment or not nxt_alignment: return None # If both",
"action is PRED, COPY_LEMMA, COPY_SENSE01. If 1) the current token is aligned to",
"= num_sentences - num_unique_sents perc = num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f}",
"in the state machine, value: list of node ids in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id]",
"write CLOSE action at the end; # CLOSE action is internally managed, and",
"if multitask_max_words: assert multitask_max_words assert out_multitask_words # get top words multitask_words = get_multitask_actions(",
"if len(self.machine.actions) and self.machine.actions[-1] == 'SHIFT' and self.machine.tok_cursor != self.machine.tokseq_len - 1 :",
"to a token. \"\"\" machine = self.machine gold_amr = self.gold_amr if machine.current_node_id is",
"in tids if tid <= len(gold_amr.tokens)] # TODO: describe this # append a",
"find the next action # NOTE the order here is important, which is",
"exist in the predicted amr, the oracle adds it using the DEPENDENT action.",
"@property def tokens(self): return self.gold_amr.tokens @property def time_step(self): return self.machine.time_step @property def actions(self):",
"r, t in edges: if r == ':name' and gold_amr.nodes[t] == 'name': return",
"# never do PRED(<ROOT>) currently, as the root node is automatically added at",
"linearized action sequences for AMR graphs in a rule based way. The parsing",
"the token ids natural positive index # setting a token id to -1",
"expression if len(aligned_tokens) > 1: token_str = \" \".join(aligned_tokens) else: token_str = aligned_tokens[0]",
"= state_machine.get_current_token(lemma=False) if tok in multitask_words: return f'SHIFT({tok})' else: return 'SHIFT' def get_multitask_actions(max_symbols,",
"alert_inconsistencies(gold_amrs): def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string num_sentences = len(gold_amrs) sentence_count = Counter()",
"num_labelings += len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) > 1: pass # There is more than",
"multitask_max_words assert not out_multitask_words # store in file with open(in_multitask_words) as fid: multitask_words",
"if self.time_step >= 8: # breakpoint() action = self.try_reduce() if not action: action",
"we do multiple PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root # TODO for multiple PREDs, we",
"if arc_name == 'LA': if (node_id, arc_label, act_node_id) in machine.amr.edges: continue if arc_name",
"def try_dependent(self): \"\"\" Check if the next action is DEPENDENT. If 1) the",
"entity types that can have pred\" ) args = parser.parse_args() return args def",
"= None for s, r, t in edges: if s not in self.built_gold_nodeids:",
"Counter()) for amr in gold_amrs: # hash of sentence skey = \" \".join(amr.tokens)",
"for one sentence.\"\"\" def __init__(self, gold_amr, lemmatizer, copy_lemma_action, multitask_words): self.gold_amr = gold_amr #",
"in sentence]) # Restrict to top-k words allowed_words = dict(list(sorted( word_count.items(), key=lambda x:",
"self.gold_amr tok_id = machine.tok_cursor node_id = machine.current_node_id if node_id is None: # NOTE",
"-1 self.built_gold_nodeids = [] @property def tokens(self): return self.gold_amr.tokens @property def time_step(self): return",
"just in case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id + 1) # below is coupled with",
"always use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge = r[1:] if r.startswith(':') else r",
"and self.multitask_words is not None: action = label_shift(self.machine, self.multitask_words) valid_actions = [action] invalid_actions",
"1) # NOTE the index + 1 if len(tok_alignment) == 0: return 'REDUCE'",
"the current node to the previous node at location pos RA(pos,label) : form",
"each hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count) num_labelings = 0 for skey, sent_count",
"args.copy_lemma_action, multitask_words) # print stats about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save statistics write_tokenized_sentences(",
"for counter in amr_counts_by_sentence.values() for count in counter.values() ) ) print(yellow_font(alert_str)) if num_labelings",
"edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None # check if named entity",
"(act_node_id, arc_label, node_id) in machine.amr.edges: continue # pointer value arc_pos = act_id return",
"whitespaces\" ) # copy lemma action parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use copy action from",
"token 1 node1 = gold_amr.findSubGraph(nodes1).root else: node1 = nodes1[0] if len(nodes2) > 1:",
"with open(out_multitask_words, 'w') as fid: for word in multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words: assert",
"gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] # NOTE gold amr root id is fixed",
"= get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root ) # store in file with open(out_multitask_words, 'w')",
"gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE the index + 1 if len(tok_alignment) == 0:",
"are checking the target nodes in the subgraph # gold_nodeids = self.nodeid_to_gold_nodeid[node_id] #",
"Loop over potential actions # NOTE \"<ROOT>\" token at last position is added",
"# store data statistics['sentence_tokens'].append(oracle_builder.tokens) # do not write CLOSE action at the end;",
"gold_nodeids and (t in gold_amr.alignments and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) # NOTE this might",
"= r[1:] if r.startswith(':') else r new_node = gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})' return",
"self.try_pred() if not action: if len(self.machine.actions) and self.machine.actions[-1] == 'SHIFT' and self.machine.tok_cursor !=",
"'spoonbill', '.'] # TODO if not dealt with, this causes a problem when",
"<= 1: return None # check if there is any edge with the",
"in action_count.items() if c == 1] print('Base actions:') print(Counter([k.split('(')[0] for k in action_count.keys()]))",
"If 1) aligned to more than 1 nodes, and 2) there are edges",
"in training data, when the sentence is # ['Among', 'common', 'birds', ',', 'a',",
"continue self.built_gold_nodeids.append(t) # NOTE this might affect the next DEPEDENT check, but is",
"by # token node_by_token[token_str].update([node]) return node_by_token def is_most_common(node_counts, node, rank=0): return ( (",
"machine.current_node_id in machine.entities: return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if",
"applied more # transparently print(f'Reading {args.in_amr}') corpus = read_amr(args.in_amr, unicode_fixes=True) gold_amrs = corpus.amrs",
"{:2.4f} % {:s}'.format( num_inconsistent, num_sentences, perc, 'inconsistent labelings from repeated sents' ) print(yellow_font(alert_str))",
"# NOTE the order here is important, which is based on priority #",
"involve the current token aligned node. If 1) currently is on a node",
"node_id) in machine.amr.edges: continue # pointer value arc_pos = act_id return f'{arc_name}({arc_pos},{arc_label})' return",
"before tryPRED. If 1) aligned to more than 1 nodes, and 2) there",
"return ( ( # as many results as the rank and node in",
"add_root=True ) # run the oracle for the entire corpus stats = run_oracle(gold_amrs,",
"in entities_with_preds and not is_dependent: return None new_id = None for s, r,",
"in action_count.keys()])) print('Most frequent actions:') print(action_count.most_common(10)) if singletons: base_action_count = [x.split('(')[0] for x",
"tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE we make all token ids positive",
"self.time_step >= 8: # breakpoint() action = self.try_reduce() if not action: action =",
"from the previous node at location pos CLOSE : complete AMR, run post-processing",
"to use for multi-task\" ) # Labeled shift args parser.add_argument( \"--out-multitask-words\", type=str, help=\"where",
"TODO: describe this # append a special token at the end of the",
"multitask_max_words, tokenized_corpus, add_root=add_root ) # store in file with open(out_multitask_words, 'w') as fid:",
"should we do multiple PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root # TODO for multiple PREDs,",
"be deterministic\" assert len(invalid_actions) == 0, \"Oracle can\\'t blacklist actions\" action = valid_actions[0]",
"need it i.e. person, thing \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id",
"edges in the aligned subgraph, and then 3) take the source nodes in",
"this sentence if args.out_rule_stats: with open(args.out_rule_stats, 'w') as fid: fid.write(json.dumps(stats['rules'])) if __name__ ==",
"num_sentences alert_str = '{:d}/{:d} {:2.1f} % {:s} (max {:d} times)'.format( num_repeated, num_sentences, 100",
"return multitask_words def print_corpus_info(amrs): # print some info print(f'{len(amrs)} sentences') node_label_count = Counter([",
"while not machine.is_closed: valid_actions, invalid_actions = self.get_valid_actions() # for now assert len(valid_actions) ==",
"managed, and treated same as <eos> in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules",
"= read_propbank(args.in_propbank_args) # read/write multi-task (labeled shift) action # TODO: Add conditional if",
"TODO: Add conditional if here multitask_words = process_multitask_words( [list(amr.tokens) for amr in gold_amrs],",
"current token is aligned to a single node, or multiple nodes? (figure out)",
"as the mapping from ENTITY node is only to the source nodes in",
"was just constructed 2) there are edges that have not been built with",
"not edges: return None is_dependent = False for s, r, t in edges:",
"of time sentence repeated sentence_count.update([skey]) # hash of AMR labeling akey = amr.toJAMRString()",
"in tokenized_corpus: word_count.update([x for x in sentence]) # Restrict to top-k words allowed_words",
"arcs] LA(pos,':name') c) for two entities with two surface tokens ENTITY('name') PRED('city') [other",
"\"\"\"Get the valid actions and invalid actions based on the current AMR state",
"a new node by copying lemma COPY_SENSE01 : form a new node by",
"Counter, defaultdict import re from tqdm import tqdm from transition_amr_parser.io import read_propbank, read_amr,",
"add root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root)) # gold_amr.alignments[root_id] =",
"if len(tok_alignment) == 0: return 'REDUCE' else: return None def try_merge(self): \"\"\" Check",
"in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)' if s not in self.built_gold_nodeids: self.built_gold_nodeids.append(s)",
"in gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True ) # run the oracle for the",
"in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})' return None def try_entities_with_pred(self): \"\"\" allow",
"= defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda: Counter()) for amr in gold_amrs: # hash of",
"for tid in tids if tid <= len(gold_amr.tokens)] # TODO: describe this #",
"[] return valid_actions, invalid_actions def build_oracle_actions(self): \"\"\"Build the oracle action sequence for the",
"then named entity subsequence, etc. # debug # on dev set, sentence id",
"\"\"\" Check if the next action is ENTITY. TryENTITY before tryPRED. If 1)",
"len(node_counts) > rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node and node_counts.most_common(rank",
"node which is a dependent of the current node LA(pos,label) : form a",
"position is added as a node from the beginning, so no prediction #",
"root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge = r[1:] if r.startswith(':') else r new_node = gold_amr.nodes[t]",
"machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions def try_reduce(self): \"\"\" Check if the next action is",
"collections import Counter, defaultdict import re from tqdm import tqdm from transition_amr_parser.io import",
"gold_amr.nodes[root] in entities_with_preds or is_dependent): return None gold_nodeids = [n for n in",
"for n in tok_alignment if any(s == n for s, r, t in",
"if the next action is ENTITY. TryENTITY before tryPRED. If 1) aligned to",
"is_named and ( gold_amr.nodes[root] in entities_with_preds or is_dependent): return None gold_nodeids = [n",
"labelings from repeated sents'.format( num_inconsistent, num_sentences, perc ) print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words =",
"a node that was just constructed 2) there are edges that have not",
"else: node1 = nodes1[0] if len(nodes2) > 1: # get root of subgraph",
"return self.actions def try_reduce(self): \"\"\" Check if the next action is REDUCE. If",
"in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True)",
"node has not been built at current step return None #for act_id, act_node_id",
") parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma separated list of entity types that can",
"previous node at location pos CLOSE : complete AMR, run post-processing \"\"\" use_addnode_rules",
"+ 1) # NOTE we make all token ids positive natural index #",
"more than one labeling for this sentence # amrs = list(amr_by_amrkey_by_sentence[skey].values()) # inform",
"gold_amr = self.gold_amr tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check",
"new_id = None for s, r, t in edges: if s not in",
"below are equivalent # machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions def try_reduce(self):",
"if machine.tok_cursor < machine.tokseq_len - 1: cur = machine.tok_cursor nxt = machine.tok_cursor +",
"# gold_nodeids = self.nodeid_to_gold_nodeid[node_id] # gold_nodeids = list(set(gold_nodeids)) # just in case gold_nodeids",
"= argument_parser() global entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\") # Load AMR (replace some unicode",
"Load propbank if provided # TODO: Use here XML propbank reader instead of",
"a left arc from the current node to the previous node at location",
"valid actions and invalid actions based on the current AMR state machine status",
"corpus stats = run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) # print stats about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions'])",
"a token. \"\"\" machine = self.machine gold_amr = self.gold_amr if machine.current_node_id is not",
"1 cur_alignment = gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt + 1) if not",
"+ 1) # NOTE the index + 1 if len(tok_alignment) == 0: return",
"len(sentence_count) num_labelings = 0 for skey, sent_count in sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey]) if",
"{:2.1f} % {:s} (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, 'repeated sents',",
"as fid: for line in fid: items = line.strip().split('\\t') if len(items) > 2:",
"by removing whitespaces\" ) # copy lemma action parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use copy",
"an edge `node_id2` <-- `node_id2` Thus the order of inputs matter. (could also",
"AMR oracle for one sentence.\"\"\" def __init__(self, gold_amr, lemmatizer, copy_lemma_action, multitask_words): self.gold_amr =",
"self.try_named_entities() if not action: action = self.try_entities_with_pred() if not action: action = self.try_entity()",
"added twice, as each time we scan all the possible edges continue if",
"arcs. Actions are SHIFT : move cursor to next position in the token",
"gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE we make all token ids positive natural index",
"[k for k, c in action_count.items() if c == 1] print('Base actions:') print(Counter([k.split('(')[0]",
"= num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % inconsistent labelings from repeated",
"that and remove this cleaning process # an example is in training data,",
"Counter([ n for amr in amrs for n in amr.nodes.values() ]) node_tokens =",
"in alignments.items(): # join multiple words into one single expression if len(aligned_tokens) >",
"check edges arc = self.get_arc(act_node_id, node_id) if arc is None: continue arc_name, arc_label",
"in_multitask_words, out_multitask_words, add_root=False): # Load/Save words for multi-task if multitask_max_words: assert multitask_max_words assert",
"if r == ':name' and gold_amr.nodes[t] == 'name': return None if r in",
"the beginning # NOTE to change this behavior, we need to be careful",
"multi-task (labeled shift) action # TODO: Add conditional if here multitask_words = process_multitask_words(",
"num_repeated = num_sentences - num_unique_sents perc = num_repeated / num_sentences alert_str = '{:d}/{:d}",
"s, r, t in entity_edges: if t not in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t)",
"self.multitask_words) valid_actions = [action] invalid_actions = [] return valid_actions, invalid_actions def build_oracle_actions(self): \"\"\"Build",
"in gold_amr.edges if s in align and t in align ] if not",
"= [] name_node_ids = [] for s, r, t in edges: if r",
"if r in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if not",
"to next position in the token sequence REDUCE : delete current token MERGE",
"multiple words into one single expression if len(aligned_tokens) > 1: token_str = \"",
"token at the end of the sentence for the first unaligned node #",
"multitask_words = [line.strip() for line in fid.readlines()] else: multitask_words = None return multitask_words",
"multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words: assert not multitask_max_words assert not out_multitask_words # store in",
"= num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % {:s} (max {:d} times)'.format(",
"out_multitask_words # store in file with open(in_multitask_words) as fid: multitask_words = [line.strip() for",
"if not edges: return None is_dependent = False for s, r, t in",
"in self.built_gold_nodeids: new_id = s break if t not in self.built_gold_nodeids: new_id =",
"1: token_str = \" \".join(aligned_tokens) else: token_str = aligned_tokens[0] node = train_amr.nodes[node_id] #",
"return args def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string entities_with_preds = [] def preprocess_amr(gold_amr,",
"= pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons = [k for",
"= machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment empty (or",
"two surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') ENTITY('name') PRED('city') [other arcs] LA(pos,':name')",
"'the', 'black', '-', 'faced', 'spoonbill', '.'] # TODO if not dealt with, this",
"edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None is_dependent = False for s,",
"return allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words, add_root=False): # Load/Save words for multi-task",
"1: # get root of subgraph aligned to token 1 node1 = gold_amr.findSubGraph(nodes1).root",
"id to -1 will break the code gold_amr.alignments[root_id] = [len(gold_amr.tokens)] # NOTE shifted",
"valid_actions, invalid_actions def build_oracle_actions(self): \"\"\"Build the oracle action sequence for the current token",
"MERGE : merge two tokens (for MWEs) ENTITY(type) : form a named entity,",
"assert len(valid_actions) == 1, \"Oracle must be deterministic\" assert len(invalid_actions) == 0, \"Oracle",
"at location pos RA(pos,label) : form a left arc to the current node",
"token_str = \" \".join(aligned_tokens) else: token_str = aligned_tokens[0] node = train_amr.nodes[node_id] # count",
"action_count.keys()])) print('Most frequent actions:') print(action_count.most_common(10)) if singletons: base_action_count = [x.split('(')[0] for x in",
"Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda: Counter()) for amr in gold_amrs: #",
"\"\"\" Get the named entity sub-sequences one by one from the current surface",
"add_root=False): word_count = Counter() for sentence in tokenized_corpus: word_count.update([x for x in sentence])",
"len(gold_nodeids) == 1: gold_nodeid = gold_nodeids[0] else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for s, r,",
"= f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons = [k for k, c in",
"NOTE we make all token ids positive natural index # check if the",
"an example is in training data, when the sentence is # ['Among', 'common',",
"store count of PREDs given pointer position 'possible_predicates': defaultdict(lambda: Counter()) } } pred_re",
"return None if machine.tok_cursor < machine.tokseq_len - 1: cur = machine.tok_cursor nxt =",
"help=\"verbose processing\" ) # parser.add_argument( \"--multitask-max-words\", type=int, help=\"number of woprds to use for",
"i in range(len(train_amr.tokens)): for al_node in train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append( train_amr.tokens[i] ) for",
"+= len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) > 1: pass # There is more than one",
"first time on a new token return None if machine.tok_cursor < machine.tokseq_len -",
"1)[-1][1] > node_counts.most_common(rank + 2)[-1][1] ) ) def sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs) sentence_count",
"do not allow multiple ENTITY here on a single token if machine.current_node_id in",
"'REDUCE' else: return None def try_merge(self): \"\"\" Check if the next action is",
"import Counter, defaultdict import re from tqdm import tqdm from transition_amr_parser.io import read_propbank,",
"t in edges: if r == ':name' and gold_amr.nodes[t] == 'name': entity_edges.append((s, r,",
"nxt = machine.tok_cursor + 1 cur_alignment = gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt",
"for al_node in train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append( train_amr.tokens[i] ) for node_id, aligned_tokens in",
"make all token ids positive natural index # check if the alignment is",
"AMR graph nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1, list): nodes1",
"# check if alignment empty (or singleton) if len(tok_alignment) <= 1: return None",
"and also the ENTITY if len(gold_nodeids) == 1: gold_nodeid = gold_nodeids[0] else: gold_nodeid",
"alignments for i, tok in enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i + 1) if len(align)",
"currently do not allow multiple ENTITY here on a single token if machine.current_node_id",
"== 1: gold_nodeid = tok_alignment[0] else: # TODO check when this happens ->",
"\"--out-sentences\", help=\"tokenized sentences from --in-amr\", type=str ) parser.add_argument( \"--out-actions\", help=\"actions given by oracle\",",
"the oracle action sequence for the current token sentence, based on the gold",
"by copying lemma COPY_SENSE01 : form a new node by copying lemma and",
"this cleaning process # an example is in training data, when the sentence",
"> node_counts.most_common(rank + 2)[-1][1] ) ) def sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs) sentence_count =",
"the end of the sentence for the first unaligned node # whose label",
"assert len(invalid_actions) == 0, \"Oracle can\\'t blacklist actions\" action = valid_actions[0] # update",
"# check if there is any edge with the aligned nodes edges =",
"node. If 1) currently is on a node that was just constructed 2)",
"current node to the previous node at location pos RA(pos,label) : form a",
"by one from the current surface token (segments). E.g. a) for one entity",
"[tid for tid in tids if tid <= len(gold_amr.tokens)] # TODO: describe this",
"\"--addnode-count-cutoff\", help=\"forbid all addnode actions appearing less times than count\", type=int ) parser.add_argument(",
"# repeat `add_unaligned` times if add_unaligned: for i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n",
"single node aligned to each of these two tokens if len(nodes1) > 1:",
"action='store_true', help=\"Use copy action from Spacy lemmas\" ) # copy lemma action parser.add_argument(",
"PRED('city') [other arcs] LA(pos,':name') b) for two entities with same surface tokens ENTITY('name')",
"be 0, 'if not node_id' would cause a bug # the node has",
"parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument data\", type=str, ) parser.add_argument( \"--out-oracle\", help=\"tokens, AMR notation and",
"oracle\", type=str ) parser.add_argument( \"--out-action-stats\", help=\"statistics about actions\", type=str ) parser.add_argument( \"--out-rule-stats\", #",
"DEPENDENT. If 1) the aligned node has been predicted already 2) Only for",
"node or overlap if cur_alignment == nxt_alignment: return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE'",
"r, t in entity_edges: if t not in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return",
"actions, arc subsequence comes highest, then named entity subsequence, etc. # debug #",
"actions based on the current AMR state machine status and the gold AMR.\"\"\"",
"t in edges: if r == ':name' and gold_amr.nodes[t] == 'name': is_named =",
"-> for DEPENDENT missing # if self.tokens == ['The', 'cyber', 'attacks', 'were', 'unprecedented',",
"= [k for k, c in action_count.items() if c == 1] print('Base actions:')",
"node2 == s: return ('LA', r) return None def run_oracle(gold_amrs, copy_lemma_action, multitask_words): #",
"defaultdict(lambda: Counter()) for train_amr in gold_amrs_train: # Get alignments alignments = defaultdict(list) for",
"state machine self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action self.multitask_words =",
"gold_amr.alignments or not gold_amr.alignments[n]: if gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)] break #",
"self.gold_amr # get the node ids in the gold AMR graph nodes1 =",
"node_id' would cause a bug # the node has not been built at",
"if n not in gold_amr.alignments or not gold_amr.alignments[n]: if gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n]",
"= True if r in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root",
"sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda:",
"or a subgraph PRED(label) : form a new node with label COPY_LEMMA :",
"store the oracle stats statistics = { 'sentence_tokens': [], 'oracle_actions': [], 'oracle_amr': [],",
"args.in_multitask_words, args.out_multitask_words, add_root=True ) # run the oracle for the entire corpus stats",
"copy_lemma_action, multitask_words) # build the oracle actions sequence actions = oracle_builder.build_oracle_actions() # store",
"matches len(node_counts) == rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node )",
"'REDUCE' else: action = 'SHIFT' if action == 'SHIFT' and self.multitask_words is not",
"node in that rank matches, and rank # results is more probable than",
"this happens -> should we do multiple PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root # TODO",
"count for counter in amr_counts_by_sentence.values() for count in counter.values() ) ) print(yellow_font(alert_str)) if",
"the mapping from ENTITY node is only to the source nodes in the",
"pred rules for idx, action in enumerate(actions): if pred_re.match(action): node_name = pred_re.match(action).groups()[0] token",
"edges: if r == ':name' and gold_amr.nodes[t] == 'name': return None if r",
"ENTITY after named entities if tok_id in machine.entity_tokenids: return None # NOTE currently",
"massively used in postprocessing to find/add root. return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id +",
"t: return ('RA', r) if node1 == t and node2 == s: return",
"desc='Oracle'): # TODO: See if we can remove this part gold_amr = gold_amr.copy()",
"out_multitask_words # get top words multitask_words = get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root ) #",
"a for loop here # check if the node has been constructed, for",
"stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t' ) # State machine stats for",
"in amr.edges]) edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count = Counter([w for amr",
"case: (entity_category, ':name', 'name') # no need, since named entity check happens first",
"LDC format\", type=str, required=True ) parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument data\", type=str, ) parser.add_argument(",
"location pos RA(pos,label) : form a left arc to the current node from",
"# copy lemma action parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use copy action from Spacy lemmas\"",
"shifted by 1 for AMR alignment return gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of",
"remove pointer for action in actions: if pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups() action =",
"machine.tok_cursor < machine.tokseq_len - 1: cur = machine.tok_cursor nxt = machine.tok_cursor + 1",
"at current step return None # NOTE this doesn't work for ENTITY now,",
"else: return None def try_merge(self): \"\"\" Check if the next action is MERGE.",
"None tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE the index",
"parsing algorithm is transition-based combined with pointers for long distance arcs. Actions are",
"the code gold_amr.alignments[root_id] = [len(gold_amr.tokens)] # NOTE shifted by 1 for AMR alignment",
"items = pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons = [k",
"\"\"\" Check if the next action is DEPENDENT. If 1) the aligned node",
"if node1 == t and node2 == s: return ('LA', r) return None",
"inconsistent labelings from repeated sents'.format( num_inconsistent, num_sentences, perc ) print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words",
"return None def try_named_entities(self): \"\"\" Get the named entity sub-sequences one by one",
"= [] target_lengths = [] action_count = Counter() for tokens, actions in zip(sentence_tokens,",
"key: node id in the state machine, value: list of node ids in",
"not machine.is_closed: valid_actions, invalid_actions = self.get_valid_actions() # for now assert len(valid_actions) == 1,",
"sentence length (not -1) for nid, tids in gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid for",
"0, \"Oracle can\\'t blacklist actions\" action = valid_actions[0] # update the machine machine.apply_action(action)",
"self.built_gold_nodeids: new_id = s break if t not in self.built_gold_nodeids: new_id = t",
"should be -1 now # that is also massively used in postprocessing to",
"a bug # the node has not been built at current step return",
"amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action self.multitask_words = multitask_words # TODO deprecate `multitask_words` or",
"gold_amr.edges: if s == gold_nodeid and r in [':polarity', ':mode']: if (node_id, r)",
"is None: continue arc_name, arc_label = arc # avoid repetitive edges if arc_name",
"State machine stats for this sentence if args.out_rule_stats: with open(args.out_rule_stats, 'w') as fid:",
"the valid actions and invalid actions based on the current AMR state machine",
"algorithm contains heuristics for generating linearized action sequences for AMR graphs in a",
"multitask_words) # print stats about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save statistics write_tokenized_sentences( args.out_actions,",
"if len(amr_counts_by_sentence[skey]) > 1: pass # There is more than one labeling for",
"current and the next token have the same node alignment. \"\"\" machine =",
"k, c in action_count.items() if c == 1] print('Base actions:') print(Counter([k.split('(')[0] for k",
"surface words\"\"\" node_by_token = defaultdict(lambda: Counter()) for train_amr in gold_amrs_train: # Get alignments",
"singleton actions' print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string num_sentences",
"== 1, \"Oracle must be deterministic\" assert len(invalid_actions) == 0, \"Oracle can\\'t blacklist",
"assert not multitask_max_words assert not out_multitask_words # store in file with open(in_multitask_words) as",
"multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab separation in actions and sentences by",
"\"\"\" This algorithm contains heuristics for generating linearized action sequences for AMR graphs",
"in the token sequence REDUCE : delete current token MERGE : merge two",
"token sequence REDUCE : delete current token MERGE : merge two tokens (for",
"\".join(amr.tokens) # count number of time sentence repeated sentence_count.update([skey]) # hash of AMR",
"'w') as fid: for word in multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words: assert not multitask_max_words",
"if gold_nodeid not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid] if self.copy_lemma_action:",
"example is in training data, when the sentence is # ['Among', 'common', 'birds',",
"clean invalid alignments: sometimes the alignments are outside of the sentence boundary #",
"amr root id is fixed at -1 self.built_gold_nodeids = [] @property def tokens(self):",
"for s, r, t in gold_amr.edges if s in align and t in",
"t)) name_node_ids.append(t) if not name_node_ids: return None for s, r, t in entity_edges:",
"AMR, run post-processing \"\"\" use_addnode_rules = True def argument_parser(): parser = argparse.ArgumentParser(description='AMR parser",
"== n for s, r, t in edges)] new_nodes = ','.join([gold_amr.nodes[n] for n",
"user if num_sentences > num_unique_sents: num_repeated = num_sentences - num_unique_sents perc = num_repeated",
"== 0: return 'REDUCE' else: return None def try_merge(self): \"\"\" Check if the",
"unicode characters) # TODO: unicode fixes and other normalizations should be applied more",
"LA(pos,'root') SHIFT CLOSE] machine = self.machine while not machine.is_closed: valid_actions, invalid_actions = self.get_valid_actions()",
"in singletons] msg = f'{len(singletons)} singleton actions' print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def yellow_font(string):",
"len(tok_alignment) == 0: return 'REDUCE' else: return None def try_merge(self): \"\"\" Check if",
"constructed, for multiple PREDs if gold_nodeid not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node",
"self.built_gold_nodeids.append(t) # NOTE this might affect the next DEPEDENT check, but is fine",
"from transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine, get_spacy_lemmatizer ) \"\"\" This algorithm contains heuristics for",
"handling args = argument_parser() global entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\") # Load AMR (replace",
"s: return ('LA', r) return None def run_oracle(gold_amrs, copy_lemma_action, multitask_words): # Initialize lemmatizer",
"return None tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE the",
"join multiple words into one single expression if len(aligned_tokens) > 1: token_str =",
"amr.tokens]) word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class AMROracleBuilder: \"\"\"Build AMR oracle for",
"that have not been built with this node \"\"\" machine = self.machine node_id",
"is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if not is_named and ( gold_amr.nodes[root] in",
"CLOSE] or [... LA(pos,'root') SHIFT CLOSE] machine = self.machine while not machine.is_closed: valid_actions,",
"to the previous node at location pos RA(pos,label) : form a left arc",
"edges that have not been built with this node \"\"\" machine = self.machine",
"Get the named entity sub-sequences one by one from the current surface token",
"help=\"avoid tab separation in actions and sentences by removing whitespaces\" ) # copy",
"\"--in-amr\", help=\"AMR notation in LDC format\", type=str, required=True ) parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument",
"[list(amr.tokens) for amr in gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True ) # run the",
"gold_amr.alignments and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) # NOTE this might affect the next DEPEDENT",
"True def argument_parser(): parser = argparse.ArgumentParser(description='AMR parser oracle') # Single input parameters parser.add_argument(",
"TODO: unicode fixes and other normalizations should be applied more # transparently print(f'Reading",
"in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr # count how many time each hash appears",
"== ':name' and gold_amr.nodes[t] == 'name': entity_edges.append((s, r, t)) name_node_ids.append(t) if not name_node_ids:",
"on a new token return None tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id +",
"= self.machine node_id = machine.current_node_id if node_id is None: # NOTE if node_id",
"lemmas\" ) # copy lemma action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all addnode actions appearing",
"the aligned subgraph, and then 3) take the source nodes in the aligned",
"action='store_true', help=\"avoid tab separation in actions and sentences by removing whitespaces\" ) #",
"gold_amr.findSubGraph(tok_alignment).root if not is_named and ( gold_amr.nodes[root] in entities_with_preds or is_dependent): return None",
"node has not been predicted yet \"\"\" machine = self.machine gold_amr = self.gold_amr",
"invalid actions based on the current AMR state machine status and the gold",
"tok = state_machine.get_current_token(lemma=False) if tok in multitask_words: return f'SHIFT({tok})' else: return 'SHIFT' def",
"at last position is added as a node from the beginning, so no",
"dependent of the current node LA(pos,label) : form a left arc from the",
"copy lemma action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all addnode actions appearing less times than",
"with open(in_multitask_words) as fid: multitask_words = [line.strip() for line in fid.readlines()] else: multitask_words",
"+ 1)[-1][0] == node and node_counts.most_common(rank + 1)[-1][1] > node_counts.most_common(rank + 2)[-1][1] )",
"re.compile(r'^PRED\\((.*)\\)$') # Process AMRs one by one for sent_idx, gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'):",
"Get the arcs between node with `node_id1` and node with `node_id2`. RA if",
"import re from tqdm import tqdm from transition_amr_parser.io import read_propbank, read_amr, write_tokenized_sentences from",
"in counter.values() ) ) print(yellow_font(alert_str)) if num_labelings > num_unique_sents: num_inconsistent = num_labelings -",
"the aligned node has not been predicted yet \"\"\" machine = self.machine gold_amr",
"len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) > 1: pass # There is more than one labeling",
"break if new_id != None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node = gold_amr.nodes[new_id] if self.copy_lemma_action:",
"node1 = gold_amr.findSubGraph(nodes1).root else: node1 = nodes1[0] if len(nodes2) > 1: # get",
"[':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if not is_named and (",
") parser.add_argument( \"--out-sentences\", help=\"tokenized sentences from --in-amr\", type=str ) parser.add_argument( \"--out-actions\", help=\"actions given",
"times than count\", type=int ) parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma separated list of",
"does not exist in the predicted amr, the oracle adds it using the",
"action. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor node_id =",
"edges: return None # check if named entity case: (entity_category, ':name', 'name') entity_edges",
"prevent same DEPENDENT added twice, as each time we scan all the possible",
"self.gold_amr.tokens @property def time_step(self): return self.machine.time_step @property def actions(self): return self.machine.actions def get_valid_actions(self):",
"r.startswith(':') else r new_node = gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})' return action return None",
"for this sentence # amrs = list(amr_by_amrkey_by_sentence[skey].values()) # inform user if num_sentences >",
"1: cur = machine.tok_cursor nxt = machine.tok_cursor + 1 cur_alignment = gold_amr.alignmentsToken2Node(cur +",
"the ending sequence is always [... SHIFT CLOSE] or [... LA(pos,'root') SHIFT CLOSE]",
"gold AMR and the alignment. \"\"\" # Loop over potential actions # NOTE",
"copying lemma and add '01' DEPENDENT(edge,node) : Add a node which is a",
"[] with open(multitask_list) as fid: for line in fid: items = line.strip().split('\\t') if",
"new token return None if machine.tok_cursor < machine.tokseq_len - 1: cur = machine.tok_cursor",
"one by one for sent_idx, gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO: See if",
"# more results than the rank, node in that rank matches, and rank",
"'sentence_tokens': [], 'oracle_actions': [], 'oracle_amr': [], 'rules': { # Will store count of",
"has map if akey not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr # count how",
"node1 = nodes1[0] if len(nodes2) > 1: # get root of subgraph aligned",
"list of entity types that can have pred\" ) args = parser.parse_args() return",
"the root aligned token id is sentence length (not -1) for nid, tids",
"else: action = 'SHIFT' if action == 'SHIFT' and self.multitask_words is not None:",
"copy_lemma_action, multitask_words): self.gold_amr = gold_amr # initialize the state machine self.machine = AMRStateMachine(gold_amr.tokens,",
"if add_unaligned: for i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n in gold_amr.nodes: if n",
"the node has not been built at current step return None # NOTE",
"# below are equivalent # machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions def",
"code gold_amr.alignments[root_id] = [len(gold_amr.tokens)] # NOTE shifted by 1 for AMR alignment return",
"and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) # NOTE this might affect the next DEPEDENT check,",
"named entity check happens first is_dependent = False is_named = False for s,",
"root id is fixed at -1 self.built_gold_nodeids = [] @property def tokens(self): return",
"= gold_amr.findSubGraph(tok_alignment).root # TODO for multiple PREDs, we need to do a for",
"other normalizations should be applied more # transparently print(f'Reading {args.in_amr}') corpus = read_amr(args.in_amr,",
"# check if the alignment is empty # no need since the REDUCE",
"'unprecedented', '.', '<ROOT>']: # if self.time_step >= 8: # breakpoint() action = self.try_reduce()",
"self.machine while not machine.is_closed: valid_actions, invalid_actions = self.get_valid_actions() # for now assert len(valid_actions)",
"check happens first if len(tok_alignment) == 1: gold_nodeid = tok_alignment[0] else: # TODO",
"in machine.entity_tokenids: return None # NOTE currently do not allow multiple ENTITY here",
") # Multiple input parameters parser.add_argument( \"--out-amr\", help=\"corresponding AMR\", type=str ) # parser.add_argument(",
"and ( gold_amr.nodes[root] in entities_with_preds or is_dependent): return None gold_nodeids = [n for",
"% {:s}'.format( num_inconsistent, num_sentences, perc, 'inconsistent labelings from repeated sents' ) print(yellow_font(alert_str)) def",
"self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})' return None def try_entities_with_pred(self): \"\"\" allow pred",
"number of time sentence repeated sentence_count.update([skey]) # hash of AMR labeling akey =",
"[x.split('(')[0] for x in singletons] msg = f'{len(singletons)} singleton actions' print(yellow_font(msg)) print(Counter(base_action_count)) def",
"process_multitask_words( [list(amr.tokens) for amr in gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True ) # run",
"type=str, required=True ) parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument data\", type=str, ) parser.add_argument( \"--out-oracle\", help=\"tokens,",
"= re.compile(r'^PRED\\((.*)\\)$') # Process AMRs one by one for sent_idx, gold_amr in tqdm(enumerate(gold_amrs),",
") parser.add_argument( \"--out-action-stats\", help=\"statistics about actions\", type=str ) parser.add_argument( \"--out-rule-stats\", # TODO this",
"with label COPY_LEMMA : form a new node by copying lemma COPY_SENSE01 :",
"tab separation in actions and sentences by removing whitespaces\" ) # copy lemma",
"machine = self.machine while not machine.is_closed: valid_actions, invalid_actions = self.get_valid_actions() # for now",
"now, as the mapping from ENTITY node is only to the source nodes",
"do PRED(<ROOT>) currently, as the root node is automatically added at the beginning",
"and invalid actions based on the current AMR state machine status and the",
"two tokens (for MWEs) ENTITY(type) : form a named entity, or a subgraph",
"in amr_counts_by_sentence.values() for count in counter.values() ) ) print(yellow_font(alert_str)) if num_labelings > num_unique_sents:",
"num_unique_sents: num_repeated = num_sentences - num_unique_sents perc = num_repeated / num_sentences alert_str =",
"action = self.try_reduce() if not action: action = self.try_merge() #if not action: #",
"cur = machine.tok_cursor nxt = machine.tok_cursor + 1 cur_alignment = gold_amr.alignmentsToken2Node(cur + 1)",
"[n for n in tok_alignment if any(s == n for s, r, t",
"entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action self.multitask_words = multitask_words # TODO deprecate `multitask_words` or change",
"for multi-task if multitask_max_words: assert multitask_max_words assert out_multitask_words # get top words multitask_words",
"None else: return None def try_named_entities(self): \"\"\" Get the named entity sub-sequences one",
"multitask_max_words assert out_multitask_words # get top words multitask_words = get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root",
"range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n in gold_amr.nodes: if n not in gold_amr.alignments or not",
"arcs] LA(pos,':name') \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor tok_alignment",
"use for multi-task\" ) # Labeled shift args parser.add_argument( \"--out-multitask-words\", type=str, help=\"where to",
"ids in the gold AMR graph nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2] if",
"try_merge(self): \"\"\" Check if the next action is MERGE. If 1) the current",
"source nodes in the aligned subgraph altogether. \"\"\" machine = self.machine gold_amr =",
"repetitive edges if arc_name == 'LA': if (node_id, arc_label, act_node_id) in machine.amr.edges: continue",
"probable than rank + 1 len(node_counts) > rank + 1 and node_counts.most_common(rank +",
"zip(sentence_tokens, oracle_actions): # filter actions to remove pointer for action in actions: if",
"= list(set(gold_nodeids)) # just in case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id + 1) # below",
"for multi-task\" ) # Labeled shift args parser.add_argument( \"--out-multitask-words\", type=str, help=\"where to store",
"alignments\", type=str ) # Multiple input parameters parser.add_argument( \"--out-amr\", help=\"corresponding AMR\", type=str )",
"# get the node ids in the gold AMR graph nodes1 = self.nodeid_to_gold_nodeid[node_id1]",
"edges: if r == ':name' and gold_amr.nodes[t] == 'name': entity_edges.append((s, r, t)) name_node_ids.append(t)",
"self.get_arc(act_node_id, node_id) if arc is None: continue arc_name, arc_label = arc # avoid",
"= f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action def try_pred(self): \"\"\" Check if the",
"None if r in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if",
"altogether. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor # to",
"AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words) # build the oracle actions sequence actions = oracle_builder.build_oracle_actions()",
"NOTE to change this behavior, we need to be careful about the root",
"behavior, we need to be careful about the root node id which should",
"machine.tok_cursor # to avoid subgraph ENTITY after named entities if tok_id in machine.entity_tokenids:",
"and r in [':polarity', ':mode']: if (node_id, r) in [(e[0], e[1]) for e",
"self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] # NOTE gold amr root id is fixed at -1",
"# Load/Save words for multi-task if multitask_max_words: assert multitask_max_words assert out_multitask_words # get",
"is on a node that was just constructed 2) there are edges that",
"if s not in self.built_gold_nodeids: new_id = s break if t not in",
"# breakpoint() action = self.try_reduce() if not action: action = self.try_merge() #if not",
"sents (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, max( count for counter",
"== 'name': entity_edges.append((s, r, t)) name_node_ids.append(t) if not name_node_ids: return None for s,",
"combined with pointers for long distance arcs. Actions are SHIFT : move cursor",
"action parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use copy action from Spacy lemmas\" ) # copy",
"rank # results is more probable than rank + 1 len(node_counts) > rank",
"singletons] msg = f'{len(singletons)} singleton actions' print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def yellow_font(string): return",
"entity check happens first is_dependent = False is_named = False for s, r,",
"in gold_nodeids and (t in gold_amr.alignments and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) # NOTE this",
"TODO could there be more than one edges? # currently we only return",
"'01' DEPENDENT(edge,node) : Add a node which is a dependent of the current",
"type=int ) parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma separated list of entity types that",
"if not is_named and ( gold_amr.nodes[root] in entities_with_preds or is_dependent): return None gold_nodeids",
"2) there are edges in the aligned subgraph, and then 3) take the",
"not been built at current step return None #for act_id, act_node_id in enumerate(machine.actions_to_nodes):",
"defaultdict import re from tqdm import tqdm from transition_amr_parser.io import read_propbank, read_amr, write_tokenized_sentences",
"r in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if not is_named",
"the node has not been built at current step return None #for act_id,",
"== 'SHIFT' and self.machine.tok_cursor != self.machine.tokseq_len - 1 : action = 'REDUCE' else:",
"t in edges)] new_nodes = ','.join([gold_amr.nodes[n] for n in gold_nodeids]) action = f'ENTITY({new_nodes})'",
"DEPEDENT check, but is fine if we always use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t)",
"ENTITY('name') PRED('city') [other arcs] LA(pos,':name') b) for two entities with same surface tokens",
"gold_nodeids = gold_amr.alignmentsToken2Node(tok_id + 1) # below is coupled with the PRED checks?",
"elif in_multitask_words: assert not multitask_max_words assert not out_multitask_words # store in file with",
"if singletons: base_action_count = [x.split('(')[0] for x in singletons] msg = f'{len(singletons)} singleton",
"the beginning, so no prediction # for it here; the ending sequence is",
"parser.add_argument( \"--verbose\", action='store_true', help=\"verbose processing\" ) # parser.add_argument( \"--multitask-max-words\", type=int, help=\"number of woprds",
"in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] # NOTE gold amr root id is",
"check if the alignment is empty # no need since the REDUCE check",
"multitask_words: return f'SHIFT({tok})' else: return 'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count = Counter()",
"gold_amr.findSubGraph(tok_alignment).edges if not edges: return None # check if named entity case: (entity_category,",
"= preprocess_amr(gold_amr) # Initialize oracle builder oracle_builder = AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words) #",
"action sequence for the current token sentence, based on the gold AMR and",
"results than the rank, node in that rank matches, and rank # results",
"return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return None else: return None def try_named_entities(self):",
"multiple PREDs, we need to do a for loop here # check if",
"AMRStateMachine, get_spacy_lemmatizer ) \"\"\" This algorithm contains heuristics for generating linearized action sequences",
"tok_alignment[0] else: # TODO check when this happens -> should we do multiple",
"aligned subgraph, whereas for the DEPENDENT we are checking the target nodes in",
"'{:d}/{:d} {:2.1f} % repeated sents (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc,",
"'RA': if (act_node_id, arc_label, node_id) in machine.amr.edges: continue # pointer value arc_pos =",
"== 'name': is_named = True if r in [':polarity', ':mode']: is_dependent = True",
"== 1: gold_nodeid = gold_nodeids[0] else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for s, r, t",
"entity sub-sequences one by one from the current surface token (segments). E.g. a)",
"of woprds to use for multi-task\" ) # Labeled shift args parser.add_argument( \"--out-multitask-words\",",
"\"\"\"Build the oracle action sequence for the current token sentence, based on the",
"help=\"number of woprds to use for multi-task\" ) # Labeled shift args parser.add_argument(",
"1) the aligned node has been predicted already 2) Only for :polarity and",
"gold_amr.findSubGraph(nodes2).root else: node2 = nodes2[0] # find edges for s, r, t in",
"if t not in self.built_gold_nodeids: new_id = t break if new_id != None:",
"the next action is MERGE. If 1) the current and the next token",
"first if len(tok_alignment) == 1: gold_nodeid = tok_alignment[0] else: # TODO check when",
"post-processing \"\"\" use_addnode_rules = True def argument_parser(): parser = argparse.ArgumentParser(description='AMR parser oracle') #",
"in fid: items = line.strip().split('\\t') if len(items) > 2: multitask_words.append(items[1]) return multitask_words def",
"# Multiple input parameters parser.add_argument( \"--out-amr\", help=\"corresponding AMR\", type=str ) # parser.add_argument( \"--verbose\",",
"If 1) the current token is aligned to a single node, or multiple",
"in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is None: continue # for multiple nodes out of",
"gold_amr.token2node_memo = {} # clean invalid alignments: sometimes the alignments are outside of",
"is aligned to a token, indexed by # token node_by_token[token_str].update([node]) return node_by_token def",
"words into one single expression if len(aligned_tokens) > 1: token_str = \" \".join(aligned_tokens)",
"alignments.items(): # join multiple words into one single expression if len(aligned_tokens) > 1:",
"to change this behavior, we need to be careful about the root node",
"{:2.1f} % repeated sents (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, max(",
"to token 2 node2 = gold_amr.findSubGraph(nodes2).root else: node2 = nodes2[0] # find edges",
"action_count = Counter() for tokens, actions in zip(sentence_tokens, oracle_actions): # filter actions to",
"None: action = label_shift(self.machine, self.multitask_words) valid_actions = [action] invalid_actions = [] return valid_actions,",
"self.tokens == ['The', 'cyber', 'attacks', 'were', 'unprecedented', '.', '<ROOT>']: # if self.time_step >=",
"count in counter.values() ) ) print(yellow_font(alert_str)) if num_labelings > num_unique_sents: num_inconsistent = num_labelings",
"self.try_entities_with_pred() if not action: action = self.try_entity() if not action: action = self.try_pred()",
"not in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})' return None def try_entities_with_pred(self): \"\"\"",
"entities that frequently need it i.e. person, thing \"\"\" machine = self.machine gold_amr",
"multitask_words.append(items[1]) return multitask_words def label_shift(state_machine, multitask_words): tok = state_machine.get_current_token(lemma=False) if tok in multitask_words:",
"def alert_inconsistencies(gold_amrs): def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string num_sentences = len(gold_amrs) sentence_count =",
"break # add root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root)) #",
"empty # no need since the REDUCE check happens first if len(tok_alignment) ==",
"\" \".join(amr.tokens) # count number of time sentence repeated sentence_count.update([skey]) # hash of",
"this is slow lemmatizer = get_spacy_lemmatizer() # This will store the oracle stats",
"careful about the root node id which should be -1 now # that",
"XML propbank reader instead of txt reader propbank_args = None if args.in_propbank_args: propbank_args",
"not on the first time on a new token return None tok_id =",
"to prevent same DEPENDENT added twice, as each time we scan all the",
"action in actions: if pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens))",
"perc, max( count for counter in amr_counts_by_sentence.values() for count in counter.values() ) )",
"LA(pos,':name') b) for two entities with same surface tokens ENTITY('name') PRED('city') [other arcs]",
"by oracle\", type=str ) parser.add_argument( \"--out-action-stats\", help=\"statistics about actions\", type=str ) parser.add_argument( \"--out-rule-stats\",",
"oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) == len(oracle_actions) source_lengths = [] target_lengths =",
"# TODO for multiple PREDs, we need to do a for loop here",
"else: return None def try_dependent(self): \"\"\" Check if the next action is DEPENDENT.",
"oracle for the entire corpus stats = run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) # print stats",
"not gold_amr.alignments[n]: if gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)] break # add root",
"import ( AMRStateMachine, get_spacy_lemmatizer ) \"\"\" This algorithm contains heuristics for generating linearized",
"else: action = f'PRED({new_node})' else: action = f'PRED({new_node})' return action return None def",
"subgraph altogether. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor #",
"fine if we always use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge = r[1:] if",
"clean alignments for i, tok in enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i + 1) if",
"if (node_id, arc_label, act_node_id) in machine.amr.edges: continue if arc_name == 'RA': if (act_node_id,",
"cur_alignment or not nxt_alignment: return None # If both tokens are mapped to",
"as a node from the beginning, so no prediction # for it here;",
"token ids natural positive index # setting a token id to -1 will",
"the end; # CLOSE action is internally managed, and treated same as <eos>",
"node_id = machine.current_node_id if node_id is None: # NOTE if node_id could be",
"preprocess_amr(gold_amr) # Initialize oracle builder oracle_builder = AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words) # build",
"for amr in gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True ) # run the oracle",
"we scan all the possible edges continue if t not in gold_nodeids and",
"types/tokens') class AMROracleBuilder: \"\"\"Build AMR oracle for one sentence.\"\"\" def __init__(self, gold_amr, lemmatizer,",
"for generating linearized action sequences for AMR graphs in a rule based way.",
": form a new node by copying lemma and add '01' DEPENDENT(edge,node) :",
"alert_str = '{:d}/{:d} {:2.4f} % inconsistent labelings from repeated sents'.format( num_inconsistent, num_sentences, perc",
"# filter actions to remove pointer for action in actions: if pointer_arc_re.match(action): items",
"= copy_lemma_action self.multitask_words = multitask_words # TODO deprecate `multitask_words` or change for a",
"= AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action self.multitask_words = multitask_words # TODO",
"stats['sentence_tokens'], separator='\\t' ) # State machine stats for this sentence if args.out_rule_stats: with",
"have made all the token ids natural positive index # setting a token",
"return f'{arc_name}({arc_pos},{arc_label})' return None def get_arc(self, node_id1, node_id2): \"\"\" Get the arcs between",
"= '{:d}/{:d} {:2.4f} % {:s}'.format( num_inconsistent, num_sentences, perc, 'inconsistent labelings from repeated sents'",
"node_counts.most_common(rank + 1)[-1][1] > node_counts.most_common(rank + 2)[-1][1] ) ) def sanity_check_amr(gold_amrs): num_sentences =",
"state machine, value: list of node ids in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1]",
"= {} # clean invalid alignments: sometimes the alignments are outside of the",
"gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO: See if we can remove this part",
"pointer value arc_pos = act_id return f'{arc_name}({arc_pos},{arc_label})' return None def get_arc(self, node_id1, node_id2):",
"'.', '<ROOT>']: # if self.time_step >= 8: # breakpoint() action = self.try_reduce() if",
"[] for s, r, t in edges: if r == ':name' and gold_amr.nodes[t]",
"\"--out-multitask-words\", type=str, help=\"where to store top-k words for multi-task\" ) parser.add_argument( \"--in-multitask-words\", type=str,",
"gold_amrs: # hash of sentence skey = \" \".join(amr.tokens) # count number of",
"if t not in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)' if s not",
"is not None: # not on the first time on a new token",
"algorithm is transition-based combined with pointers for long distance arcs. Actions are SHIFT",
"never do PRED(<ROOT>) currently, as the root node is automatically added at the",
"num_repeated, num_sentences, 100 * perc, max( count for counter in amr_counts_by_sentence.values() for count",
"rule based way. The parsing algorithm is transition-based combined with pointers for long",
"potential actions # NOTE \"<ROOT>\" token at last position is added as a",
"\"\"\" Get the arcs between node with `node_id1` and node with `node_id2`. RA",
"# TODO could there be more than one edges? # currently we only",
"def try_arcs(self): \"\"\" Get the arcs that involve the current token aligned node.",
"Add root regardless allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words, add_root=False):",
"currently is on a node that was just constructed 2) there are edges",
"the node ids in the gold AMR graph nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2 =",
"1) # below is coupled with the PRED checks? and also the ENTITY",
"multiple PREDs if gold_nodeid not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid]",
"amr.edges]) edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count = Counter([w for amr in",
"return self.machine.time_step @property def actions(self): return self.machine.actions def get_valid_actions(self): \"\"\"Get the valid actions",
"the next action is DEPENDENT. If 1) the aligned node has been predicted",
"return action return None def try_arcs(self): \"\"\" Get the arcs that involve the",
"from the beginning, so no prediction # for it here; the ending sequence",
"See if we can remove this part gold_amr = gold_amr.copy() gold_amr = preprocess_amr(gold_amr)",
"# sanity check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load propbank if provided # TODO:",
"add_unaligned=None, included_unaligned=None, root_id=-1): # clean alignments for i, tok in enumerate(gold_amr.tokens): align =",
"for k in action_count.keys()])) print('Most frequent actions:') print(action_count.most_common(10)) if singletons: base_action_count = [x.split('(')[0]",
"# TODO check when this happens -> should we do multiple PRED? gold_nodeid",
"data reading process # TODO and fix that and remove this cleaning process",
"open(multitask_list) as fid: for line in fid: items = line.strip().split('\\t') if len(items) >",
"# check if named entity case: (entity_category, ':name', 'name') # no need, since",
"None: # NOTE if node_id could be 0, 'if not node_id' would cause",
"def build_oracle_actions(self): \"\"\"Build the oracle action sequence for the current token sentence, based",
"base_action_count = [x.split('(')[0] for x in singletons] msg = f'{len(singletons)} singleton actions' print(yellow_font(msg))",
"action = f'DEPENDENT({new_node},{new_edge})' return action return None def try_arcs(self): \"\"\" Get the arcs",
"gold_amr.alignmentsToken2Node(nxt + 1) if not cur_alignment or not nxt_alignment: return None # If",
"would cause a bug # the node has not been built at current",
"e in machine.amr.edges]: # to prevent same DEPENDENT added twice, as each time",
"been built with this node \"\"\" machine = self.machine node_id = machine.current_node_id if",
"the entire corpus stats = run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) # print stats about actions",
"node that was just constructed 2) there are edges that have not been",
"aligned subgraph altogether. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor",
"type=str, help=\"where to read top-k words for multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid",
"out of one token --> need to use node id to check edges",
"sents'.format( num_inconsistent, num_sentences, perc ) print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words = [] with open(multitask_list)",
"left arc to the current node from the previous node at location pos",
"# ['Among', 'common', 'birds', ',', 'a', 'rather', 'special', 'one', 'is', # 'the', 'black',",
"gold_nodeids]) action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action def try_pred(self): \"\"\" Check",
"a new node by copying lemma and add '01' DEPENDENT(edge,node) : Add a",
"alert_str = '{:d}/{:d} {:2.4f} % {:s}'.format( num_inconsistent, num_sentences, perc, 'inconsistent labelings from repeated",
"try_reduce(self): \"\"\" Check if the next action is REDUCE. If 1) there is",
"#if not action: # action = self.try_dependent() if not action: action = self.try_arcs()",
"'black', '-', 'faced', 'spoonbill', '.'] # TODO if not dealt with, this causes",
"root node id which should be -1 now # that is also massively",
"= tok_alignment[0] else: # TODO check when this happens -> should we do",
"('RA', r) if node1 == t and node2 == s: return ('LA', r)",
"on the current AMR state machine status and the gold AMR.\"\"\" # find",
"(figure out) 2) the aligned node has not been predicted yet \"\"\" machine",
"allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words, add_root=False): # Load/Save words for multi-task if",
"True if r in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if",
"sentences from --in-amr\", type=str ) parser.add_argument( \"--out-actions\", help=\"actions given by oracle\", type=str )",
"tok in enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i + 1) if len(align) == 2: edges",
"allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words, add_root=False): # Load/Save words",
"1: # never do PRED(<ROOT>) currently, as the root node is automatically added",
"\"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab separation in actions and sentences by removing whitespaces\" )",
"# hash of AMR labeling akey = amr.toJAMRString() # store different amr labels",
"= list(amr_by_amrkey_by_sentence[skey].values()) # inform user if num_sentences > num_unique_sents: num_repeated = num_sentences -",
"= self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor node_id = machine.current_node_id if node_id",
"= Counter([ n for amr in amrs for n in amr.nodes.values() ]) node_tokens",
"return None # NOTE currently do not allow multiple ENTITY here on a",
"arc_name, arc_label = arc # avoid repetitive edges if arc_name == 'LA': if",
"of inputs matter. (could also change to follow strict orders between these 2",
"cause a bug # the node has not been built at current step",
"name_node_ids.append(t) if not name_node_ids: return None for s, r, t in entity_edges: if",
"machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions def try_reduce(self): \"\"\" Check if the",
"AMR (replace some unicode characters) # TODO: unicode fixes and other normalizations should",
"None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment empty (or singleton)",
"bug # the node has not been built at current step return None",
"named entity sub-sequences one by one from the current surface token (segments). E.g.",
"edge with the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None",
"for the first unaligned node # whose label is in `included_unaligned` to align",
"':mode']: if (node_id, r) in [(e[0], e[1]) for e in machine.amr.edges]: # to",
"0) -> for DEPENDENT missing # if self.tokens == ['The', 'cyber', 'attacks', 'were',",
"act_node_id in enumerate(machine.actions_to_nodes): for act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is None: continue",
"this # append a special token at the end of the sentence for",
"machine.entity_tokenids: return None # NOTE currently do not allow multiple ENTITY here on",
"num_inconsistent, num_sentences, perc ) print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words = [] with open(multitask_list) as",
"amr in amrs for t in amr.edges]) edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens')",
"continue if t not in gold_nodeids and (t in gold_amr.alignments and gold_amr.alignments[t]): continue",
"(starting from 0) -> for DEPENDENT missing # if self.tokens == ['The', 'cyber',",
"# add root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root)) # gold_amr.alignments[root_id]",
"num_sentences alert_str = '{:d}/{:d} {:2.4f} % inconsistent labelings from repeated sents'.format( num_inconsistent, num_sentences,",
"edge_label_count = Counter([t[1] for amr in amrs for t in amr.edges]) edge_tokens =",
"action else: return None def try_dependent(self): \"\"\" Check if the next action is",
"all the possible edges continue if t not in gold_nodeids and (t in",
"gold_amr.copy() gold_amr = preprocess_amr(gold_amr) # Initialize oracle builder oracle_builder = AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action,",
"top words multitask_words = get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root ) # store in file",
"read/write multi-task (labeled shift) action # TODO: Add conditional if here multitask_words =",
"PRED('city') [other arcs] LA(pos,':name') PRED('city') [other arcs] LA(pos,':name') c) for two entities with",
"== machine.tokseq_len - 1: # never do PRED(<ROOT>) currently, as the root node",
"and 2) there are edges in the aligned subgraph, and then 3) take",
"COPY_LEMMA, COPY_SENSE01. If 1) the current token is aligned to a single node,",
"subgraph # gold_nodeids = self.nodeid_to_gold_nodeid[node_id] # gold_nodeids = list(set(gold_nodeids)) # just in case",
"\"--out-actions\", help=\"actions given by oracle\", type=str ) parser.add_argument( \"--out-action-stats\", help=\"statistics about actions\", type=str",
"print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count = Counter([t[1] for amr in amrs for t in",
"def try_merge(self): \"\"\" Check if the next action is MERGE. If 1) the",
"= {} # key: node id in the state machine, value: list of",
"return action else: return None def try_dependent(self): \"\"\" Check if the next action",
"have not been built with this node \"\"\" machine = self.machine node_id =",
"one. \"\"\" gold_amr = self.gold_amr # get the node ids in the gold",
"special token at the end of the sentence for the first unaligned node",
"form a left arc to the current node from the previous node at",
"gold_amr.edges: if node1 == s and node2 == t: return ('RA', r) if",
"sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda: Counter()) for amr in",
"= self.gold_amr tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if",
"token id is sentence length (not -1) for nid, tids in gold_amr.alignments.items(): gold_amr.alignments[nid]",
"def label_shift(state_machine, multitask_words): tok = state_machine.get_current_token(lemma=False) if tok in multitask_words: return f'SHIFT({tok})' else:",
"a new token return None tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1)",
"the oracle stats statistics = { 'sentence_tokens': [], 'oracle_actions': [], 'oracle_amr': [], 'rules':",
"number of time a node is aligned to a token, indexed by #",
"boundary # TODO check why this happens in the data reading process #",
"not multitask_max_words assert not out_multitask_words # store in file with open(in_multitask_words) as fid:",
"# clean invalid alignments: sometimes the alignments are outside of the sentence boundary",
"1 len(node_counts) > rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node and",
"#if not action: # action = self.try_named_entities() if not action: action = self.try_entities_with_pred()",
"action = self.try_entities_with_pred() if not action: action = self.try_entity() if not action: action",
"within node-arc actions, arc subsequence comes highest, then named entity subsequence, etc. #",
"= machine.tok_cursor nxt = machine.tok_cursor + 1 cur_alignment = gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment",
"if gold_amr.nodes[root] not in entities_with_preds and not is_dependent: return None new_id = None",
"actions = oracle_builder.build_oracle_actions() # store data statistics['sentence_tokens'].append(oracle_builder.tokens) # do not write CLOSE action",
"long distance arcs. Actions are SHIFT : move cursor to next position in",
"= self.try_dependent() if not action: action = self.try_arcs() #if not action: # action",
"None gold_nodeids = [n for n in tok_alignment if any(s == n for",
"tokens (for MWEs) ENTITY(type) : form a named entity, or a subgraph PRED(label)",
"','.join([gold_amr.nodes[n] for n in gold_nodeids]) action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action",
"the source nodes in the # aligned subgraph, whereas for the DEPENDENT we",
"tid <= len(gold_amr.tokens)] # TODO: describe this # append a special token at",
"for the entire corpus stats = run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) # print stats about",
"of time a node is aligned to a token, indexed by # token",
"sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) == len(oracle_actions) source_lengths = [] target_lengths",
"sequence REDUCE : delete current token MERGE : merge two tokens (for MWEs)",
"delete current token MERGE : merge two tokens (for MWEs) ENTITY(type) : form",
"= [-1] # NOTE gold amr root id is fixed at -1 self.built_gold_nodeids",
"edges if arc_name == 'LA': if (node_id, arc_label, act_node_id) in machine.amr.edges: continue if",
"copy_lemma_action, multitask_words): # Initialize lemmatizer as this is slow lemmatizer = get_spacy_lemmatizer() #",
"different amr labels for same sent, keep has map if akey not in",
") parser.add_argument( \"--out-rule-stats\", # TODO this is accessed by replacing '-' to '_'",
"TODO check when this happens -> should we do multiple PRED? gold_nodeid =",
"fid: multitask_words = [line.strip() for line in fid.readlines()] else: multitask_words = None return",
"parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all addnode actions appearing less times than count\", type=int )",
"\"\"\"Build AMR oracle for one sentence.\"\"\" def __init__(self, gold_amr, lemmatizer, copy_lemma_action, multitask_words): self.gold_amr",
"# for now assert len(valid_actions) == 1, \"Oracle must be deterministic\" assert len(invalid_actions)",
"arc_label, act_node_id) in machine.amr.edges: continue if arc_name == 'RA': if (act_node_id, arc_label, node_id)",
"= '{:d}/{:d} {:2.1f} % repeated sents (max {:d} times)'.format( num_repeated, num_sentences, 100 *",
"(could also change to follow strict orders between these 2 ids) # TODO",
"count of PREDs given pointer position 'possible_predicates': defaultdict(lambda: Counter()) } } pred_re =",
"data, when the sentence is # ['Among', 'common', 'birds', ',', 'a', 'rather', 'special',",
"\"root\", gold_amr.root)) # gold_amr.alignments[root_id] = [-1] # NOTE do not do this; we",
"s, r, t in edges)] new_nodes = ','.join([gold_amr.nodes[n] for n in gold_nodeids]) action",
") \"\"\" This algorithm contains heuristics for generating linearized action sequences for AMR",
"= [len(gold_amr.tokens)] break # add root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id, \"root\",",
"machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor # to avoid subgraph",
"return ('LA', r) return None def run_oracle(gold_amrs, copy_lemma_action, multitask_words): # Initialize lemmatizer as",
"\"--out-rule-stats\", # TODO this is accessed by replacing '-' to '_' help=\"statistics about",
"on a single token if machine.current_node_id in machine.entities: return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id",
"# for multiple nodes out of one token --> need to use node",
"than count\", type=int ) parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma separated list of entity",
"machine.current_node_id if node_id is None: # NOTE if node_id could be 0, 'if",
"same sent, keep has map if akey not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr",
"':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not in entities_with_preds and",
"t in gold_amr.edges if s in align and t in align ] if",
"`add_unaligned` times if add_unaligned: for i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n in gold_amr.nodes:",
"if we can remove this part gold_amr = gold_amr.copy() gold_amr = preprocess_amr(gold_amr) #",
"matter. (could also change to follow strict orders between these 2 ids) #",
"is internally managed, and treated same as <eos> in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) #",
"stats for this sentence if args.out_rule_stats: with open(args.out_rule_stats, 'w') as fid: fid.write(json.dumps(stats['rules'])) if",
"below is coupled with the PRED checks? and also the ENTITY if len(gold_nodeids)",
"results is more probable than rank + 1 len(node_counts) > rank + 1",
"add '01' DEPENDENT(edge,node) : Add a node which is a dependent of the",
"sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) > 1: pass # There is more",
"= aligned_tokens[0] node = train_amr.nodes[node_id] # count number of time a node is",
"node_by_token[token_str].update([node]) return node_by_token def is_most_common(node_counts, node, rank=0): return ( ( # as many",
"id in the state machine, value: list of node ids in gold AMR",
"corpus.amrs # sanity check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load propbank if provided #",
"return multitask_words def label_shift(state_machine, multitask_words): tok = state_machine.get_current_token(lemma=False) if tok in multitask_words: return",
"False for s, r, t in edges: if r == ':name' and gold_amr.nodes[t]",
"# TODO and fix that and remove this cleaning process # an example",
"= oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics def main(): # Argument handling args = argument_parser()",
"# initialize the state machine self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action =",
"one edges? # currently we only return the first one. \"\"\" gold_amr =",
"defaultdict(lambda: Counter()) } } pred_re = re.compile(r'^PRED\\((.*)\\)$') # Process AMRs one by one",
"return None # If both tokens are mapped to same node or overlap",
"arcs] LA(pos,':name') b) for two entities with same surface tokens ENTITY('name') PRED('city') [other",
"action = valid_actions[0] # update the machine machine.apply_action(action) # close machine # below",
"self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor # to avoid subgraph ENTITY after",
"(node_id, arc_label, act_node_id) in machine.amr.edges: continue if arc_name == 'RA': if (act_node_id, arc_label,",
"single node, or multiple nodes? (figure out) 2) the aligned node has not",
"# 'the', 'black', '-', 'faced', 'spoonbill', '.'] # TODO if not dealt with,",
"def run_oracle(gold_amrs, copy_lemma_action, multitask_words): # Initialize lemmatizer as this is slow lemmatizer =",
"['Among', 'common', 'birds', ',', 'a', 'rather', 'special', 'one', 'is', # 'the', 'black', '-',",
"new_node = gold_amr.nodes[new_id] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node: action",
"than the rank, node in that rank matches, and rank # results is",
"graph nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1, list): nodes1 =",
"token node_by_token[token_str].update([node]) return node_by_token def is_most_common(node_counts, node, rank=0): return ( ( # as",
"= len(sentence_count) num_labelings = 0 for skey, sent_count in sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey])",
"# NOTE we make all token ids positive natural index # check if",
"for w in amr.tokens]) word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class AMROracleBuilder: \"\"\"Build",
"action = 'REDUCE' else: action = 'SHIFT' if action == 'SHIFT' and self.multitask_words",
"c in action_count.items() if c == 1] print('Base actions:') print(Counter([k.split('(')[0] for k in",
"for it here; the ending sequence is always [... SHIFT CLOSE] or [...",
"fid: for line in fid: items = line.strip().split('\\t') if len(items) > 2: multitask_words.append(items[1])",
"or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ): remove = 0 gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo =",
"edges: return None # check if named entity case: (entity_category, ':name', 'name') #",
"next action is DEPENDENT. If 1) the aligned node has been predicted already",
"return None # NOTE this doesn't work for ENTITY now, as the mapping",
"Thus the order of inputs matter. (could also change to follow strict orders",
"write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine, get_spacy_lemmatizer ) \"\"\" This algorithm contains heuristics",
"nodes? (figure out) 2) the aligned node has not been predicted yet \"\"\"",
"id 459 (starting from 0) -> for DEPENDENT missing # if self.tokens ==",
"len(node_counts) == rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node ) or",
"and (t in gold_amr.alignments and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) # NOTE this might affect",
"there are edges in the aligned subgraph, and then 3) take the source",
") ) print(yellow_font(alert_str)) if num_labelings > num_unique_sents: num_inconsistent = num_labelings - num_unique_sents perc",
"8: # breakpoint() action = self.try_reduce() if not action: action = self.try_merge() #if",
"if len(gold_nodeids) == 1: gold_nodeid = gold_nodeids[0] else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for s,",
"the root node is automatically added at the beginning # NOTE to change",
"lemmatizer as this is slow lemmatizer = get_spacy_lemmatizer() # This will store the",
"time_step(self): return self.machine.time_step @property def actions(self): return self.machine.actions def get_valid_actions(self): \"\"\"Get the valid",
"if args.out_rule_stats: with open(args.out_rule_stats, 'w') as fid: fid.write(json.dumps(stats['rules'])) if __name__ == '__main__': main()",
"-1 will break the code gold_amr.alignments[root_id] = [len(gold_amr.tokens)] # NOTE shifted by 1",
"return None #for act_id, act_node_id in enumerate(machine.actions_to_nodes): for act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if",
"Use here XML propbank reader instead of txt reader propbank_args = None if",
"self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})' return None def try_entities_with_pred(self): \"\"\" allow pred inside entities",
"propbank_args = read_propbank(args.in_propbank_args) # read/write multi-task (labeled shift) action # TODO: Add conditional",
"built at current step return None # NOTE this doesn't work for ENTITY",
"with open(multitask_list) as fid: for line in fid: items = line.strip().split('\\t') if len(items)",
"pred_re = re.compile(r'^PRED\\((.*)\\)$') # Process AMRs one by one for sent_idx, gold_amr in",
"num_sentences, 100 * perc, max( count for counter in amr_counts_by_sentence.values() for count in",
"'COPY_SENSE01' else: action = f'PRED({new_node})' else: action = f'PRED({new_node})' return action return None",
"action == 'SHIFT' and self.multitask_words is not None: action = label_shift(self.machine, self.multitask_words) valid_actions",
"= act_id return f'{arc_name}({arc_pos},{arc_label})' return None def get_arc(self, node_id1, node_id2): \"\"\" Get the",
"= valid_actions[0] # update the machine machine.apply_action(action) # close machine # below are",
"to token 1 node1 = gold_amr.findSubGraph(nodes1).root else: node1 = nodes1[0] if len(nodes2) >",
"if gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)] break # add root node gold_amr.tokens.append(\"<ROOT>\")",
"is added as a node from the beginning, so no prediction # for",
"AMROracleBuilder: \"\"\"Build AMR oracle for one sentence.\"\"\" def __init__(self, gold_amr, lemmatizer, copy_lemma_action, multitask_words):",
"nodes in the # aligned subgraph, whereas for the DEPENDENT we are checking",
"of subgraph aligned to token 1 node1 = gold_amr.findSubGraph(nodes1).root else: node1 = nodes1[0]",
"new node by copying lemma COPY_SENSE01 : form a new node by copying",
"work for ENTITY now, as the mapping from ENTITY node is only to",
"twice, as each time we scan all the possible edges continue if t",
"node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count = Counter([t[1] for amr in amrs",
"time sentence repeated sentence_count.update([skey]) # hash of AMR labeling akey = amr.toJAMRString() #",
"else: node2 = nodes2[0] # find edges for s, r, t in gold_amr.edges:",
"avoid subgraph ENTITY after named entities if tok_id in machine.entity_tokenids: return None #",
"action='store_true', help=\"verbose processing\" ) # parser.add_argument( \"--multitask-max-words\", type=int, help=\"number of woprds to use",
"':name' and gold_amr.nodes[t] == 'name': return None if r in [':polarity', ':mode']: is_dependent",
"will store the oracle stats statistics = { 'sentence_tokens': [], 'oracle_actions': [], 'oracle_amr':",
"sentence id 459 (starting from 0) -> for DEPENDENT missing # if self.tokens",
"return None def try_entities_with_pred(self): \"\"\" allow pred inside entities that frequently need it",
"for the current token sentence, based on the gold AMR and the alignment.",
"# read/write multi-task (labeled shift) action # TODO: Add conditional if here multitask_words",
"by 1 for AMR alignment return gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of alignments",
"to more than 1 nodes, and 2) there are edges in the aligned",
"\"\"\"Get statistics of alignments between nodes and surface words\"\"\" node_by_token = defaultdict(lambda: Counter())",
"] if not edges: remove = 1 if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) >",
"invalid_actions = [] return valid_actions, invalid_actions def build_oracle_actions(self): \"\"\"Build the oracle action sequence",
"= self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1)",
"tok_id = machine.tok_cursor # to avoid subgraph ENTITY after named entities if tok_id",
"help=\"AMR notation in LDC format\", type=str, required=True ) parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument data\",",
"priority # e.g. within node-arc actions, arc subsequence comes highest, then named entity",
"+ 1) if len(align) == 2: edges = [ (s, r, t) for",
"self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node = gold_amr.nodes[new_id] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma ==",
"- num_unique_sents perc = num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % {:s}",
"the rank and node in that rank matches len(node_counts) == rank + 1",
"None # NOTE currently do not allow multiple ENTITY here on a single",
"# TODO: unicode fixes and other normalizations should be applied more # transparently",
"conditional if here multitask_words = process_multitask_words( [list(amr.tokens) for amr in gold_amrs], args.multitask_max_words, args.in_multitask_words,",
"accessed by replacing '-' to '_' help=\"statistics about alignments\", type=str ) # Multiple",
"less times than count\", type=int ) parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma separated list",
"@property def actions(self): return self.machine.actions def get_valid_actions(self): \"\"\"Get the valid actions and invalid",
"words for multi-task\" ) parser.add_argument( \"--in-multitask-words\", type=str, help=\"where to read top-k words for",
"= self.gold_amr tok_id = machine.tok_cursor # to avoid subgraph ENTITY after named entities",
"amr in gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True ) # run the oracle for",
"if s not in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})' return None def",
"= [] def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1): # clean alignments for i, tok",
"case: (entity_category, ':name', 'name') entity_edges = [] name_node_ids = [] for s, r,",
"= [-1] # NOTE do not do this; we have made all the",
"if arc is None: continue arc_name, arc_label = arc # avoid repetitive edges",
"node, rank=0): return ( ( # as many results as the rank and",
"'SHIFT' if action == 'SHIFT' and self.multitask_words is not None: action = label_shift(self.machine,",
"for x in sentence]) # Restrict to top-k words allowed_words = dict(list(sorted( word_count.items(),",
"# update the machine machine.apply_action(action) # close machine # below are equivalent #",
"None: # not on the first time on a new token return None",
"for train_amr in gold_amrs_train: # Get alignments alignments = defaultdict(list) for i in",
"[other arcs] LA(pos,':name') b) for two entities with same surface tokens ENTITY('name') PRED('city')",
"token id to -1 will break the code gold_amr.alignments[root_id] = [len(gold_amr.tokens)] # NOTE",
"been built at current step return None #for act_id, act_node_id in enumerate(machine.actions_to_nodes): for",
"== 'SHIFT' and self.multitask_words is not None: action = label_shift(self.machine, self.multitask_words) valid_actions =",
"{:d} times)'.format( num_repeated, num_sentences, 100 * perc, max( count for counter in amr_counts_by_sentence.values()",
"b) for two entities with same surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name')",
"= sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count = Counter([t[1] for amr in amrs for",
"action_count.items() if c == 1] print('Base actions:') print(Counter([k.split('(')[0] for k in action_count.keys()])) print('Most",
"required=True ) parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument data\", type=str, ) parser.add_argument( \"--out-oracle\", help=\"tokens, AMR",
"gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root)) # gold_amr.alignments[root_id] = [-1] # NOTE do",
"instead of txt reader propbank_args = None if args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args) #",
"= self.try_reduce() if not action: action = self.try_merge() #if not action: # action",
"# store different amr labels for same sent, keep has map if akey",
"natural positive index # setting a token id to -1 will break the",
"node ) or ( # more results than the rank, node in that",
"for multiple PREDs if gold_nodeid not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node =",
"s, r, t in gold_amr.edges if s in align and t in align",
"build the oracle actions sequence actions = oracle_builder.build_oracle_actions() # store data statistics['sentence_tokens'].append(oracle_builder.tokens) #",
"parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma separated list of entity types that can have",
"num_unique_sents perc = num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % {:s}'.format( num_inconsistent,",
") # run the oracle for the entire corpus stats = run_oracle(gold_amrs, args.copy_lemma_action,",
"with two surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') ENTITY('name') PRED('city') [other arcs]",
"NOTE currently do not allow multiple ENTITY here on a single token if",
"gold_nodeids = list(set(gold_nodeids)) # just in case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id + 1) #",
"== 'name': return None if r in [':polarity', ':mode']: is_dependent = True root",
"so no prediction # for it here; the ending sequence is always [...",
"arcs between node with `node_id1` and node with `node_id2`. RA if there is",
"'ENTITY(name)' if s not in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})' return None",
"# the node has not been built at current step return None #",
"only to the source nodes in the # aligned subgraph, whereas for the",
"here; the ending sequence is always [... SHIFT CLOSE] or [... LA(pos,'root') SHIFT",
"in_multitask_words: assert not multitask_max_words assert not out_multitask_words # store in file with open(in_multitask_words)",
"LA(pos,':name') c) for two entities with two surface tokens ENTITY('name') PRED('city') [other arcs]",
"or not nodes2: return None # convert to single node aligned to each",
"if not nodes1 or not nodes2: return None # convert to single node",
"c == 1] print('Base actions:') print(Counter([k.split('(')[0] for k in action_count.keys()])) print('Most frequent actions:')",
"sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class AMROracleBuilder: \"\"\"Build AMR oracle for one sentence.\"\"\" def",
"check when this happens -> should we do multiple PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root",
"amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr # count how many time each hash appears amr_counts_by_sentence[skey].update([akey])",
"a dependent of the current node LA(pos,label) : form a left arc from",
"ids in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] # NOTE gold amr root id",
"alignment is empty # no need since the REDUCE check happens first if",
"None def run_oracle(gold_amrs, copy_lemma_action, multitask_words): # Initialize lemmatizer as this is slow lemmatizer",
"also massively used in postprocessing to find/add root. return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id",
"{:s}'.format( num_inconsistent, num_sentences, perc, 'inconsistent labelings from repeated sents' ) print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens,",
"in edges: if r == ':name' and gold_amr.nodes[t] == 'name': entity_edges.append((s, r, t))",
"# currently we only return the first one. \"\"\" gold_amr = self.gold_amr #",
"is_named = True if r in [':polarity', ':mode']: is_dependent = True root =",
"f'PRED({new_node})' else: action = f'PRED({new_node})' return action else: return None def try_dependent(self): \"\"\"",
"'name': return None if r in [':polarity', ':mode']: is_dependent = True root =",
"n for s, r, t in edges)] new_nodes = ','.join([gold_amr.nodes[n] for n in",
"t not in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)' if s not in",
"and t in align ] if not edges: remove = 1 if (",
"dev set, sentence id 459 (starting from 0) -> for DEPENDENT missing #",
"not in self.built_gold_nodeids: new_id = s break if t not in self.built_gold_nodeids: new_id",
"# Process AMRs one by one for sent_idx, gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'): #",
"'rather', 'special', 'one', 'is', # 'the', 'black', '-', 'faced', 'spoonbill', '.'] # TODO",
"= self.try_merge() #if not action: # action = self.try_dependent() if not action: action",
"'-' to '_' help=\"statistics about alignments\", type=str ) # Multiple input parameters parser.add_argument(",
"AMR labeling akey = amr.toJAMRString() # store different amr labels for same sent,",
"yellow_font(string): return \"\\033[93m%s\\033[0m\" % string num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence =",
"cur_alignment == nxt_alignment: return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return None else: return",
"all addnode actions appearing less times than count\", type=int ) parser.add_argument( \"--in-pred-entities\", type=str,",
"len(items) > 2: multitask_words.append(items[1]) return multitask_words def label_shift(state_machine, multitask_words): tok = state_machine.get_current_token(lemma=False) if",
"True root = gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not in entities_with_preds and not is_dependent: return",
"use node id to check edges arc = self.get_arc(act_node_id, node_id) if arc is",
"args = parser.parse_args() return args def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string entities_with_preds =",
"= machine.tok_cursor if tok_id == machine.tokseq_len - 1: # never do PRED(<ROOT>) currently,",
"'rules': { # Will store count of PREDs given pointer position 'possible_predicates': defaultdict(lambda:",
"the previous node at location pos CLOSE : complete AMR, run post-processing \"\"\"",
"return None def try_dependent(self): \"\"\" Check if the next action is DEPENDENT. If",
"# e.g. within node-arc actions, arc subsequence comes highest, then named entity subsequence,",
"PREDs given pointer position 'possible_predicates': defaultdict(lambda: Counter()) } } pred_re = re.compile(r'^PRED\\((.*)\\)$') #",
"help=\"tokens, AMR notation and actions given by oracle\", type=str ) parser.add_argument( \"--out-sentences\", help=\"tokenized",
"{} # key: node id in the state machine, value: list of node",
"just constructed 2) there are edges that have not been built with this",
"count number of time sentence repeated sentence_count.update([skey]) # hash of AMR labeling akey",
"parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use copy action from Spacy lemmas\" ) # copy lemma",
"not isinstance(nodes1, list): nodes1 = [nodes1] if not isinstance(nodes2, list): nodes2 = [nodes2]",
"f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action def try_pred(self): \"\"\" Check if the next",
"gold_amr.tokens.append(\"<unaligned>\") for n in gold_amr.nodes: if n not in gold_amr.alignments or not gold_amr.alignments[n]:",
"node has been constructed, for multiple PREDs if gold_nodeid not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid)",
"/ num_sentences alert_str = '{:d}/{:d} {:2.4f} % {:s}'.format( num_inconsistent, num_sentences, perc, 'inconsistent labelings",
"LA(pos,':name') \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor tok_alignment =",
"normalizations should be applied more # transparently print(f'Reading {args.in_amr}') corpus = read_amr(args.in_amr, unicode_fixes=True)",
"for same sent, keep has map if akey not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] =",
"subgraph ENTITY after named entities if tok_id in machine.entity_tokenids: return None # NOTE",
"location pos CLOSE : complete AMR, run post-processing \"\"\" use_addnode_rules = True def",
"c) for two entities with two surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name')",
"< machine.tokseq_len - 1: cur = machine.tok_cursor nxt = machine.tok_cursor + 1 cur_alignment",
"def try_entity(self): \"\"\" Check if the next action is ENTITY. TryENTITY before tryPRED.",
"more probable than rank + 1 len(node_counts) > rank + 1 and node_counts.most_common(rank",
"try_pred(self): \"\"\" Check if the next action is PRED, COPY_LEMMA, COPY_SENSE01. If 1)",
"get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count = Counter() for sentence in tokenized_corpus: word_count.update([x for x",
"break the code gold_amr.alignments[root_id] = [len(gold_amr.tokens)] # NOTE shifted by 1 for AMR",
"print(f'Reading {args.in_amr}') corpus = read_amr(args.in_amr, unicode_fixes=True) gold_amrs = corpus.amrs # sanity check AMRS",
"gold_amr = self.gold_amr if machine.current_node_id is not None: # not on the first",
"arc to the current node from the previous node at location pos CLOSE",
"in entities_with_preds or is_dependent): return None gold_nodeids = [n for n in tok_alignment",
"count how many time each hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count) num_labelings =",
"AMR construction states info self.nodeid_to_gold_nodeid = {} # key: node id in the",
": form a left arc to the current node from the previous node",
"the data reading process # TODO and fix that and remove this cleaning",
"gold_amr.alignments[n] = [len(gold_amr.tokens)] break # add root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id,",
"1) # check if alignment empty (or singleton) if len(tok_alignment) <= 1: return",
"actions in zip(sentence_tokens, oracle_actions): # filter actions to remove pointer for action in",
") # store in file with open(out_multitask_words, 'w') as fid: for word in",
"orders between these 2 ids) # TODO could there be more than one",
"= [action] invalid_actions = [] return valid_actions, invalid_actions def build_oracle_actions(self): \"\"\"Build the oracle",
"the sentence for the first unaligned node # whose label is in `included_unaligned`",
"for tokens, actions in zip(sentence_tokens, oracle_actions): # filter actions to remove pointer for",
"if len(aligned_tokens) > 1: token_str = \" \".join(aligned_tokens) else: token_str = aligned_tokens[0] node",
"CLOSE] machine = self.machine while not machine.is_closed: valid_actions, invalid_actions = self.get_valid_actions() # for",
"f'{len(singletons)} singleton actions' print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string",
"node to the previous node at location pos RA(pos,label) : form a left",
"labelings from repeated sents' ) print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert",
"r, t in edges: if r == ':name' and gold_amr.nodes[t] == 'name': is_named",
"self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma",
"else r new_node = gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})' return action return None def",
"assert multitask_max_words assert out_multitask_words # get top words multitask_words = get_multitask_actions( multitask_max_words, tokenized_corpus,",
"isinstance(nodes2, list): nodes2 = [nodes2] if not nodes1 or not nodes2: return None",
"nodes1 or not nodes2: return None # convert to single node aligned to",
"Will store count of PREDs given pointer position 'possible_predicates': defaultdict(lambda: Counter()) } }",
"actions appearing less times than count\", type=int ) parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma",
"actions\" action = valid_actions[0] # update the machine machine.apply_action(action) # close machine #",
"gold_amr = self.gold_amr # get the node ids in the gold AMR graph",
"NOTE if node_id could be 0, 'if not node_id' would cause a bug",
"edges: return None is_dependent = False for s, r, t in edges: if",
"postprocessing to find/add root. return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE",
"# NOTE if node_id could be 0, 'if not node_id' would cause a",
"len(tok_alignment) <= 1: return None # check if there is any edge with",
"{} # clean invalid alignments: sometimes the alignments are outside of the sentence",
"rank matches, and rank # results is more probable than rank + 1",
"num_sentences - num_unique_sents perc = num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} %",
"if machine.current_node_id is not None: # not on the first time on a",
"multitask_words = process_multitask_words( [list(amr.tokens) for amr in gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True )",
"repeat `add_unaligned` times if add_unaligned: for i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n in",
"current step return None # NOTE this doesn't work for ENTITY now, as",
"predicted yet \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor if",
"at the beginning # NOTE to change this behavior, we need to be",
"if num_sentences > num_unique_sents: num_repeated = num_sentences - num_unique_sents perc = num_repeated /",
"= None return multitask_words def print_corpus_info(amrs): # print some info print(f'{len(amrs)} sentences') node_label_count",
"not action: action = self.try_entity() if not action: action = self.try_pred() if not",
"Spacy lemmas\" ) # copy lemma action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all addnode actions",
"CLOSE action at the end; # CLOSE action is internally managed, and treated",
"word_count = Counter() for sentence in tokenized_corpus: word_count.update([x for x in sentence]) #",
"Add a node which is a dependent of the current node LA(pos,label) :",
"separator='\\t' ) # State machine stats for this sentence if args.out_rule_stats: with open(args.out_rule_stats,",
"+ 1) gold_amr.token2node_memo = {} # clean invalid alignments: sometimes the alignments are",
"return f'SHIFT({tok})' else: return 'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count = Counter() for",
"for i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n in gold_amr.nodes: if n not in",
"action: action = self.try_merge() #if not action: # action = self.try_dependent() if not",
"no need, since named entity check happens first is_dependent = False is_named =",
"x in sentence]) # Restrict to top-k words allowed_words = dict(list(sorted( word_count.items(), key=lambda",
"None: continue # for multiple nodes out of one token --> need to",
") # State machine stats for this sentence if args.out_rule_stats: with open(args.out_rule_stats, 'w')",
"# run the oracle for the entire corpus stats = run_oracle(gold_amrs, args.copy_lemma_action, multitask_words)",
"it using the DEPENDENT action. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id",
"not allow multiple ENTITY here on a single token if machine.current_node_id in machine.entities:",
"ENTITY('name') PRED('city') [other arcs] LA(pos,':name') ENTITY('name') PRED('city') [other arcs] LA(pos,':name') \"\"\" machine =",
"[line.strip() for line in fid.readlines()] else: multitask_words = None return multitask_words def print_corpus_info(amrs):",
"happens first is_dependent = False is_named = False for s, r, t in",
"invalid alignments: sometimes the alignments are outside of the sentence boundary # TODO",
"edges)] new_nodes = ','.join([gold_amr.nodes[n] for n in gold_nodeids]) action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id,",
"argparse from collections import Counter, defaultdict import re from tqdm import tqdm from",
"the ENTITY if len(gold_nodeids) == 1: gold_nodeid = gold_nodeids[0] else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root",
"None # NOTE this doesn't work for ENTITY now, as the mapping from",
"edges continue if t not in gold_nodeids and (t in gold_amr.alignments and gold_amr.alignments[t]):",
"alignments alignments = defaultdict(list) for i in range(len(train_amr.tokens)): for al_node in train_amr.alignmentsToken2Node(i +",
"num_sentences alert_str = '{:d}/{:d} {:2.1f} % repeated sents (max {:d} times)'.format( num_repeated, num_sentences,",
"source nodes in the # aligned subgraph, whereas for the DEPENDENT we are",
"Check if the next action is MERGE. If 1) the current and the",
"using the DEPENDENT action. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id =",
"from --in-amr\", type=str ) parser.add_argument( \"--out-actions\", help=\"actions given by oracle\", type=str ) parser.add_argument(",
"node = train_amr.nodes[node_id] # count number of time a node is aligned to",
"one from the current surface token (segments). E.g. a) for one entity ENTITY('name')",
"positive natural index # check if the alignment is empty # no need",
"('LA', r) return None def run_oracle(gold_amrs, copy_lemma_action, multitask_words): # Initialize lemmatizer as this",
"# aligned subgraph, whereas for the DEPENDENT we are checking the target nodes",
"r) in [(e[0], e[1]) for e in machine.amr.edges]: # to prevent same DEPENDENT",
"in [(e[0], e[1]) for e in machine.amr.edges]: # to prevent same DEPENDENT added",
"return None new_id = None for s, r, t in edges: if s",
"[ (s, r, t) for s, r, t in gold_amr.edges if s in",
"# gold_amr.alignments[root_id] = [-1] # NOTE do not do this; we have made",
"indexed by # token node_by_token[token_str].update([node]) return node_by_token def is_most_common(node_counts, node, rank=0): return (",
"return None def try_entity(self): \"\"\" Check if the next action is ENTITY. TryENTITY",
"if s in align and t in align ] if not edges: remove",
"valid_actions, invalid_actions = self.get_valid_actions() # for now assert len(valid_actions) == 1, \"Oracle must",
"between these 2 ids) # TODO could there be more than one edges?",
"if not dealt with, this causes a problem when the root aligned token",
"check if named entity case: (entity_category, ':name', 'name') # no need, since named",
"action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons = [k for k, c in action_count.items() if",
"self.actions def try_reduce(self): \"\"\" Check if the next action is REDUCE. If 1)",
"id to check edges arc = self.get_arc(act_node_id, node_id) if arc is None: continue",
"when this happens -> should we do multiple PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root #",
"* perc, max( count for counter in amr_counts_by_sentence.values() for count in counter.values() )",
"time each hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count) num_labelings = 0 for skey,",
"'COPY_SENSE01' else: action = f'PRED({new_node})' else: action = f'PRED({new_node})' return action else: return",
"list of node ids in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] # NOTE gold",
"PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root # TODO for multiple PREDs, we need to do",
"1)[-1][0] == node and node_counts.most_common(rank + 1)[-1][1] > node_counts.most_common(rank + 2)[-1][1] ) )",
"generating linearized action sequences for AMR graphs in a rule based way. The",
"gold_amr.nodes[t] == 'name': return None if r in [':polarity', ':mode']: is_dependent = True",
"= nodes2[0] # find edges for s, r, t in gold_amr.edges: if node1",
"prediction # for it here; the ending sequence is always [... SHIFT CLOSE]",
"'-', 'faced', 'spoonbill', '.'] # TODO if not dealt with, this causes a",
"new_id != None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node = gold_amr.nodes[new_id] if self.copy_lemma_action: lemma =",
"pointers for long distance arcs. Actions are SHIFT : move cursor to next",
"node LA(pos,label) : form a left arc from the current node to the",
"False is_named = False for s, r, t in edges: if r ==",
"self.machine node_id = machine.current_node_id if node_id is None: # NOTE if node_id could",
"r == ':name' and gold_amr.nodes[t] == 'name': is_named = True if r in",
": action = 'REDUCE' else: action = 'SHIFT' if action == 'SHIFT' and",
"action # TODO: Add conditional if here multitask_words = process_multitask_words( [list(amr.tokens) for amr",
"self.gold_amr = gold_amr # initialize the state machine self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True,",
"print('Base actions:') print(Counter([k.split('(')[0] for k in action_count.keys()])) print('Most frequent actions:') print(action_count.most_common(10)) if singletons:",
"arc subsequence comes highest, then named entity subsequence, etc. # debug # on",
"with, this causes a problem when the root aligned token id is sentence",
"1] print('Base actions:') print(Counter([k.split('(')[0] for k in action_count.keys()])) print('Most frequent actions:') print(action_count.most_common(10)) if",
"counter in amr_counts_by_sentence.values() for count in counter.values() ) ) print(yellow_font(alert_str)) if num_labelings >",
"NOTE the index + 1 if len(tok_alignment) == 0: return 'REDUCE' else: return",
"added as a node from the beginning, so no prediction # for it",
"= args.in_pred_entities.split(\",\") # Load AMR (replace some unicode characters) # TODO: unicode fixes",
"for long distance arcs. Actions are SHIFT : move cursor to next position",
"= defaultdict(lambda: Counter()) for train_amr in gold_amrs_train: # Get alignments alignments = defaultdict(list)",
"e[1]) for e in machine.amr.edges]: # to prevent same DEPENDENT added twice, as",
"'LA': if (node_id, arc_label, act_node_id) in machine.amr.edges: continue if arc_name == 'RA': if",
"in multitask_words: return f'SHIFT({tok})' else: return 'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count =",
"0 gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo = {} # clean invalid alignments: sometimes the",
"the first unaligned node # whose label is in `included_unaligned` to align to",
"aligned subgraph, and then 3) take the source nodes in the aligned subgraph",
"there is an edge `node_id2` <-- `node_id2` Thus the order of inputs matter.",
"tok in multitask_words: return f'SHIFT({tok})' else: return 'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count",
"frequently need it i.e. person, thing \"\"\" machine = self.machine gold_amr = self.gold_amr",
"to store top-k words for multi-task\" ) parser.add_argument( \"--in-multitask-words\", type=str, help=\"where to read",
"mapping from ENTITY node is only to the source nodes in the #",
"run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) # print stats about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save statistics",
"not action: # action = self.try_named_entities() if not action: action = self.try_entities_with_pred() if",
"alignments are outside of the sentence boundary # TODO check why this happens",
"parameters parser.add_argument( \"--in-amr\", help=\"AMR notation in LDC format\", type=str, required=True ) parser.add_argument( \"--in-propbank-args\",",
"if not edges: remove = 1 if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]])",
"s break if t not in self.built_gold_nodeids: new_id = t break if new_id",
"= self.try_entity() if not action: action = self.try_pred() if not action: if len(self.machine.actions)",
"training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules for idx, action in enumerate(actions): if pred_re.match(action):",
"and gold_amr.nodes[t] == 'name': is_named = True if r in [':polarity', ':mode']: is_dependent",
"if len(tok_alignment) <= 1: return None # check if there is any edge",
"len(sentence_tokens) == len(oracle_actions) source_lengths = [] target_lengths = [] action_count = Counter() for",
"act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is None: continue # for multiple nodes",
"statistics['rules']['possible_predicates'][token].update(node_name) return statistics def main(): # Argument handling args = argument_parser() global entities_with_preds",
"for the DEPENDENT we are checking the target nodes in the subgraph #",
"0 for skey, sent_count in sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) > 1:",
"not cur_alignment or not nxt_alignment: return None # If both tokens are mapped",
"if an edge and node is aligned to this token in the gold",
"RA if there is an edge `node_id1` --> `node_id2` LA if there is",
"def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1): # clean alignments for i, tok in enumerate(gold_amr.tokens):",
"here # check if the node has been constructed, for multiple PREDs if",
"def read_multitask_words(multitask_list): multitask_words = [] with open(multitask_list) as fid: for line in fid:",
"check if named entity case: (entity_category, ':name', 'name') entity_edges = [] name_node_ids =",
"act_node_id) in machine.amr.edges: continue if arc_name == 'RA': if (act_node_id, arc_label, node_id) in",
"if c == 1] print('Base actions:') print(Counter([k.split('(')[0] for k in action_count.keys()])) print('Most frequent",
"\"\\033[93m%s\\033[0m\" % string entities_with_preds = [] def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1): # clean",
"= 'REDUCE' else: action = 'SHIFT' if action == 'SHIFT' and self.multitask_words is",
"for count in counter.values() ) ) print(yellow_font(alert_str)) if num_labelings > num_unique_sents: num_inconsistent =",
"align ] if not edges: remove = 1 if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]])",
"allow pred inside entities that frequently need it i.e. person, thing \"\"\" machine",
"in machine.entities: return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment",
"node_id is None: # NOTE if node_id could be 0, 'if not node_id'",
"== s: return ('LA', r) return None def run_oracle(gold_amrs, copy_lemma_action, multitask_words): # Initialize",
"{ 'sentence_tokens': [], 'oracle_actions': [], 'oracle_amr': [], 'rules': { # Will store count",
"al_node in train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append( train_amr.tokens[i] ) for node_id, aligned_tokens in alignments.items():",
") for node_id, aligned_tokens in alignments.items(): # join multiple words into one single",
"in zip(sentence_tokens, oracle_actions): # filter actions to remove pointer for action in actions:",
"words multitask_words = get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root ) # store in file with",
"# on dev set, sentence id 459 (starting from 0) -> for DEPENDENT",
"target_lengths.append(len(actions)) pass singletons = [k for k, c in action_count.items() if c ==",
"ENTITY if len(gold_nodeids) == 1: gold_nodeid = gold_nodeids[0] else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for",
"= gold_amr.alignmentsToken2Node(tok_id + 1) # below is coupled with the PRED checks? and",
"than one edges? # currently we only return the first one. \"\"\" gold_amr",
"read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine, get_spacy_lemmatizer ) \"\"\" This algorithm contains",
"PRED('city') [other arcs] LA(pos,':name') c) for two entities with two surface tokens ENTITY('name')",
"None def try_merge(self): \"\"\" Check if the next action is MERGE. If 1)",
"entity_edges: if t not in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)' if s",
"on the first time on a new token return None if machine.tok_cursor <",
"sents', max( count for counter in amr_counts_by_sentence.values() for count in counter.values() ) )",
"for multiple PREDs, we need to do a for loop here # check",
"SHIFT CLOSE] or [... LA(pos,'root') SHIFT CLOSE] machine = self.machine while not machine.is_closed:",
"replacing '-' to '_' help=\"statistics about alignments\", type=str ) # Multiple input parameters",
"[] target_lengths = [] action_count = Counter() for tokens, actions in zip(sentence_tokens, oracle_actions):",
"tokenized_corpus: word_count.update([x for x in sentence]) # Restrict to top-k words allowed_words =",
"> 1: pass # There is more than one labeling for this sentence",
"and node_counts.most_common(rank + 1)[-1][0] == node and node_counts.most_common(rank + 1)[-1][1] > node_counts.most_common(rank +",
"already 2) Only for :polarity and :mode, if an edge and node is",
"many time each hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count) num_labelings = 0 for",
"the oracle adds it using the DEPENDENT action. \"\"\" machine = self.machine gold_amr",
"( gold_amr.nodes[root] in entities_with_preds or is_dependent): return None gold_nodeids = [n for n",
"if tok_id == machine.tokseq_len - 1: # never do PRED(<ROOT>) currently, as the",
"this token in the gold amr but does not exist in the predicted",
"the current token aligned node. If 1) currently is on a node that",
"= get_spacy_lemmatizer() # This will store the oracle stats statistics = { 'sentence_tokens':",
"do not write CLOSE action at the end; # CLOSE action is internally",
"a named entity, or a subgraph PRED(label) : form a new node with",
") # parser.add_argument( \"--verbose\", action='store_true', help=\"verbose processing\" ) # parser.add_argument( \"--multitask-max-words\", type=int, help=\"number",
"= [] @property def tokens(self): return self.gold_amr.tokens @property def time_step(self): return self.machine.time_step @property",
"is aligned to this token in the gold amr but does not exist",
"sometimes the alignments are outside of the sentence boundary # TODO check why",
"AMR and the alignment. \"\"\" # Loop over potential actions # NOTE \"<ROOT>\"",
"help=\"statistics about actions\", type=str ) parser.add_argument( \"--out-rule-stats\", # TODO this is accessed by",
"source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons = [k for k, c in action_count.items() if c",
"= '{:d}/{:d} {:2.1f} % {:s} (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc,",
"train_amr in gold_amrs_train: # Get alignments alignments = defaultdict(list) for i in range(len(train_amr.tokens)):",
"here multitask_words = process_multitask_words( [list(amr.tokens) for amr in gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True",
"( ( # as many results as the rank and node in that",
"# Load AMR (replace some unicode characters) # TODO: unicode fixes and other",
"nodes2[0] # find edges for s, r, t in gold_amr.edges: if node1 ==",
"not in self.built_gold_nodeids: new_id = t break if new_id != None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id,",
"graphs in a rule based way. The parsing algorithm is transition-based combined with",
"'name': is_named = True if r in [':polarity', ':mode']: is_dependent = True root",
"None if args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args) # read/write multi-task (labeled shift) action #",
"statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules for idx, action in enumerate(actions): if pred_re.match(action): node_name",
"\"Oracle can\\'t blacklist actions\" action = valid_actions[0] # update the machine machine.apply_action(action) #",
"this node \"\"\" machine = self.machine node_id = machine.current_node_id if node_id is None:",
"entity subsequence, etc. # debug # on dev set, sentence id 459 (starting",
"1) # NOTE we make all token ids positive natural index # check",
"add_root=add_root ) # store in file with open(out_multitask_words, 'w') as fid: for word",
"s not in self.built_gold_nodeids: new_id = s break if t not in self.built_gold_nodeids:",
"store top-k words for multi-task\" ) parser.add_argument( \"--in-multitask-words\", type=str, help=\"where to read top-k",
"[nodes2] if not nodes1 or not nodes2: return None # convert to single",
"[-1] # NOTE do not do this; we have made all the token",
"REDUCE. If 1) there is nothing aligned to a token. \"\"\" machine =",
"need since the REDUCE check happens first if len(tok_alignment) == 1: gold_nodeid =",
"in fid.readlines()] else: multitask_words = None return multitask_words def print_corpus_info(amrs): # print some",
"= \"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root)) # gold_amr.alignments[root_id] = [-1] # NOTE do not",
"and node_counts.most_common(rank + 1)[-1][0] == node ) or ( # more results than",
"the sentence is # ['Among', 'common', 'birds', ',', 'a', 'rather', 'special', 'one', 'is',",
"since named entity check happens first is_dependent = False is_named = False for",
"propbank reader instead of txt reader propbank_args = None if args.in_propbank_args: propbank_args =",
"AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load propbank if provided # TODO: Use here XML",
"into one single expression if len(aligned_tokens) > 1: token_str = \" \".join(aligned_tokens) else:",
"align = gold_amr.alignmentsToken2Node(i + 1) if len(align) == 2: edges = [ (s,",
"in gold_amr.nodes: if n not in gold_amr.alignments or not gold_amr.alignments[n]: if gold_amr.nodes[n] in",
") or ( # more results than the rank, node in that rank",
"1) if len(align) == 2: edges = [ (s, r, t) for s,",
"= \" \".join(amr.tokens) # count number of time sentence repeated sentence_count.update([skey]) # hash",
"# NOTE currently do not allow multiple ENTITY here on a single token",
"alert_str = '{:d}/{:d} {:2.1f} % {:s} (max {:d} times)'.format( num_repeated, num_sentences, 100 *",
"out_multitask_words, add_root=False): # Load/Save words for multi-task if multitask_max_words: assert multitask_max_words assert out_multitask_words",
"change to follow strict orders between these 2 ids) # TODO could there",
"edges? # currently we only return the first one. \"\"\" gold_amr = self.gold_amr",
"akey = amr.toJAMRString() # store different amr labels for same sent, keep has",
"['The', 'cyber', 'attacks', 'were', 'unprecedented', '.', '<ROOT>']: # if self.time_step >= 8: #",
"aligned node. If 1) currently is on a node that was just constructed",
"and node with `node_id2`. RA if there is an edge `node_id1` --> `node_id2`",
"avoid repetitive edges if arc_name == 'LA': if (node_id, arc_label, act_node_id) in machine.amr.edges:",
"else: token_str = aligned_tokens[0] node = train_amr.nodes[node_id] # count number of time a",
"as this is slow lemmatizer = get_spacy_lemmatizer() # This will store the oracle",
"on dev set, sentence id 459 (starting from 0) -> for DEPENDENT missing",
"e.g. within node-arc actions, arc subsequence comes highest, then named entity subsequence, etc.",
"'were', 'unprecedented', '.', '<ROOT>']: # if self.time_step >= 8: # breakpoint() action =",
"+ 1 and node_counts.most_common(rank + 1)[-1][0] == node ) or ( # more",
"label is in `included_unaligned` to align to # repeat `add_unaligned` times if add_unaligned:",
"[action] invalid_actions = [] return valid_actions, invalid_actions def build_oracle_actions(self): \"\"\"Build the oracle action",
"use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge = r[1:] if r.startswith(':') else r new_node",
"that involve the current token aligned node. If 1) currently is on a",
"NOTE \"<ROOT>\" token at last position is added as a node from the",
"return None # check if named entity case: (entity_category, ':name', 'name') entity_edges =",
"r, t in edges)] new_nodes = ','.join([gold_amr.nodes[n] for n in gold_nodeids]) action =",
"first is_dependent = False is_named = False for s, r, t in edges:",
"{ # Will store count of PREDs given pointer position 'possible_predicates': defaultdict(lambda: Counter())",
"included_unaligned=None, root_id=-1): # clean alignments for i, tok in enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i",
"single token if machine.current_node_id in machine.entities: return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1)",
"NOTE do not do this; we have made all the token ids natural",
"1 and node_counts.most_common(rank + 1)[-1][0] == node and node_counts.most_common(rank + 1)[-1][1] > node_counts.most_common(rank",
"100 * perc, max( count for counter in amr_counts_by_sentence.values() for count in counter.values()",
"better name such as `shift_label_words` # AMR construction states info self.nodeid_to_gold_nodeid = {}",
"print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) == len(oracle_actions) source_lengths =",
"entities with same surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') PRED('city') [other arcs]",
"def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) == len(oracle_actions) source_lengths = []",
"all token ids positive natural index # check if the alignment is empty",
"aligned to token 1 node1 = gold_amr.findSubGraph(nodes1).root else: node1 = nodes1[0] if len(nodes2)",
"tok_id = machine.tok_cursor node_id = machine.current_node_id if node_id is None: # NOTE if",
"self.machine.actions def get_valid_actions(self): \"\"\"Get the valid actions and invalid actions based on the",
"== 'LA': if (node_id, arc_label, act_node_id) in machine.amr.edges: continue if arc_name == 'RA':",
"slow lemmatizer = get_spacy_lemmatizer() # This will store the oracle stats statistics =",
"previous node at location pos RA(pos,label) : form a left arc to the",
"the gold AMR graph nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1,",
"= [] for s, r, t in edges: if r == ':name' and",
"machine.tok_cursor nxt = machine.tok_cursor + 1 cur_alignment = gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment =",
"that rank matches, and rank # results is more probable than rank +",
"multi-task\" ) # Labeled shift args parser.add_argument( \"--out-multitask-words\", type=str, help=\"where to store top-k",
"None # convert to single node aligned to each of these two tokens",
"the token sequence REDUCE : delete current token MERGE : merge two tokens",
"node ids in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] # NOTE gold amr root",
"action = f'PRED({new_node})' return action return None def try_entity(self): \"\"\" Check if the",
"def try_pred(self): \"\"\" Check if the next action is PRED, COPY_LEMMA, COPY_SENSE01. If",
"woprds to use for multi-task\" ) # Labeled shift args parser.add_argument( \"--out-multitask-words\", type=str,",
"\"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor if tok_id ==",
"= 0 gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo = {} # clean invalid alignments: sometimes",
"the subgraph # gold_nodeids = self.nodeid_to_gold_nodeid[node_id] # gold_nodeids = list(set(gold_nodeids)) # just in",
"here on a single token if machine.current_node_id in machine.entities: return None tok_alignment =",
"rules for idx, action in enumerate(actions): if pred_re.match(action): node_name = pred_re.match(action).groups()[0] token =",
"nodes in the subgraph # gold_nodeids = self.nodeid_to_gold_nodeid[node_id] # gold_nodeids = list(set(gold_nodeids)) #",
"in align and t in align ] if not edges: remove = 1",
"and treated same as <eos> in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules for",
"aligned to a token. \"\"\" machine = self.machine gold_amr = self.gold_amr if machine.current_node_id",
"None for s, r, t in edges: if s not in self.built_gold_nodeids: new_id",
"): remove = 0 gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo = {} # clean invalid",
"for amr in gold_amrs: # hash of sentence skey = \" \".join(amr.tokens) #",
"# not on the first time on a new token return None tok_id",
"remove = 1 if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ): remove =",
"action in enumerate(actions): if pred_re.match(action): node_name = pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return",
"multitask_words): # Initialize lemmatizer as this is slow lemmatizer = get_spacy_lemmatizer() # This",
"fid.readlines()] else: multitask_words = None return multitask_words def print_corpus_info(amrs): # print some info",
"s, r, t in gold_amr.edges: if s == gold_nodeid and r in [':polarity',",
"gold_amrs_train: # Get alignments alignments = defaultdict(list) for i in range(len(train_amr.tokens)): for al_node",
"separated list of entity types that can have pred\" ) args = parser.parse_args()",
"to same node or overlap if cur_alignment == nxt_alignment: return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)):",
"import read_propbank, read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine, get_spacy_lemmatizer ) \"\"\" This",
"machine.apply_action(action) # close machine # below are equivalent # machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True,",
"gold_amr.nodes[t] == 'name': is_named = True if r in [':polarity', ':mode']: is_dependent =",
"tok_alignment if any(s == n for s, r, t in edges)] new_nodes =",
"nodes2 = [nodes2] if not nodes1 or not nodes2: return None # convert",
"# pointer value arc_pos = act_id return f'{arc_name}({arc_pos},{arc_label})' return None def get_arc(self, node_id1,",
"with `node_id1` and node with `node_id2`. RA if there is an edge `node_id1`",
"many results as the rank and node in that rank matches len(node_counts) ==",
"1 and node_counts.most_common(rank + 1)[-1][0] == node ) or ( # more results",
"(replace some unicode characters) # TODO: unicode fixes and other normalizations should be",
"open(in_multitask_words) as fid: multitask_words = [line.strip() for line in fid.readlines()] else: multitask_words =",
"types/tokens') edge_label_count = Counter([t[1] for amr in amrs for t in amr.edges]) edge_tokens",
"nxt_alignment = gold_amr.alignmentsToken2Node(nxt + 1) if not cur_alignment or not nxt_alignment: return None",
"rank=0): return ( ( # as many results as the rank and node",
"help=\"Use copy action from Spacy lemmas\" ) # copy lemma action parser.add_argument( \"--addnode-count-cutoff\",",
"sentence is # ['Among', 'common', 'birds', ',', 'a', 'rather', 'special', 'one', 'is', #",
"num_sentences, 100 * perc, 'repeated sents', max( count for counter in amr_counts_by_sentence.values() for",
"or overlap if cur_alignment == nxt_alignment: return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return",
"is accessed by replacing '-' to '_' help=\"statistics about alignments\", type=str ) #",
"type=str ) parser.add_argument( \"--out-rule-stats\", # TODO this is accessed by replacing '-' to",
"t in amr.edges]) edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count = Counter([w for",
"= [line.strip() for line in fid.readlines()] else: multitask_words = None return multitask_words def",
"# find the next action # NOTE the order here is important, which",
"types that can have pred\" ) args = parser.parse_args() return args def yellow_font(string):",
"perc = num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % {:s}'.format( num_inconsistent, num_sentences,",
"same surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') PRED('city') [other arcs] LA(pos,':name') c)",
"1) the current token is aligned to a single node, or multiple nodes?",
"root node is automatically added at the beginning # NOTE to change this",
"the DEPENDENT we are checking the target nodes in the subgraph # gold_nodeids",
"nxt_alignment: return None # If both tokens are mapped to same node or",
"added at the beginning # NOTE to change this behavior, we need to",
"to use node id to check edges arc = self.get_arc(act_node_id, node_id) if arc",
"on a node that was just constructed 2) there are edges that have",
"multitask_max_words: assert multitask_max_words assert out_multitask_words # get top words multitask_words = get_multitask_actions( multitask_max_words,",
"and not is_dependent: return None new_id = None for s, r, t in",
"node has been predicted already 2) Only for :polarity and :mode, if an",
"# TODO: Add conditional if here multitask_words = process_multitask_words( [list(amr.tokens) for amr in",
"r) if node1 == t and node2 == s: return ('LA', r) return",
"the root node id which should be -1 now # that is also",
"node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root)) # gold_amr.alignments[root_id] = [-1] #",
"s, r, t in gold_amr.edges: if node1 == s and node2 == t:",
"tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE the index + 1 if len(tok_alignment)",
"beginning, so no prediction # for it here; the ending sequence is always",
"new_id = s break if t not in self.built_gold_nodeids: new_id = t break",
"node is aligned to this token in the gold amr but does not",
"one token --> need to use node id to check edges arc =",
"argument data\", type=str, ) parser.add_argument( \"--out-oracle\", help=\"tokens, AMR notation and actions given by",
"state machine status and the gold AMR.\"\"\" # find the next action #",
"for loop here # check if the node has been constructed, for multiple",
"'SHIFT' and self.multitask_words is not None: action = label_shift(self.machine, self.multitask_words) valid_actions = [action]",
"Get the arcs that involve the current token aligned node. If 1) currently",
"return \"\\033[93m%s\\033[0m\" % string entities_with_preds = [] def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1): #",
"surface token (segments). E.g. a) for one entity ENTITY('name') PRED('city') [other arcs] LA(pos,':name')",
"node2 == t: return ('RA', r) if node1 == t and node2 ==",
"r, t in gold_amr.edges: if s == gold_nodeid and r in [':polarity', ':mode']:",
"action = f'PRED({new_node})' else: action = f'PRED({new_node})' return action return None def try_entity(self):",
"of node ids in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] # NOTE gold amr",
"in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n in gold_amr.nodes: if n not in gold_amr.alignments or",
"statistics = { 'sentence_tokens': [], 'oracle_actions': [], 'oracle_amr': [], 'rules': { # Will",
"oracle_actions): # filter actions to remove pointer for action in actions: if pointer_arc_re.match(action):",
"end; # CLOSE action is internally managed, and treated same as <eos> in",
"1)[-1][0] == node ) or ( # more results than the rank, node",
"we need to do a for loop here # check if the node",
"= [n for n in tok_alignment if any(s == n for s, r,",
"store in file with open(out_multitask_words, 'w') as fid: for word in multitask_words.keys(): fid.write(f'{word}\\n')",
"gold AMR.\"\"\" # find the next action # NOTE the order here is",
"id is fixed at -1 self.built_gold_nodeids = [] @property def tokens(self): return self.gold_amr.tokens",
"enumerate(machine.actions_to_nodes): for act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is None: continue # for",
"edge and node is aligned to this token in the gold amr but",
"print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words = [] with open(multitask_list) as fid: for line in",
"print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count = Counter([w for amr in amrs for w in",
"find/add root. return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE we make",
"'_' help=\"statistics about alignments\", type=str ) # Multiple input parameters parser.add_argument( \"--out-amr\", help=\"corresponding",
"[other arcs] LA(pos,':name') ENTITY('name') PRED('city') [other arcs] LA(pos,':name') \"\"\" machine = self.machine gold_amr",
"try_entity(self): \"\"\" Check if the next action is ENTITY. TryENTITY before tryPRED. If",
"= gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE we make all token ids positive natural",
"for i in range(len(train_amr.tokens)): for al_node in train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append( train_amr.tokens[i] )",
"actions:') print(action_count.most_common(10)) if singletons: base_action_count = [x.split('(')[0] for x in singletons] msg =",
"name_node_ids = [] for s, r, t in edges: if r == ':name'",
"in case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id + 1) # below is coupled with the",
"def sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence =",
"one sentence.\"\"\" def __init__(self, gold_amr, lemmatizer, copy_lemma_action, multitask_words): self.gold_amr = gold_amr # initialize",
"subgraph, whereas for the DEPENDENT we are checking the target nodes in the",
"next DEPEDENT check, but is fine if we always use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id,",
"action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all addnode actions appearing less times than count\", type=int",
"data\", type=str, ) parser.add_argument( \"--out-oracle\", help=\"tokens, AMR notation and actions given by oracle\",",
"[]).append(t) return 'ENTITY(name)' if s not in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})'",
"we always use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge = r[1:] if r.startswith(':') else",
"main(): # Argument handling args = argument_parser() global entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\") #",
"2)[-1][1] ) ) def sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence =",
"not on the first time on a new token return None if machine.tok_cursor",
"num_labelings - num_unique_sents perc = num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} %",
"def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count = Counter() for sentence in tokenized_corpus: word_count.update([x for",
"than one labeling for this sentence # amrs = list(amr_by_amrkey_by_sentence[skey].values()) # inform user",
"reader propbank_args = None if args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args) # read/write multi-task (labeled",
"= process_multitask_words( [list(amr.tokens) for amr in gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True ) #",
"not action: action = self.try_pred() if not action: if len(self.machine.actions) and self.machine.actions[-1] ==",
"train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append( train_amr.tokens[i] ) for node_id, aligned_tokens in alignments.items(): # join",
"from ENTITY node is only to the source nodes in the # aligned",
"def try_named_entities(self): \"\"\" Get the named entity sub-sequences one by one from the",
"nodes1[0] if len(nodes2) > 1: # get root of subgraph aligned to token",
"check if the node has been constructed, for multiple PREDs if gold_nodeid not",
"is ENTITY. TryENTITY before tryPRED. If 1) aligned to more than 1 nodes,",
"1: pass # There is more than one labeling for this sentence #",
"to be careful about the root node id which should be -1 now",
"unicode fixes and other normalizations should be applied more # transparently print(f'Reading {args.in_amr}')",
"complete AMR, run post-processing \"\"\" use_addnode_rules = True def argument_parser(): parser = argparse.ArgumentParser(description='AMR",
"E.g. a) for one entity ENTITY('name') PRED('city') [other arcs] LA(pos,':name') b) for two",
"num_labelings > num_unique_sents: num_inconsistent = num_labelings - num_unique_sents perc = num_inconsistent / num_sentences",
"gold_nodeids[0] else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for s, r, t in gold_amr.edges: if s",
"help=\"forbid all addnode actions appearing less times than count\", type=int ) parser.add_argument( \"--in-pred-entities\",",
"times if add_unaligned: for i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n in gold_amr.nodes: if",
"if named entity case: (entity_category, ':name', 'name') # no need, since named entity",
"for multiple nodes out of one token --> need to use node id",
"else: return 'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count = Counter() for sentence in",
"len(align) == 2: edges = [ (s, r, t) for s, r, t",
"the current and the next token have the same node alignment. \"\"\" machine",
"n in gold_nodeids]) action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action def try_pred(self):",
"given pointer position 'possible_predicates': defaultdict(lambda: Counter()) } } pred_re = re.compile(r'^PRED\\((.*)\\)$') # Process",
"= f'PRED({new_node})' else: action = f'PRED({new_node})' return action return None def try_entity(self): \"\"\"",
"TryENTITY before tryPRED. If 1) aligned to more than 1 nodes, and 2)",
"input parameters parser.add_argument( \"--in-amr\", help=\"AMR notation in LDC format\", type=str, required=True ) parser.add_argument(",
"args.out_multitask_words, add_root=True ) # run the oracle for the entire corpus stats =",
"one for sent_idx, gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO: See if we can",
"amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda: Counter()) for amr in gold_amrs: # hash",
"lemma = machine.get_current_token(lemma=True) if lemma == new_node: action = 'COPY_LEMMA' elif f'{lemma}-01' ==",
"\"--copy-lemma-action\", action='store_true', help=\"Use copy action from Spacy lemmas\" ) # copy lemma action",
"return None def get_arc(self, node_id1, node_id2): \"\"\" Get the arcs between node with",
"node_counts.most_common(rank + 1)[-1][0] == node and node_counts.most_common(rank + 1)[-1][1] > node_counts.most_common(rank + 2)[-1][1]",
"name such as `shift_label_words` # AMR construction states info self.nodeid_to_gold_nodeid = {} #",
"new_edge = r[1:] if r.startswith(':') else r new_node = gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})'",
"'faced', 'spoonbill', '.'] # TODO if not dealt with, this causes a problem",
"shift) action # TODO: Add conditional if here multitask_words = process_multitask_words( [list(amr.tokens) for",
"store different amr labels for same sent, keep has map if akey not",
"singletons: base_action_count = [x.split('(')[0] for x in singletons] msg = f'{len(singletons)} singleton actions'",
"node_label_count = Counter([ n for amr in amrs for n in amr.nodes.values() ])",
"amr_by_amrkey_by_sentence[skey][akey] = amr # count how many time each hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents",
"self.machine.time_step @property def actions(self): return self.machine.actions def get_valid_actions(self): \"\"\"Get the valid actions and",
"position 'possible_predicates': defaultdict(lambda: Counter()) } } pred_re = re.compile(r'^PRED\\((.*)\\)$') # Process AMRs one",
"self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)' if s not in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s)",
"[':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not in entities_with_preds",
"pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons =",
"f'{arc_name}({arc_pos},{arc_label})' return None def get_arc(self, node_id1, node_id2): \"\"\" Get the arcs between node",
"gold_nodeid not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma",
"actions(self): return self.machine.actions def get_valid_actions(self): \"\"\"Get the valid actions and invalid actions based",
"t in gold_amr.edges: if node1 == s and node2 == t: return ('RA',",
"None: continue arc_name, arc_label = arc # avoid repetitive edges if arc_name ==",
"action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action def try_pred(self): \"\"\" Check if",
"CLOSE : complete AMR, run post-processing \"\"\" use_addnode_rules = True def argument_parser(): parser",
"= self.machine gold_amr = self.gold_amr if machine.current_node_id is not None: # not on",
"'COPY_LEMMA' elif f'{lemma}-01' == new_node: action = 'COPY_SENSE01' else: action = f'PRED({new_node})' else:",
"propbank if provided # TODO: Use here XML propbank reader instead of txt",
"return node_by_token def is_most_common(node_counts, node, rank=0): return ( ( # as many results",
"for action in actions: if pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})' action_count.update([action])",
"with same surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') PRED('city') [other arcs] LA(pos,':name')",
"get_spacy_lemmatizer ) \"\"\" This algorithm contains heuristics for generating linearized action sequences for",
"action: # action = self.try_named_entities() if not action: action = self.try_entities_with_pred() if not",
"# Restrict to top-k words allowed_words = dict(list(sorted( word_count.items(), key=lambda x: x[1]) )[-max_symbols:])",
"= [nodes1] if not isinstance(nodes2, list): nodes2 = [nodes2] if not nodes1 or",
")[-max_symbols:]) if add_root: # Add root regardless allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words def process_multitask_words(tokenized_corpus,",
"been predicted already 2) Only for :polarity and :mode, if an edge and",
"lemma action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all addnode actions appearing less times than count\",",
"the next action is REDUCE. If 1) there is nothing aligned to a",
"label_shift(state_machine, multitask_words): tok = state_machine.get_current_token(lemma=False) if tok in multitask_words: return f'SHIFT({tok})' else: return",
"also the ENTITY if len(gold_nodeids) == 1: gold_nodeid = gold_nodeids[0] else: gold_nodeid =",
"word_label_count = Counter([w for amr in amrs for w in amr.tokens]) word_tokens =",
"if the next action is MERGE. If 1) the current and the next",
"not in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)' if s not in self.built_gold_nodeids:",
"action: action = self.try_entities_with_pred() if not action: action = self.try_entity() if not action:",
"next action is REDUCE. If 1) there is nothing aligned to a token.",
"should be applied more # transparently print(f'Reading {args.in_amr}') corpus = read_amr(args.in_amr, unicode_fixes=True) gold_amrs",
"if there is an edge `node_id1` --> `node_id2` LA if there is an",
"machine.amr.edges: continue # pointer value arc_pos = act_id return f'{arc_name}({arc_pos},{arc_label})' return None def",
": form a named entity, or a subgraph PRED(label) : form a new",
"+ 1 len(node_counts) > rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node",
"repeated sents'.format( num_inconsistent, num_sentences, perc ) print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words = [] with",
"copying lemma COPY_SENSE01 : form a new node by copying lemma and add",
"self.copy_lemma_action = copy_lemma_action self.multitask_words = multitask_words # TODO deprecate `multitask_words` or change for",
"of alignments between nodes and surface words\"\"\" node_by_token = defaultdict(lambda: Counter()) for train_amr",
"no prediction # for it here; the ending sequence is always [... SHIFT",
"between nodes and surface words\"\"\" node_by_token = defaultdict(lambda: Counter()) for train_amr in gold_amrs_train:",
"built with this node \"\"\" machine = self.machine node_id = machine.current_node_id if node_id",
"\"--multitask-max-words\", type=int, help=\"number of woprds to use for multi-task\" ) # Labeled shift",
"PRED checks? and also the ENTITY if len(gold_nodeids) == 1: gold_nodeid = gold_nodeids[0]",
"return action return None def try_entity(self): \"\"\" Check if the next action is",
"node id in the state machine, value: list of node ids in gold",
"the arcs between node with `node_id1` and node with `node_id2`. RA if there",
"tids in gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid for tid in tids if tid <=",
"amr_counts_by_sentence.values() for count in counter.values() ) ) print(yellow_font(alert_str)) if num_labelings > num_unique_sents: num_inconsistent",
"tqdm import tqdm from transition_amr_parser.io import read_propbank, read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import (",
"state_machine.get_current_token(lemma=False) if tok in multitask_words: return f'SHIFT({tok})' else: return 'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus,",
"t not in self.built_gold_nodeids: new_id = t break if new_id != None: self.built_gold_nodeids.append(new_id)",
"if pred_re.match(action): node_name = pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics def main():",
"t in align ] if not edges: remove = 1 if ( gold_amr.nodes[align[1]].startswith(tok[:2])",
"based on priority # e.g. within node-arc actions, arc subsequence comes highest, then",
"'{:d}/{:d} {:2.4f} % inconsistent labelings from repeated sents'.format( num_inconsistent, num_sentences, perc ) print(yellow_font(alert_str))",
"build_oracle_actions(self): \"\"\"Build the oracle action sequence for the current token sentence, based on",
"as the rank and node in that rank matches len(node_counts) == rank +",
"for s, r, t in edges)] new_nodes = ','.join([gold_amr.nodes[n] for n in gold_nodeids])",
"in a rule based way. The parsing algorithm is transition-based combined with pointers",
"None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE we make all token ids",
"enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i + 1) if len(align) == 2: edges = [",
"MERGE. If 1) the current and the next token have the same node",
"is DEPENDENT. If 1) the aligned node has been predicted already 2) Only",
"in machine.amr.edges]: # to prevent same DEPENDENT added twice, as each time we",
"to do a for loop here # check if the node has been",
"akey not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr # count how many time each",
"aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None is_dependent = False",
"and node2 == t: return ('RA', r) if node1 == t and node2",
"# an example is in training data, when the sentence is # ['Among',",
"parser = argparse.ArgumentParser(description='AMR parser oracle') # Single input parameters parser.add_argument( \"--in-amr\", help=\"AMR notation",
"num_unique_sents perc = num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % {:s} (max",
"gold amr but does not exist in the predicted amr, the oracle adds",
"surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') PRED('city') [other arcs] LA(pos,':name') c) for",
"= pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics def main(): # Argument handling",
"is transition-based combined with pointers for long distance arcs. Actions are SHIFT :",
"actions and invalid actions based on the current AMR state machine status and",
"if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node: action = 'COPY_LEMMA' elif",
"gold_amr.root)) # gold_amr.alignments[root_id] = [-1] # NOTE do not do this; we have",
"if num_labelings > num_unique_sents: num_inconsistent = num_labelings - num_unique_sents perc = num_inconsistent /",
"return 'ENTITY(name)' if s not in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})' return",
"in edges: if r == ':name' and gold_amr.nodes[t] == 'name': is_named = True",
"self.try_reduce() if not action: action = self.try_merge() #if not action: # action =",
"DEPENDENT missing # if self.tokens == ['The', 'cyber', 'attacks', 'were', 'unprecedented', '.', '<ROOT>']:",
"action return None def try_arcs(self): \"\"\" Get the arcs that involve the current",
"= f'PRED({new_node})' return action else: return None def try_dependent(self): \"\"\" Check if the",
"% string entities_with_preds = [] def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1): # clean alignments",
"cursor to next position in the token sequence REDUCE : delete current token",
"sequence actions = oracle_builder.build_oracle_actions() # store data statistics['sentence_tokens'].append(oracle_builder.tokens) # do not write CLOSE",
"notation and actions given by oracle\", type=str ) parser.add_argument( \"--out-sentences\", help=\"tokenized sentences from",
"parser.add_argument( \"--out-action-stats\", help=\"statistics about actions\", type=str ) parser.add_argument( \"--out-rule-stats\", # TODO this is",
"if the next action is PRED, COPY_LEMMA, COPY_SENSE01. If 1) the current token",
"amr # count how many time each hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count)",
"return 'REDUCE' else: return None def try_merge(self): \"\"\" Check if the next action",
"= self.gold_amr if machine.current_node_id is not None: # not on the first time",
"an edge and node is aligned to this token in the gold amr",
"print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string num_sentences = len(gold_amrs)",
"return self.machine.actions def get_valid_actions(self): \"\"\"Get the valid actions and invalid actions based on",
"oracle adds it using the DEPENDENT action. \"\"\" machine = self.machine gold_amr =",
"<-- `node_id2` Thus the order of inputs matter. (could also change to follow",
"print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class AMROracleBuilder: \"\"\"Build AMR oracle for one sentence.\"\"\" def __init__(self,",
"r == ':name' and gold_amr.nodes[t] == 'name': return None if r in [':polarity',",
"459 (starting from 0) -> for DEPENDENT missing # if self.tokens == ['The',",
"2: edges = [ (s, r, t) for s, r, t in gold_amr.edges",
"statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules for idx, action in enumerate(actions): if pred_re.match(action): node_name =",
"TODO: Use here XML propbank reader instead of txt reader propbank_args = None",
"len(invalid_actions) == 0, \"Oracle can\\'t blacklist actions\" action = valid_actions[0] # update the",
"inside entities that frequently need it i.e. person, thing \"\"\" machine = self.machine",
"remove this part gold_amr = gold_amr.copy() gold_amr = preprocess_amr(gold_amr) # Initialize oracle builder",
"alignment return gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of alignments between nodes and surface",
"if act_node_id is None: continue # for multiple nodes out of one token",
"# transparently print(f'Reading {args.in_amr}') corpus = read_amr(args.in_amr, unicode_fixes=True) gold_amrs = corpus.amrs # sanity",
"find edges for s, r, t in gold_amr.edges: if node1 == s and",
"num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % {:s} (max {:d} times)'.format( num_repeated,",
"than rank + 1 len(node_counts) > rank + 1 and node_counts.most_common(rank + 1)[-1][0]",
"oracle action sequence for the current token sentence, based on the gold AMR",
"continue if arc_name == 'RA': if (act_node_id, arc_label, node_id) in machine.amr.edges: continue #",
") # parser.add_argument( \"--multitask-max-words\", type=int, help=\"number of woprds to use for multi-task\" )",
"# machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions def try_reduce(self): \"\"\" Check if",
"def time_step(self): return self.machine.time_step @property def actions(self): return self.machine.actions def get_valid_actions(self): \"\"\"Get the",
"need to do a for loop here # check if the node has",
"step return None # NOTE this doesn't work for ENTITY now, as the",
"= False is_named = False for s, r, t in edges: if r",
"action is internally managed, and treated same as <eos> in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString())",
"not action: if len(self.machine.actions) and self.machine.actions[-1] == 'SHIFT' and self.machine.tok_cursor != self.machine.tokseq_len -",
"to read top-k words for multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab separation",
"sanity_check_amr(gold_amrs) # Load propbank if provided # TODO: Use here XML propbank reader",
"keep has map if akey not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr # count",
"If both tokens are mapped to same node or overlap if cur_alignment ==",
"not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr # count how many time each hash",
"is sentence length (not -1) for nid, tids in gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid",
"of subgraph aligned to token 2 node2 = gold_amr.findSubGraph(nodes2).root else: node2 = nodes2[0]",
"the oracle actions sequence actions = oracle_builder.build_oracle_actions() # store data statistics['sentence_tokens'].append(oracle_builder.tokens) # do",
"is PRED, COPY_LEMMA, COPY_SENSE01. If 1) the current token is aligned to a",
"# print some info print(f'{len(amrs)} sentences') node_label_count = Counter([ n for amr in",
"oracle for one sentence.\"\"\" def __init__(self, gold_amr, lemmatizer, copy_lemma_action, multitask_words): self.gold_amr = gold_amr",
"action: # action = self.try_dependent() if not action: action = self.try_arcs() #if not",
"are SHIFT : move cursor to next position in the token sequence REDUCE",
"/ num_sentences alert_str = '{:d}/{:d} {:2.1f} % {:s} (max {:d} times)'.format( num_repeated, num_sentences,",
"action = self.try_pred() if not action: if len(self.machine.actions) and self.machine.actions[-1] == 'SHIFT' and",
"self.try_dependent() if not action: action = self.try_arcs() #if not action: # action =",
"argument_parser(): parser = argparse.ArgumentParser(description='AMR parser oracle') # Single input parameters parser.add_argument( \"--in-amr\", help=\"AMR",
"[], 'rules': { # Will store count of PREDs given pointer position 'possible_predicates':",
"num_unique_sents perc = num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % repeated sents",
"`node_id1` --> `node_id2` LA if there is an edge `node_id2` <-- `node_id2` Thus",
"not nodes2: return None # convert to single node aligned to each of",
"at current step return None #for act_id, act_node_id in enumerate(machine.actions_to_nodes): for act_id, act_node_id",
"for line in fid.readlines()] else: multitask_words = None return multitask_words def print_corpus_info(amrs): #",
"parser.add_argument( \"--out-oracle\", help=\"tokens, AMR notation and actions given by oracle\", type=str ) parser.add_argument(",
"the sentence boundary # TODO check why this happens in the data reading",
"aligned_tokens[0] node = train_amr.nodes[node_id] # count number of time a node is aligned",
"r == ':name' and gold_amr.nodes[t] == 'name': entity_edges.append((s, r, t)) name_node_ids.append(t) if not",
"to check edges arc = self.get_arc(act_node_id, node_id) if arc is None: continue arc_name,",
"type=str ) parser.add_argument( \"--out-action-stats\", help=\"statistics about actions\", type=str ) parser.add_argument( \"--out-rule-stats\", # TODO",
"first unaligned node # whose label is in `included_unaligned` to align to #",
"is a dependent of the current node LA(pos,label) : form a left arc",
"in align ] if not edges: remove = 1 if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or",
"alignment. \"\"\" # Loop over potential actions # NOTE \"<ROOT>\" token at last",
"pass singletons = [k for k, c in action_count.items() if c == 1]",
"a problem when the root aligned token id is sentence length (not -1)",
"NOTE the order here is important, which is based on priority # e.g.",
"mapped to same node or overlap if cur_alignment == nxt_alignment: return 'MERGE' if",
"'special', 'one', 'is', # 'the', 'black', '-', 'faced', 'spoonbill', '.'] # TODO if",
"sequence is always [... SHIFT CLOSE] or [... LA(pos,'root') SHIFT CLOSE] machine =",
"self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor node_id = machine.current_node_id if node_id is",
"token in the gold amr but does not exist in the predicted amr,",
"multitask_words): self.gold_amr = gold_amr # initialize the state machine self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer,",
"AMR state machine status and the gold AMR.\"\"\" # find the next action",
"based on the gold AMR and the alignment. \"\"\" # Loop over potential",
": delete current token MERGE : merge two tokens (for MWEs) ENTITY(type) :",
"# count how many time each hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count) num_labelings",
"not edges: return None # check if named entity case: (entity_category, ':name', 'name')",
"if new_id != None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node = gold_amr.nodes[new_id] if self.copy_lemma_action: lemma",
"of the sentence boundary # TODO check why this happens in the data",
"# CLOSE action is internally managed, and treated same as <eos> in training",
"return valid_actions, invalid_actions def build_oracle_actions(self): \"\"\"Build the oracle action sequence for the current",
"1, \"Oracle must be deterministic\" assert len(invalid_actions) == 0, \"Oracle can\\'t blacklist actions\"",
"return None gold_nodeids = [n for n in tok_alignment if any(s == n",
"# Save statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t' )",
"single expression if len(aligned_tokens) > 1: token_str = \" \".join(aligned_tokens) else: token_str =",
"first time on a new token return None tok_id = machine.tok_cursor tok_alignment =",
"check if there is any edge with the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges",
"is automatically added at the beginning # NOTE to change this behavior, we",
"# Load propbank if provided # TODO: Use here XML propbank reader instead",
"these two tokens if len(nodes1) > 1: # get root of subgraph aligned",
"if tid <= len(gold_amr.tokens)] # TODO: describe this # append a special token",
"print(Counter([k.split('(')[0] for k in action_count.keys()])) print('Most frequent actions:') print(action_count.most_common(10)) if singletons: base_action_count =",
"all the token ids natural positive index # setting a token id to",
"count number of time a node is aligned to a token, indexed by",
"labeling for this sentence # amrs = list(amr_by_amrkey_by_sentence[skey].values()) # inform user if num_sentences",
"print(action_count.most_common(10)) if singletons: base_action_count = [x.split('(')[0] for x in singletons] msg = f'{len(singletons)}",
"# check if the node has been constructed, for multiple PREDs if gold_nodeid",
"next position in the token sequence REDUCE : delete current token MERGE :",
"sentences by removing whitespaces\" ) # copy lemma action parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use",
"actions sequence actions = oracle_builder.build_oracle_actions() # store data statistics['sentence_tokens'].append(oracle_builder.tokens) # do not write",
"label_shift(self.machine, self.multitask_words) valid_actions = [action] invalid_actions = [] return valid_actions, invalid_actions def build_oracle_actions(self):",
"from Spacy lemmas\" ) # copy lemma action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all addnode",
"= gold_amr.findSubGraph(tok_alignment).root if not is_named and ( gold_amr.nodes[root] in entities_with_preds or is_dependent): return",
") print(yellow_font(alert_str)) if num_labelings > num_unique_sents: num_inconsistent = num_labelings - num_unique_sents perc =",
"deprecate `multitask_words` or change for a better name such as `shift_label_words` # AMR",
"= self.gold_amr # get the node ids in the gold AMR graph nodes1",
"node2 = gold_amr.findSubGraph(nodes2).root else: node2 = nodes2[0] # find edges for s, r,",
"singletons = [k for k, c in action_count.items() if c == 1] print('Base",
"2) the aligned node has not been predicted yet \"\"\" machine = self.machine",
"\"\"\" machine = self.machine node_id = machine.current_node_id if node_id is None: # NOTE",
"stats about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t' )",
"for AMR alignment return gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of alignments between nodes",
"we need to be careful about the root node id which should be",
"order of inputs matter. (could also change to follow strict orders between these",
"self.nodeid_to_gold_nodeid[node_id] # gold_nodeids = list(set(gold_nodeids)) # just in case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id +",
"token return None tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE",
"\"--out-amr\", help=\"corresponding AMR\", type=str ) # parser.add_argument( \"--verbose\", action='store_true', help=\"verbose processing\" ) #",
"type=str ) parser.add_argument( \"--out-actions\", help=\"actions given by oracle\", type=str ) parser.add_argument( \"--out-action-stats\", help=\"statistics",
"self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1, list): nodes1 = [nodes1] if not",
"\"--in-multitask-words\", type=str, help=\"where to read top-k words for multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\", action='store_true',",
"repeated sentence_count.update([skey]) # hash of AMR labeling akey = amr.toJAMRString() # store different",
"None def get_arc(self, node_id1, node_id2): \"\"\" Get the arcs between node with `node_id1`",
"If 1) the current and the next token have the same node alignment.",
"as each time we scan all the possible edges continue if t not",
"sentence # amrs = list(amr_by_amrkey_by_sentence[skey].values()) # inform user if num_sentences > num_unique_sents: num_repeated",
"`node_id2`. RA if there is an edge `node_id1` --> `node_id2` LA if there",
"gold_nodeid = tok_alignment[0] else: # TODO check when this happens -> should we",
"or [... LA(pos,'root') SHIFT CLOSE] machine = self.machine while not machine.is_closed: valid_actions, invalid_actions",
"for two entities with same surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') PRED('city')",
"be -1 now # that is also massively used in postprocessing to find/add",
"return None # check if named entity case: (entity_category, ':name', 'name') # no",
"None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node = gold_amr.nodes[new_id] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if",
"append a special token at the end of the sentence for the first",
"to a token, indexed by # token node_by_token[token_str].update([node]) return node_by_token def is_most_common(node_counts, node,",
"r in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not",
"ENTITY(type) : form a named entity, or a subgraph PRED(label) : form a",
"gold_amr = preprocess_amr(gold_amr) # Initialize oracle builder oracle_builder = AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words)",
"is based on priority # e.g. within node-arc actions, arc subsequence comes highest,",
"empty (or singleton) if len(tok_alignment) <= 1: return None # check if there",
"process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words, add_root=False): # Load/Save words for multi-task if multitask_max_words: assert",
"print(f'{len(amrs)} sentences') node_label_count = Counter([ n for amr in amrs for n in",
"\"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor # to avoid",
"Initialize lemmatizer as this is slow lemmatizer = get_spacy_lemmatizer() # This will store",
"This will store the oracle stats statistics = { 'sentence_tokens': [], 'oracle_actions': [],",
"print some info print(f'{len(amrs)} sentences') node_label_count = Counter([ n for amr in amrs",
"== t and node2 == s: return ('LA', r) return None def run_oracle(gold_amrs,",
"the order of inputs matter. (could also change to follow strict orders between",
"re from tqdm import tqdm from transition_amr_parser.io import read_propbank, read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine",
"align to # repeat `add_unaligned` times if add_unaligned: for i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\")",
"= True root = gold_amr.findSubGraph(tok_alignment).root if not is_named and ( gold_amr.nodes[root] in entities_with_preds",
"predicted amr, the oracle adds it using the DEPENDENT action. \"\"\" machine =",
"gold_amr.alignments[n]: if gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)] break # add root node",
"these 2 ids) # TODO could there be more than one edges? #",
"# the node has not been built at current step return None #for",
"is fixed at -1 self.built_gold_nodeids = [] @property def tokens(self): return self.gold_amr.tokens @property",
"0: return 'REDUCE' else: return None def try_merge(self): \"\"\" Check if the next",
"line in fid: items = line.strip().split('\\t') if len(items) > 2: multitask_words.append(items[1]) return multitask_words",
"gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment empty (or singleton) if len(tok_alignment) <=",
"def __init__(self, gold_amr, lemmatizer, copy_lemma_action, multitask_words): self.gold_amr = gold_amr # initialize the state",
"been built at current step return None # NOTE this doesn't work for",
"return None # convert to single node aligned to each of these two",
"for one entity ENTITY('name') PRED('city') [other arcs] LA(pos,':name') b) for two entities with",
"and remove this cleaning process # an example is in training data, when",
"node_by_token = defaultdict(lambda: Counter()) for train_amr in gold_amrs_train: # Get alignments alignments =",
"multitask_words): tok = state_machine.get_current_token(lemma=False) if tok in multitask_words: return f'SHIFT({tok})' else: return 'SHIFT'",
"def try_entities_with_pred(self): \"\"\" allow pred inside entities that frequently need it i.e. person,",
"now assert len(valid_actions) == 1, \"Oracle must be deterministic\" assert len(invalid_actions) == 0,",
"the predicted amr, the oracle adds it using the DEPENDENT action. \"\"\" machine",
"'inconsistent labelings from repeated sents' ) print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$')",
"None # If both tokens are mapped to same node or overlap if",
"[nodes1] if not isinstance(nodes2, list): nodes2 = [nodes2] if not nodes1 or not",
"--> `node_id2` LA if there is an edge `node_id2` <-- `node_id2` Thus the",
"subgraph aligned to token 1 node1 = gold_amr.findSubGraph(nodes1).root else: node1 = nodes1[0] if",
"return statistics def main(): # Argument handling args = argument_parser() global entities_with_preds entities_with_preds",
"entity case: (entity_category, ':name', 'name') entity_edges = [] name_node_ids = [] for s,",
"if r.startswith(':') else r new_node = gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})' return action return",
"and the alignment. \"\"\" # Loop over potential actions # NOTE \"<ROOT>\" token",
"in the subgraph # gold_nodeids = self.nodeid_to_gold_nodeid[node_id] # gold_nodeids = list(set(gold_nodeids)) # just",
"get root of subgraph aligned to token 1 node1 = gold_amr.findSubGraph(nodes1).root else: node1",
"= gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node: action =",
"remove this cleaning process # an example is in training data, when the",
"amrs = list(amr_by_amrkey_by_sentence[skey].values()) # inform user if num_sentences > num_unique_sents: num_repeated = num_sentences",
"+ 1): alignments[al_node].append( train_amr.tokens[i] ) for node_id, aligned_tokens in alignments.items(): # join multiple",
"gold_amr.alignments[root_id] = [-1] # NOTE do not do this; we have made all",
"that rank matches len(node_counts) == rank + 1 and node_counts.most_common(rank + 1)[-1][0] ==",
"2) Only for :polarity and :mode, if an edge and node is aligned",
"if not action: action = self.try_entity() if not action: action = self.try_pred() if",
"a single node, or multiple nodes? (figure out) 2) the aligned node has",
"are outside of the sentence boundary # TODO check why this happens in",
"node from the beginning, so no prediction # for it here; the ending",
"-1 now # that is also massively used in postprocessing to find/add root.",
"tryPRED. If 1) aligned to more than 1 nodes, and 2) there are",
"string num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda:",
"node is automatically added at the beginning # NOTE to change this behavior,",
"sentence if args.out_rule_stats: with open(args.out_rule_stats, 'w') as fid: fid.write(json.dumps(stats['rules'])) if __name__ == '__main__':",
"stats = run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) # print stats about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) #",
"node1 == t and node2 == s: return ('LA', r) return None def",
"{:s} (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, 'repeated sents', max( count",
"aligned to each of these two tokens if len(nodes1) > 1: # get",
"type=str ) parser.add_argument( \"--out-sentences\", help=\"tokenized sentences from --in-amr\", type=str ) parser.add_argument( \"--out-actions\", help=\"actions",
"= [len(gold_amr.tokens)] # NOTE shifted by 1 for AMR alignment return gold_amr def",
"oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics def main(): # Argument handling args = argument_parser() global",
"fid.write(f'{word}\\n') elif in_multitask_words: assert not multitask_max_words assert not out_multitask_words # store in file",
"amr in amrs for w in amr.tokens]) word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens')",
"coupled with the PRED checks? and also the ENTITY if len(gold_nodeids) == 1:",
"the order here is important, which is based on priority # e.g. within",
"self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1, list): nodes1 = [nodes1] if not isinstance(nodes2, list): nodes2",
"machine self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action self.multitask_words = multitask_words",
"self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action self.multitask_words = multitask_words #",
"Check if the next action is REDUCE. If 1) there is nothing aligned",
"machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id +",
"act_node_id is None: continue # for multiple nodes out of one token -->",
"action: action = self.try_pred() if not action: if len(self.machine.actions) and self.machine.actions[-1] == 'SHIFT'",
"-> should we do multiple PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root # TODO for multiple",
"= num_labelings - num_unique_sents perc = num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f}",
"in gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid for tid in tids if tid <= len(gold_amr.tokens)]",
"else: multitask_words = None return multitask_words def print_corpus_info(amrs): # print some info print(f'{len(amrs)}",
"Actions are SHIFT : move cursor to next position in the token sequence",
"None is_dependent = False for s, r, t in edges: if r ==",
"if r in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root]",
"only return the first one. \"\"\" gold_amr = self.gold_amr # get the node",
"self.multitask_words is not None: action = label_shift(self.machine, self.multitask_words) valid_actions = [action] invalid_actions =",
"sentence]) # Restrict to top-k words allowed_words = dict(list(sorted( word_count.items(), key=lambda x: x[1])",
"args = argument_parser() global entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\") # Load AMR (replace some",
"100 * perc, 'repeated sents', max( count for counter in amr_counts_by_sentence.values() for count",
"get_valid_actions(self): \"\"\"Get the valid actions and invalid actions based on the current AMR",
"amr, the oracle adds it using the DEPENDENT action. \"\"\" machine = self.machine",
"# TODO: describe this # append a special token at the end of",
"and other normalizations should be applied more # transparently print(f'Reading {args.in_amr}') corpus =",
"fixed at -1 self.built_gold_nodeids = [] @property def tokens(self): return self.gold_amr.tokens @property def",
"aligned node has been predicted already 2) Only for :polarity and :mode, if",
"# amrs = list(amr_by_amrkey_by_sentence[skey].values()) # inform user if num_sentences > num_unique_sents: num_repeated =",
"reader instead of txt reader propbank_args = None if args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args)",
"machine = self.machine gold_amr = self.gold_amr if machine.current_node_id is not None: # not",
"node id to check edges arc = self.get_arc(act_node_id, node_id) if arc is None:",
"tokens(self): return self.gold_amr.tokens @property def time_step(self): return self.machine.time_step @property def actions(self): return self.machine.actions",
"transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine, get_spacy_lemmatizer ) \"\"\" This algorithm contains heuristics for generating",
"now # that is also massively used in postprocessing to find/add root. return",
"= [x.split('(')[0] for x in singletons] msg = f'{len(singletons)} singleton actions' print(yellow_font(msg)) print(Counter(base_action_count))",
"'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return None else: return None def try_named_entities(self): \"\"\"",
"sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count = Counter([t[1] for amr in amrs for t",
"machine machine.apply_action(action) # close machine # below are equivalent # machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr)",
"lemmatizer = get_spacy_lemmatizer() # This will store the oracle stats statistics = {",
"perc, 'repeated sents', max( count for counter in amr_counts_by_sentence.values() for count in counter.values()",
"new_node = gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})' return action return None def try_arcs(self): \"\"\"",
"edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count = Counter([w for amr in amrs",
"action def try_pred(self): \"\"\" Check if the next action is PRED, COPY_LEMMA, COPY_SENSE01.",
"blacklist actions\" action = valid_actions[0] # update the machine machine.apply_action(action) # close machine",
"> 1: # get root of subgraph aligned to token 2 node2 =",
"since the REDUCE check happens first if len(tok_alignment) == 1: gold_nodeid = tok_alignment[0]",
"is # ['Among', 'common', 'birds', ',', 'a', 'rather', 'special', 'one', 'is', # 'the',",
"MWEs) ENTITY(type) : form a named entity, or a subgraph PRED(label) : form",
"i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n in gold_amr.nodes: if n not in gold_amr.alignments",
"= gold_nodeids[0] else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for s, r, t in gold_amr.edges: if",
"oracle_builder.build_oracle_actions() # store data statistics['sentence_tokens'].append(oracle_builder.tokens) # do not write CLOSE action at the",
"return self.gold_amr.tokens @property def time_step(self): return self.machine.time_step @property def actions(self): return self.machine.actions def",
"which is based on priority # e.g. within node-arc actions, arc subsequence comes",
"same DEPENDENT added twice, as each time we scan all the possible edges",
"# NOTE to change this behavior, we need to be careful about the",
"shift args parser.add_argument( \"--out-multitask-words\", type=str, help=\"where to store top-k words for multi-task\" )",
"(or singleton) if len(tok_alignment) <= 1: return None # check if there is",
"close machine # below are equivalent # machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return",
"( AMRStateMachine, get_spacy_lemmatizer ) \"\"\" This algorithm contains heuristics for generating linearized action",
"a node from the beginning, so no prediction # for it here; the",
"two tokens if len(nodes1) > 1: # get root of subgraph aligned to",
"construction states info self.nodeid_to_gold_nodeid = {} # key: node id in the state",
"perc = num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % repeated sents (max",
"new_nodes = ','.join([gold_amr.nodes[n] for n in gold_nodeids]) action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids)",
"gold_amr.findSubGraph(nodes1).root else: node1 = nodes1[0] if len(nodes2) > 1: # get root of",
"Multiple input parameters parser.add_argument( \"--out-amr\", help=\"corresponding AMR\", type=str ) # parser.add_argument( \"--verbose\", action='store_true',",
"= [nodes2] if not nodes1 or not nodes2: return None # convert to",
"2 node2 = gold_amr.findSubGraph(nodes2).root else: node2 = nodes2[0] # find edges for s,",
"happens -> should we do multiple PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root # TODO for",
"# for it here; the ending sequence is always [... SHIFT CLOSE] or",
"scan all the possible edges continue if t not in gold_nodeids and (t",
"= self.try_arcs() #if not action: # action = self.try_named_entities() if not action: action",
"gold_amr.nodes: if n not in gold_amr.alignments or not gold_amr.alignments[n]: if gold_amr.nodes[n] in included_unaligned:",
"could be 0, 'if not node_id' would cause a bug # the node",
"alignments = defaultdict(list) for i in range(len(train_amr.tokens)): for al_node in train_amr.alignmentsToken2Node(i + 1):",
"multitask_words def label_shift(state_machine, multitask_words): tok = state_machine.get_current_token(lemma=False) if tok in multitask_words: return f'SHIFT({tok})'",
"f'SHIFT({tok})' else: return 'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count = Counter() for sentence",
"also change to follow strict orders between these 2 ids) # TODO could",
"== s and node2 == t: return ('RA', r) if node1 == t",
"gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True ) # run the oracle for the entire",
"# State machine stats for this sentence if args.out_rule_stats: with open(args.out_rule_stats, 'w') as",
"# close machine # below are equivalent # machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr)",
"actions\", type=str ) parser.add_argument( \"--out-rule-stats\", # TODO this is accessed by replacing '-'",
"= machine.tok_cursor + 1 cur_alignment = gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt +",
"\"--out-action-stats\", help=\"statistics about actions\", type=str ) parser.add_argument( \"--out-rule-stats\", # TODO this is accessed",
"PRED('city') [other arcs] LA(pos,':name') ENTITY('name') PRED('city') [other arcs] LA(pos,':name') \"\"\" machine = self.machine",
"sentence boundary # TODO check why this happens in the data reading process",
"read top-k words for multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab separation in",
"but is fine if we always use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge =",
"copy action from Spacy lemmas\" ) # copy lemma action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid",
"or is_dependent): return None gold_nodeids = [n for n in tok_alignment if any(s",
"token sentence, based on the gold AMR and the alignment. \"\"\" # Loop",
"Process AMRs one by one for sent_idx, gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO:",
"# below is coupled with the PRED checks? and also the ENTITY if",
"1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt + 1) if not cur_alignment or not nxt_alignment: return",
"actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences( args.out_sentences,",
"action: action = self.try_entity() if not action: action = self.try_pred() if not action:",
"- 1: cur = machine.tok_cursor nxt = machine.tok_cursor + 1 cur_alignment = gold_amr.alignmentsToken2Node(cur",
"PRED, COPY_LEMMA, COPY_SENSE01. If 1) the current token is aligned to a single",
"in that rank matches len(node_counts) == rank + 1 and node_counts.most_common(rank + 1)[-1][0]",
"idx, action in enumerate(actions): if pred_re.match(action): node_name = pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name)",
"are edges that have not been built with this node \"\"\" machine =",
"if len(nodes2) > 1: # get root of subgraph aligned to token 2",
"in gold_nodeids]) action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action def try_pred(self): \"\"\"",
"do a for loop here # check if the node has been constructed,",
"`node_id2` LA if there is an edge `node_id2` <-- `node_id2` Thus the order",
"predicted already 2) Only for :polarity and :mode, if an edge and node",
") parser.add_argument( \"--out-actions\", help=\"actions given by oracle\", type=str ) parser.add_argument( \"--out-action-stats\", help=\"statistics about",
"current step return None #for act_id, act_node_id in enumerate(machine.actions_to_nodes): for act_id, act_node_id in",
"if not isinstance(nodes2, list): nodes2 = [nodes2] if not nodes1 or not nodes2:",
"not is_named and ( gold_amr.nodes[root] in entities_with_preds or is_dependent): return None gold_nodeids =",
"read_multitask_words(multitask_list): multitask_words = [] with open(multitask_list) as fid: for line in fid: items",
"= gold_amr # initialize the state machine self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds)",
"sentence for the first unaligned node # whose label is in `included_unaligned` to",
"num_repeated, num_sentences, 100 * perc, 'repeated sents', max( count for counter in amr_counts_by_sentence.values()",
"Counter()) for train_amr in gold_amrs_train: # Get alignments alignments = defaultdict(list) for i",
"# count number of time sentence repeated sentence_count.update([skey]) # hash of AMR labeling",
"not action: action = self.try_arcs() #if not action: # action = self.try_named_entities() if",
"-1) for nid, tids in gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid for tid in tids",
"None def try_arcs(self): \"\"\" Get the arcs that involve the current token aligned",
"DEPENDENT(edge,node) : Add a node which is a dependent of the current node",
"the REDUCE check happens first if len(tok_alignment) == 1: gold_nodeid = tok_alignment[0] else:",
"used in postprocessing to find/add root. return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1)",
"+ 1 cur_alignment = gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt + 1) if",
"in actions: if pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions))",
"AMRs one by one for sent_idx, gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO: See",
"in machine.amr.edges: continue # pointer value arc_pos = act_id return f'{arc_name}({arc_pos},{arc_label})' return None",
"equivalent # machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions def try_reduce(self): \"\"\" Check",
":polarity and :mode, if an edge and node is aligned to this token",
"# to prevent same DEPENDENT added twice, as each time we scan all",
"sequence for the current token sentence, based on the gold AMR and the",
"else: # TODO check when this happens -> should we do multiple PRED?",
"'oracle_amr': [], 'rules': { # Will store count of PREDs given pointer position",
"and fix that and remove this cleaning process # an example is in",
"'MERGE' return None else: return None def try_named_entities(self): \"\"\" Get the named entity",
"is_named = False for s, r, t in edges: if r == ':name'",
"parser.add_argument( \"--multitask-max-words\", type=int, help=\"number of woprds to use for multi-task\" ) # Labeled",
"over potential actions # NOTE \"<ROOT>\" token at last position is added as",
"more than one edges? # currently we only return the first one. \"\"\"",
"gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root)) # gold_amr.alignments[root_id] = [-1] # NOTE",
"sequences for AMR graphs in a rule based way. The parsing algorithm is",
"> num_unique_sents: num_inconsistent = num_labelings - num_unique_sents perc = num_inconsistent / num_sentences alert_str",
"return None for s, r, t in entity_edges: if t not in self.built_gold_nodeids:",
"= '{:d}/{:d} {:2.4f} % inconsistent labelings from repeated sents'.format( num_inconsistent, num_sentences, perc )",
"list): nodes1 = [nodes1] if not isinstance(nodes2, list): nodes2 = [nodes2] if not",
"one single expression if len(aligned_tokens) > 1: token_str = \" \".join(aligned_tokens) else: token_str",
"elif f'{lemma}-01' == new_node: action = 'COPY_SENSE01' else: action = f'PRED({new_node})' else: action",
"token (segments). E.g. a) for one entity ENTITY('name') PRED('city') [other arcs] LA(pos,':name') b)",
"of sentence skey = \" \".join(amr.tokens) # count number of time sentence repeated",
"# Will store count of PREDs given pointer position 'possible_predicates': defaultdict(lambda: Counter()) }",
"assert out_multitask_words # get top words multitask_words = get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root )",
"gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo = {} # clean invalid alignments: sometimes the alignments",
"return action def try_pred(self): \"\"\" Check if the next action is PRED, COPY_LEMMA,",
"!= None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node = gold_amr.nodes[new_id] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True)",
"# print stats about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'],",
"add_root: # Add root regardless allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words,",
"the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None # check",
"LA(pos,':name') PRED('city') [other arcs] LA(pos,':name') c) for two entities with two surface tokens",
"[... SHIFT CLOSE] or [... LA(pos,'root') SHIFT CLOSE] machine = self.machine while not",
"pos CLOSE : complete AMR, run post-processing \"\"\" use_addnode_rules = True def argument_parser():",
"not action: action = self.try_merge() #if not action: # action = self.try_dependent() if",
"if r == ':name' and gold_amr.nodes[t] == 'name': entity_edges.append((s, r, t)) name_node_ids.append(t) if",
"f'{lemma}-01' == new_node: action = 'COPY_SENSE01' else: action = f'PRED({new_node})' else: action =",
"action = self.try_named_entities() if not action: action = self.try_entities_with_pred() if not action: action",
"gold_amr.alignments[nid] = [tid for tid in tids if tid <= len(gold_amr.tokens)] # TODO:",
"the next token have the same node alignment. \"\"\" machine = self.machine gold_amr",
":mode, if an edge and node is aligned to this token in the",
"return ('RA', r) if node1 == t and node2 == s: return ('LA',",
"a left arc to the current node from the previous node at location",
"len(oracle_actions) source_lengths = [] target_lengths = [] action_count = Counter() for tokens, actions",
"is_most_common(node_counts, node, rank=0): return ( ( # as many results as the rank",
"# debug # on dev set, sentence id 459 (starting from 0) ->",
"any edge with the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return",
"r, t in edges: if s not in self.built_gold_nodeids: new_id = s break",
"oracle builder oracle_builder = AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words) # build the oracle actions",
"to remove pointer for action in actions: if pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups() action",
"position in the token sequence REDUCE : delete current token MERGE : merge",
"and node is aligned to this token in the gold amr but does",
"from tqdm import tqdm from transition_amr_parser.io import read_propbank, read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import",
"problem when the root aligned token id is sentence length (not -1) for",
"+ 1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt + 1) if not cur_alignment or not nxt_alignment:",
"__init__(self, gold_amr, lemmatizer, copy_lemma_action, multitask_words): self.gold_amr = gold_amr # initialize the state machine",
"hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count) num_labelings = 0 for skey, sent_count in",
"and the gold AMR.\"\"\" # find the next action # NOTE the order",
"gold_amr.nodes[new_id] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node: action = 'COPY_LEMMA'",
"pred_re.match(action): node_name = pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics def main(): #",
"% {:s} (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, 'repeated sents', max(",
"for act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is None: continue # for multiple",
") print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) == len(oracle_actions) source_lengths",
"1: return None # check if there is any edge with the aligned",
"strict orders between these 2 ids) # TODO could there be more than",
"this sentence # amrs = list(amr_by_amrkey_by_sentence[skey].values()) # inform user if num_sentences > num_unique_sents:",
"= read_amr(args.in_amr, unicode_fixes=True) gold_amrs = corpus.amrs # sanity check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) #",
"and surface words\"\"\" node_by_token = defaultdict(lambda: Counter()) for train_amr in gold_amrs_train: # Get",
"characters) # TODO: unicode fixes and other normalizations should be applied more #",
"self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node = gold_amr.nodes[new_id] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma",
"natural index # check if the alignment is empty # no need since",
"the current token is aligned to a single node, or multiple nodes? (figure",
"after named entities if tok_id in machine.entity_tokenids: return None # NOTE currently do",
"two entities with two surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') ENTITY('name') PRED('city')",
"top-k words for multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab separation in actions",
"the current AMR state machine status and the gold AMR.\"\"\" # find the",
"return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment empty (or",
"# Initialize lemmatizer as this is slow lemmatizer = get_spacy_lemmatizer() # This will",
"token. \"\"\" machine = self.machine gold_amr = self.gold_amr if machine.current_node_id is not None:",
"from the current surface token (segments). E.g. a) for one entity ENTITY('name') PRED('city')",
"machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor if tok_id == machine.tokseq_len",
"( # more results than the rank, node in that rank matches, and",
"is always [... SHIFT CLOSE] or [... LA(pos,'root') SHIFT CLOSE] machine = self.machine",
"f'PRED({new_node})' return action else: return None def try_dependent(self): \"\"\" Check if the next",
"for ENTITY now, as the mapping from ENTITY node is only to the",
"def main(): # Argument handling args = argument_parser() global entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\")",
"node_counts.most_common(rank + 2)[-1][1] ) ) def sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs) sentence_count = Counter()",
"the current node LA(pos,label) : form a left arc from the current node",
"when the root aligned token id is sentence length (not -1) for nid,",
"subgraph, and then 3) take the source nodes in the aligned subgraph altogether.",
"# get root of subgraph aligned to token 1 node1 = gold_amr.findSubGraph(nodes1).root else:",
"string entities_with_preds = [] def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1): # clean alignments for",
"1) aligned to more than 1 nodes, and 2) there are edges in",
"check if alignment empty (or singleton) if len(tok_alignment) <= 1: return None #",
"machine status and the gold AMR.\"\"\" # find the next action # NOTE",
">= 8: # breakpoint() action = self.try_reduce() if not action: action = self.try_merge()",
"in edges: if s not in self.built_gold_nodeids: new_id = s break if t",
"None def try_entity(self): \"\"\" Check if the next action is ENTITY. TryENTITY before",
"1: # get root of subgraph aligned to token 2 node2 = gold_amr.findSubGraph(nodes2).root",
"ENTITY node is only to the source nodes in the # aligned subgraph,",
"} } pred_re = re.compile(r'^PRED\\((.*)\\)$') # Process AMRs one by one for sent_idx,",
"if the next action is REDUCE. If 1) there is nothing aligned to",
"if the alignment is empty # no need since the REDUCE check happens",
"return gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of alignments between nodes and surface words\"\"\"",
"is nothing aligned to a token. \"\"\" machine = self.machine gold_amr = self.gold_amr",
"machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE the index + 1 if",
"[], 'oracle_actions': [], 'oracle_amr': [], 'rules': { # Will store count of PREDs",
"len(amr_counts_by_sentence[skey]) > 1: pass # There is more than one labeling for this",
"as fid: multitask_words = [line.strip() for line in fid.readlines()] else: multitask_words = None",
"# TODO this is accessed by replacing '-' to '_' help=\"statistics about alignments\",",
"gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid for tid in tids if tid <= len(gold_amr.tokens)] #",
"pos RA(pos,label) : form a left arc to the current node from the",
"for amr in amrs for t in amr.edges]) edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge",
"same node or overlap if cur_alignment == nxt_alignment: return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return",
"tokens, actions in zip(sentence_tokens, oracle_actions): # filter actions to remove pointer for action",
"multitask_max_words, in_multitask_words, out_multitask_words, add_root=False): # Load/Save words for multi-task if multitask_max_words: assert multitask_max_words",
"etc. # debug # on dev set, sentence id 459 (starting from 0)",
"named entities if tok_id in machine.entity_tokenids: return None # NOTE currently do not",
"multiple nodes? (figure out) 2) the aligned node has not been predicted yet",
"index # check if the alignment is empty # no need since the",
"<reponame>IBM/transition-amr-parser import json import argparse from collections import Counter, defaultdict import re from",
"`node_id2` Thus the order of inputs matter. (could also change to follow strict",
"aligned to a token, indexed by # token node_by_token[token_str].update([node]) return node_by_token def is_most_common(node_counts,",
"the first time on a new token return None if machine.tok_cursor < machine.tokseq_len",
"current surface token (segments). E.g. a) for one entity ENTITY('name') PRED('city') [other arcs]",
") # copy lemma action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all addnode actions appearing less",
"can\\'t blacklist actions\" action = valid_actions[0] # update the machine machine.apply_action(action) # close",
"1) gold_amr.token2node_memo = {} # clean invalid alignments: sometimes the alignments are outside",
"node alignment. \"\"\" machine = self.machine gold_amr = self.gold_amr if machine.current_node_id is not",
"a) for one entity ENTITY('name') PRED('city') [other arcs] LA(pos,':name') b) for two entities",
"action sequences for AMR graphs in a rule based way. The parsing algorithm",
"action = label_shift(self.machine, self.multitask_words) valid_actions = [action] invalid_actions = [] return valid_actions, invalid_actions",
"# NOTE the index + 1 if len(tok_alignment) == 0: return 'REDUCE' else:",
"repeated sents' ) print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) ==",
"new_id = t break if new_id != None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node =",
"assert len(sentence_tokens) == len(oracle_actions) source_lengths = [] target_lengths = [] action_count = Counter()",
"machine.tok_cursor node_id = machine.current_node_id if node_id is None: # NOTE if node_id could",
"== ['The', 'cyber', 'attacks', 'were', 'unprecedented', '.', '<ROOT>']: # if self.time_step >= 8:",
"in train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append( train_amr.tokens[i] ) for node_id, aligned_tokens in alignments.items(): #",
"Argument handling args = argument_parser() global entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\") # Load AMR",
"\"\"\" gold_amr = self.gold_amr # get the node ids in the gold AMR",
"Check if the next action is PRED, COPY_LEMMA, COPY_SENSE01. If 1) the current",
"lemma and add '01' DEPENDENT(edge,node) : Add a node which is a dependent",
"is REDUCE. If 1) there is nothing aligned to a token. \"\"\" machine",
"Load AMR (replace some unicode characters) # TODO: unicode fixes and other normalizations",
"help=\"where to store top-k words for multi-task\" ) parser.add_argument( \"--in-multitask-words\", type=str, help=\"where to",
"and the next token have the same node alignment. \"\"\" machine = self.machine",
"add_root=False): # Load/Save words for multi-task if multitask_max_words: assert multitask_max_words assert out_multitask_words #",
"here XML propbank reader instead of txt reader propbank_args = None if args.in_propbank_args:",
"action # NOTE the order here is important, which is based on priority",
"= self.gold_amr tok_id = machine.tok_cursor if tok_id == machine.tokseq_len - 1: # never",
"to the source nodes in the # aligned subgraph, whereas for the DEPENDENT",
"\"\"\" Get the arcs that involve the current token aligned node. If 1)",
"training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions def try_reduce(self): \"\"\" Check if the next",
"word_count.items(), key=lambda x: x[1]) )[-max_symbols:]) if add_root: # Add root regardless allowed_words.update({'ROOT': word_count['ROOT']})",
"r, t in edges: if r == ':name' and gold_amr.nodes[t] == 'name': entity_edges.append((s,",
"# TODO deprecate `multitask_words` or change for a better name such as `shift_label_words`",
"in sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) > 1: pass # There is",
"if any(s == n for s, r, t in edges)] new_nodes = ','.join([gold_amr.nodes[n]",
"ids positive natural index # check if the alignment is empty # no",
"add_unaligned: for i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for n in gold_amr.nodes: if n not",
"if lemma == new_node: action = 'COPY_LEMMA' elif f'{lemma}-01' == new_node: action =",
"None def try_dependent(self): \"\"\" Check if the next action is DEPENDENT. If 1)",
"form a new node by copying lemma and add '01' DEPENDENT(edge,node) : Add",
"words\"\"\" node_by_token = defaultdict(lambda: Counter()) for train_amr in gold_amrs_train: # Get alignments alignments",
": form a new node by copying lemma COPY_SENSE01 : form a new",
"COPY_SENSE01 : form a new node by copying lemma and add '01' DEPENDENT(edge,node)",
"+ 2)[-1][1] ) ) def sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence",
"in amr.nodes.values() ]) node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count = Counter([t[1] for",
"tok_id in machine.entity_tokenids: return None # NOTE currently do not allow multiple ENTITY",
"'possible_predicates': defaultdict(lambda: Counter()) } } pred_re = re.compile(r'^PRED\\((.*)\\)$') # Process AMRs one by",
"it i.e. person, thing \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id =",
"amrs for t in amr.edges]) edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count =",
"True root = gold_amr.findSubGraph(tok_alignment).root if not is_named and ( gold_amr.nodes[root] in entities_with_preds or",
"setting a token id to -1 will break the code gold_amr.alignments[root_id] = [len(gold_amr.tokens)]",
"if (node_id, r) in [(e[0], e[1]) for e in machine.amr.edges]: # to prevent",
"= gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})' return action return None def try_arcs(self): \"\"\" Get",
"the oracle for the entire corpus stats = run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) # print",
"= f'DEPENDENT({new_node},{new_edge})' return action return None def try_arcs(self): \"\"\" Get the arcs that",
"in the aligned subgraph, and then 3) take the source nodes in the",
"step return None #for act_id, act_node_id in enumerate(machine.actions_to_nodes): for act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))):",
"print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string num_sentences = len(gold_amrs) sentence_count",
"but does not exist in the predicted amr, the oracle adds it using",
"== nxt_alignment: return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return None else: return None",
"lemmatizer, copy_lemma_action, multitask_words) # build the oracle actions sequence actions = oracle_builder.build_oracle_actions() #",
"sanity check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load propbank if provided # TODO: Use",
"parser.add_argument( \"--out-multitask-words\", type=str, help=\"where to store top-k words for multi-task\" ) parser.add_argument( \"--in-multitask-words\",",
"def get_arc(self, node_id1, node_id2): \"\"\" Get the arcs between node with `node_id1` and",
"if tok in multitask_words: return f'SHIFT({tok})' else: return 'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False):",
"machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment empty (or singleton)",
"multiple nodes out of one token --> need to use node id to",
"with the PRED checks? and also the ENTITY if len(gold_nodeids) == 1: gold_nodeid",
"for a better name such as `shift_label_words` # AMR construction states info self.nodeid_to_gold_nodeid",
"as many results as the rank and node in that rank matches len(node_counts)",
"[other arcs] LA(pos,':name') \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor",
"machine.tokseq_len - 1: cur = machine.tok_cursor nxt = machine.tok_cursor + 1 cur_alignment =",
"self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge = r[1:] if r.startswith(':') else r new_node = gold_amr.nodes[t] action",
"if machine.current_node_id in machine.entities: return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check",
"use_addnode_rules = True def argument_parser(): parser = argparse.ArgumentParser(description='AMR parser oracle') # Single input",
"parser.add_argument( \"--out-sentences\", help=\"tokenized sentences from --in-amr\", type=str ) parser.add_argument( \"--out-actions\", help=\"actions given by",
"= 'SHIFT' if action == 'SHIFT' and self.multitask_words is not None: action =",
"= ','.join([gold_amr.nodes[n] for n in gold_nodeids]) action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return",
": complete AMR, run post-processing \"\"\" use_addnode_rules = True def argument_parser(): parser =",
"same as <eos> in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules for idx, action",
"length (not -1) for nid, tids in gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid for tid",
"Get alignments alignments = defaultdict(list) for i in range(len(train_amr.tokens)): for al_node in train_amr.alignmentsToken2Node(i",
"training data, when the sentence is # ['Among', 'common', 'birds', ',', 'a', 'rather',",
"\"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma separated list of entity types that can have pred\"",
"x: x[1]) )[-max_symbols:]) if add_root: # Add root regardless allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words",
"w in amr.tokens]) word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class AMROracleBuilder: \"\"\"Build AMR",
"is more than one labeling for this sentence # amrs = list(amr_by_amrkey_by_sentence[skey].values()) #",
"entity ENTITY('name') PRED('city') [other arcs] LA(pos,':name') b) for two entities with same surface",
"in amrs for n in amr.nodes.values() ]) node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens')",
"the alignment is empty # no need since the REDUCE check happens first",
"(node_id, r) in [(e[0], e[1]) for e in machine.amr.edges]: # to prevent same",
"arc_name == 'RA': if (act_node_id, arc_label, node_id) in machine.amr.edges: continue # pointer value",
"SHIFT : move cursor to next position in the token sequence REDUCE :",
"to find/add root. return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE we",
"`shift_label_words` # AMR construction states info self.nodeid_to_gold_nodeid = {} # key: node id",
"oracle_builder = AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words) # build the oracle actions sequence actions",
"txt reader propbank_args = None if args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args) # read/write multi-task",
"# Loop over potential actions # NOTE \"<ROOT>\" token at last position is",
"store in file with open(in_multitask_words) as fid: multitask_words = [line.strip() for line in",
"i, tok in enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i + 1) if len(align) == 2:",
"t) for s, r, t in gold_amr.edges if s in align and t",
"json import argparse from collections import Counter, defaultdict import re from tqdm import",
"action = f'PRED({new_node})' else: action = f'PRED({new_node})' return action else: return None def",
"separation in actions and sentences by removing whitespaces\" ) # copy lemma action",
"info self.nodeid_to_gold_nodeid = {} # key: node id in the state machine, value:",
"args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args) # read/write multi-task (labeled shift) action # TODO: Add",
"args.in_pred_entities.split(\",\") # Load AMR (replace some unicode characters) # TODO: unicode fixes and",
"REDUCE check happens first if len(tok_alignment) == 1: gold_nodeid = tok_alignment[0] else: #",
"len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ): remove = 0 gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo = {}",
"Counter([t[1] for amr in amrs for t in amr.edges]) edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens}",
"gold_amr.findSubGraph(tok_alignment).root # TODO for multiple PREDs, we need to do a for loop",
"token --> need to use node id to check edges arc = self.get_arc(act_node_id,",
"why this happens in the data reading process # TODO and fix that",
"len(nodes2) > 1: # get root of subgraph aligned to token 2 node2",
"- 1 : action = 'REDUCE' else: action = 'SHIFT' if action ==",
"type=str, default=\"person,thing\", help=\"comma separated list of entity types that can have pred\" )",
"len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda: Counter()) for amr",
"sentences') node_label_count = Counter([ n for amr in amrs for n in amr.nodes.values()",
"aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None # check if",
"'name') # no need, since named entity check happens first is_dependent = False",
"we are checking the target nodes in the subgraph # gold_nodeids = self.nodeid_to_gold_nodeid[node_id]",
"read_amr(args.in_amr, unicode_fixes=True) gold_amrs = corpus.amrs # sanity check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load",
"in range(len(train_amr.tokens)): for al_node in train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append( train_amr.tokens[i] ) for node_id,",
"node_by_token def is_most_common(node_counts, node, rank=0): return ( ( # as many results as",
"ENTITY('name') PRED('city') [other arcs] LA(pos,':name') \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id",
"a better name such as `shift_label_words` # AMR construction states info self.nodeid_to_gold_nodeid =",
"> num_unique_sents: num_repeated = num_sentences - num_unique_sents perc = num_repeated / num_sentences alert_str",
"the node has been constructed, for multiple PREDs if gold_nodeid not in self.built_gold_nodeids:",
"action from Spacy lemmas\" ) # copy lemma action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all",
"this happens in the data reading process # TODO and fix that and",
"# action = self.try_dependent() if not action: action = self.try_arcs() #if not action:",
"is important, which is based on priority # e.g. within node-arc actions, arc",
"nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None # check if named",
"amr labels for same sent, keep has map if akey not in amr_by_amrkey_by_sentence[skey]:",
"have pred\" ) args = parser.parse_args() return args def yellow_font(string): return \"\\033[93m%s\\033[0m\" %",
"not exist in the predicted amr, the oracle adds it using the DEPENDENT",
"a single token if machine.current_node_id in machine.entities: return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id +",
"2) there are edges that have not been built with this node \"\"\"",
"= len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda: Counter()) for",
"value: list of node ids in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] # NOTE",
"skey, sent_count in sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) > 1: pass #",
"which is a dependent of the current node LA(pos,label) : form a left",
"not write CLOSE action at the end; # CLOSE action is internally managed,",
"action is ENTITY. TryENTITY before tryPRED. If 1) aligned to more than 1",
"import json import argparse from collections import Counter, defaultdict import re from tqdm",
"= self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor # to avoid subgraph ENTITY",
"this might affect the next DEPEDENT check, but is fine if we always",
"AMR\", type=str ) # parser.add_argument( \"--verbose\", action='store_true', help=\"verbose processing\" ) # parser.add_argument( \"--multitask-max-words\",",
"= gold_amr.alignmentsToken2Node(i + 1) if len(align) == 2: edges = [ (s, r,",
"defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda: Counter()) for amr in gold_amrs: # hash of sentence",
"to top-k words allowed_words = dict(list(sorted( word_count.items(), key=lambda x: x[1]) )[-max_symbols:]) if add_root:",
"None for s, r, t in entity_edges: if t not in self.built_gold_nodeids: self.built_gold_nodeids.append(t)",
"= amr # count how many time each hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents =",
"return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE we make all token",
"node_id could be 0, 'if not node_id' would cause a bug # the",
"for x in singletons] msg = f'{len(singletons)} singleton actions' print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs):",
"defaultdict(list) for i in range(len(train_amr.tokens)): for al_node in train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append( train_amr.tokens[i]",
"time on a new token return None if machine.tok_cursor < machine.tokseq_len - 1:",
"n in tok_alignment if any(s == n for s, r, t in edges)]",
"not in gold_nodeids and (t in gold_amr.alignments and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) # NOTE",
"tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') ENTITY('name') PRED('city') [other arcs] LA(pos,':name') \"\"\" machine",
"parameters parser.add_argument( \"--out-amr\", help=\"corresponding AMR\", type=str ) # parser.add_argument( \"--verbose\", action='store_true', help=\"verbose processing\"",
"has not been built at current step return None # NOTE this doesn't",
"check, but is fine if we always use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge",
"is_dependent = False is_named = False for s, r, t in edges: if",
"not isinstance(nodes2, list): nodes2 = [nodes2] if not nodes1 or not nodes2: return",
"as <eos> in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules for idx, action in",
"node aligned to each of these two tokens if len(nodes1) > 1: #",
"one labeling for this sentence # amrs = list(amr_by_amrkey_by_sentence[skey].values()) # inform user if",
"[] def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1): # clean alignments for i, tok in",
"gold_amr.nodes[t] == 'name': entity_edges.append((s, r, t)) name_node_ids.append(t) if not name_node_ids: return None for",
"= 'COPY_SENSE01' else: action = f'PRED({new_node})' else: action = f'PRED({new_node})' return action return",
"unicode_fixes=True) gold_amrs = corpus.amrs # sanity check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load propbank",
"None # check if named entity case: (entity_category, ':name', 'name') # no need,",
"in tok_alignment if any(s == n for s, r, t in edges)] new_nodes",
"'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count = Counter() for sentence in tokenized_corpus: word_count.update([x",
"PREDs if gold_nodeid not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid] if",
"in [':polarity', ':mode']: if (node_id, r) in [(e[0], e[1]) for e in machine.amr.edges]:",
"def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of alignments between nodes and surface words\"\"\" node_by_token =",
"(entity_category, ':name', 'name') entity_edges = [] name_node_ids = [] for s, r, t",
"actions to remove pointer for action in actions: if pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups()",
"in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if not is_named and",
"about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences(",
"num_inconsistent = num_labelings - num_unique_sents perc = num_inconsistent / num_sentences alert_str = '{:d}/{:d}",
"for n in gold_nodeids]) action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action def",
"to each of these two tokens if len(nodes1) > 1: # get root",
"== node ) or ( # more results than the rank, node in",
"name_node_ids: return None for s, r, t in entity_edges: if t not in",
"label COPY_LEMMA : form a new node by copying lemma COPY_SENSE01 : form",
"= None if args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args) # read/write multi-task (labeled shift) action",
"root = gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not in entities_with_preds and not is_dependent: return None",
"len(nodes1) > 1: # get root of subgraph aligned to token 1 node1",
"machine.amr.edges: continue if arc_name == 'RA': if (act_node_id, arc_label, node_id) in machine.amr.edges: continue",
"= self.try_entities_with_pred() if not action: action = self.try_entity() if not action: action =",
"there is any edge with the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not",
"named entity, or a subgraph PRED(label) : form a new node with label",
"gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)] break # add root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id]",
"at the end; # CLOSE action is internally managed, and treated same as",
"invalid_actions = self.get_valid_actions() # for now assert len(valid_actions) == 1, \"Oracle must be",
"else: action = f'PRED({new_node})' return action return None def try_entity(self): \"\"\" Check if",
"and then 3) take the source nodes in the aligned subgraph altogether. \"\"\"",
"nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1, list): nodes1 = [nodes1]",
"change this behavior, we need to be careful about the root node id",
") parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab separation in actions and sentences by removing",
"preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1): # clean alignments for i, tok in enumerate(gold_amr.tokens): align",
"words allowed_words = dict(list(sorted( word_count.items(), key=lambda x: x[1]) )[-max_symbols:]) if add_root: # Add",
"self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) #",
"run the oracle for the entire corpus stats = run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) #",
"args.out_actions, stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t' ) # State machine stats",
"None def try_entities_with_pred(self): \"\"\" allow pred inside entities that frequently need it i.e.",
"aligned to a single node, or multiple nodes? (figure out) 2) the aligned",
"the first one. \"\"\" gold_amr = self.gold_amr # get the node ids in",
"help=\"where to read top-k words for multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab",
"+ 1) # below is coupled with the PRED checks? and also the",
"a new node with label COPY_LEMMA : form a new node by copying",
"= self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1, list): nodes1 = [nodes1] if",
"nodes, and 2) there are edges in the aligned subgraph, and then 3)",
"not in gold_amr.alignments or not gold_amr.alignments[n]: if gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)]",
"is aligned to a single node, or multiple nodes? (figure out) 2) the",
"# as many results as the rank and node in that rank matches",
"None # check if there is any edge with the aligned nodes edges",
"self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)' if s not in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id,",
"counter.values() ) ) print(yellow_font(alert_str)) if num_labelings > num_unique_sents: num_inconsistent = num_labelings - num_unique_sents",
"gold_amr.alignmentsToken2Node(i + 1) if len(align) == 2: edges = [ (s, r, t)",
"the PRED checks? and also the ENTITY if len(gold_nodeids) == 1: gold_nodeid =",
"/ num_sentences alert_str = '{:d}/{:d} {:2.1f} % repeated sents (max {:d} times)'.format( num_repeated,",
"[]).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node:",
"need, since named entity check happens first is_dependent = False is_named = False",
"current token MERGE : merge two tokens (for MWEs) ENTITY(type) : form a",
"in gold_amr.alignments or not gold_amr.alignments[n]: if gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)] break",
"\"--out-oracle\", help=\"tokens, AMR notation and actions given by oracle\", type=str ) parser.add_argument( \"--out-sentences\",",
"for word in multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words: assert not multitask_max_words assert not out_multitask_words",
"is None: continue # for multiple nodes out of one token --> need",
"s, r, t in edges: if r == ':name' and gold_amr.nodes[t] == 'name':",
"more results than the rank, node in that rank matches, and rank #",
"token, indexed by # token node_by_token[token_str].update([node]) return node_by_token def is_most_common(node_counts, node, rank=0): return",
"3) take the source nodes in the aligned subgraph altogether. \"\"\" machine =",
"\"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor node_id = machine.current_node_id",
"t not in gold_nodeids and (t in gold_amr.alignments and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) #",
"allow multiple ENTITY here on a single token if machine.current_node_id in machine.entities: return",
"TODO check why this happens in the data reading process # TODO and",
"\" \".join(aligned_tokens) else: token_str = aligned_tokens[0] node = train_amr.nodes[node_id] # count number of",
"gold_amr.edges.append((root_id, \"root\", gold_amr.root)) # gold_amr.alignments[root_id] = [-1] # NOTE do not do this;",
"\"\\033[93m%s\\033[0m\" % string num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence",
"token if machine.current_node_id in machine.entities: return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) #",
"fid: items = line.strip().split('\\t') if len(items) > 2: multitask_words.append(items[1]) return multitask_words def label_shift(state_machine,",
"'if not node_id' would cause a bug # the node has not been",
"times)'.format( num_repeated, num_sentences, 100 * perc, 'repeated sents', max( count for counter in",
"num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % {:s}'.format( num_inconsistent, num_sentences, perc, 'inconsistent",
"for amr in amrs for w in amr.tokens]) word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word",
"self.try_merge() #if not action: # action = self.try_dependent() if not action: action =",
"':name', 'name') # no need, since named entity check happens first is_dependent =",
"tok_id == machine.tokseq_len - 1: # never do PRED(<ROOT>) currently, as the root",
"# store in file with open(in_multitask_words) as fid: multitask_words = [line.strip() for line",
"self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma ==",
"self.machine.actions[-1] == 'SHIFT' and self.machine.tok_cursor != self.machine.tokseq_len - 1 : action = 'REDUCE'",
"in gold_amr.edges: if node1 == s and node2 == t: return ('RA', r)",
"# Labeled shift args parser.add_argument( \"--out-multitask-words\", type=str, help=\"where to store top-k words for",
"lemma action parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use copy action from Spacy lemmas\" ) #",
"from repeated sents'.format( num_inconsistent, num_sentences, perc ) print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words = []",
"root regardless allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words, add_root=False): #",
"len(gold_amr.alignments[align[1]]) ): remove = 0 gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo = {} # clean",
"gold_nodeid = gold_amr.findSubGraph(tok_alignment).root # TODO for multiple PREDs, we need to do a",
"target nodes in the subgraph # gold_nodeids = self.nodeid_to_gold_nodeid[node_id] # gold_nodeids = list(set(gold_nodeids))",
"time on a new token return None tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id",
"is MERGE. If 1) the current and the next token have the same",
"# hash of sentence skey = \" \".join(amr.tokens) # count number of time",
"merge two tokens (for MWEs) ENTITY(type) : form a named entity, or a",
"<= len(gold_amr.tokens)] # TODO: describe this # append a special token at the",
"num_unique_sents = len(sentence_count) num_labelings = 0 for skey, sent_count in sentence_count.items(): num_labelings +=",
"1 : action = 'REDUCE' else: action = 'SHIFT' if action == 'SHIFT'",
"made all the token ids natural positive index # setting a token id",
"# results is more probable than rank + 1 len(node_counts) > rank +",
"= self.machine while not machine.is_closed: valid_actions, invalid_actions = self.get_valid_actions() # for now assert",
"then 3) take the source nodes in the aligned subgraph altogether. \"\"\" machine",
"or multiple nodes? (figure out) 2) the aligned node has not been predicted",
"gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node: action = 'COPY_LEMMA'",
"(segments). E.g. a) for one entity ENTITY('name') PRED('city') [other arcs] LA(pos,':name') b) for",
"token is aligned to a single node, or multiple nodes? (figure out) 2)",
"1) the current and the next token have the same node alignment. \"\"\"",
"machine.is_closed: valid_actions, invalid_actions = self.get_valid_actions() # for now assert len(valid_actions) == 1, \"Oracle",
"aligned_tokens in alignments.items(): # join multiple words into one single expression if len(aligned_tokens)",
"a node is aligned to a token, indexed by # token node_by_token[token_str].update([node]) return",
"yet \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor if tok_id",
"help=\"statistics about alignments\", type=str ) # Multiple input parameters parser.add_argument( \"--out-amr\", help=\"corresponding AMR\",",
"from transition_amr_parser.io import read_propbank, read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine, get_spacy_lemmatizer )",
"gold_amr # initialize the state machine self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action",
"are mapped to same node or overlap if cur_alignment == nxt_alignment: return 'MERGE'",
"None return multitask_words def print_corpus_info(amrs): # print some info print(f'{len(amrs)} sentences') node_label_count =",
"action = 'COPY_SENSE01' else: action = f'PRED({new_node})' else: action = f'PRED({new_node})' return action",
"act_id, act_node_id in enumerate(machine.actions_to_nodes): for act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is None:",
"# convert to single node aligned to each of these two tokens if",
"get top words multitask_words = get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root ) # store in",
"else: action = f'PRED({new_node})' return action else: return None def try_dependent(self): \"\"\" Check",
"sent, keep has map if akey not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr #",
"t in gold_amr.edges: if s == gold_nodeid and r in [':polarity', ':mode']: if",
"# NOTE this might affect the next DEPEDENT check, but is fine if",
"gold AMR graph nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1, list):",
"is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not in entities_with_preds and not",
"pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics def main(): # Argument handling args",
"a token, indexed by # token node_by_token[token_str].update([node]) return node_by_token def is_most_common(node_counts, node, rank=0):",
"1 if len(tok_alignment) == 0: return 'REDUCE' else: return None def try_merge(self): \"\"\"",
"# get top words multitask_words = get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root ) # store",
"if named entity case: (entity_category, ':name', 'name') entity_edges = [] name_node_ids = []",
"arc_pos = act_id return f'{arc_name}({arc_pos},{arc_label})' return None def get_arc(self, node_id1, node_id2): \"\"\" Get",
"# TODO: Use here XML propbank reader instead of txt reader propbank_args =",
"None if machine.tok_cursor < machine.tokseq_len - 1: cur = machine.tok_cursor nxt = machine.tok_cursor",
"by one for sent_idx, gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO: See if we",
"word types/tokens') class AMROracleBuilder: \"\"\"Build AMR oracle for one sentence.\"\"\" def __init__(self, gold_amr,",
"nodes in the aligned subgraph altogether. \"\"\" machine = self.machine gold_amr = self.gold_amr",
"machine.tok_cursor + 1 cur_alignment = gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt + 1)",
"in tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO: See if we can remove this part gold_amr",
"= Counter() for tokens, actions in zip(sentence_tokens, oracle_actions): # filter actions to remove",
"token 2 node2 = gold_amr.findSubGraph(nodes2).root else: node2 = nodes2[0] # find edges for",
"ENTITY now, as the mapping from ENTITY node is only to the source",
"# copy lemma action parser.add_argument( \"--addnode-count-cutoff\", help=\"forbid all addnode actions appearing less times",
"= amr.toJAMRString() # store different amr labels for same sent, keep has map",
"edges for s, r, t in gold_amr.edges: if node1 == s and node2",
"# parser.add_argument( \"--multitask-max-words\", type=int, help=\"number of woprds to use for multi-task\" ) #",
"to the current node from the previous node at location pos CLOSE :",
"{args.in_amr}') corpus = read_amr(args.in_amr, unicode_fixes=True) gold_amrs = corpus.amrs # sanity check AMRS print_corpus_info(gold_amrs)",
"perc = num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % inconsistent labelings from",
"sentence repeated sentence_count.update([skey]) # hash of AMR labeling akey = amr.toJAMRString() # store",
"if not action: action = self.try_arcs() #if not action: # action = self.try_named_entities()",
"1): alignments[al_node].append( train_amr.tokens[i] ) for node_id, aligned_tokens in alignments.items(): # join multiple words",
"out) 2) the aligned node has not been predicted yet \"\"\" machine =",
"this is accessed by replacing '-' to '_' help=\"statistics about alignments\", type=str )",
"oracle\", type=str ) parser.add_argument( \"--out-sentences\", help=\"tokenized sentences from --in-amr\", type=str ) parser.add_argument( \"--out-actions\",",
"the previous node at location pos RA(pos,label) : form a left arc to",
"LA(pos,label) : form a left arc from the current node to the previous",
"% string num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence =",
"at the end of the sentence for the first unaligned node # whose",
"whose label is in `included_unaligned` to align to # repeat `add_unaligned` times if",
"new_node = gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node: action",
"labels for same sent, keep has map if akey not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey]",
"1: gold_nodeid = gold_nodeids[0] else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for s, r, t in",
"based on the current AMR state machine status and the gold AMR.\"\"\" #",
"token return None if machine.tok_cursor < machine.tokseq_len - 1: cur = machine.tok_cursor nxt",
"== 2: edges = [ (s, r, t) for s, r, t in",
"cur_alignment = gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt + 1) if not cur_alignment",
"in the data reading process # TODO and fix that and remove this",
"':name' and gold_amr.nodes[t] == 'name': entity_edges.append((s, r, t)) name_node_ids.append(t) if not name_node_ids: return",
"sents' ) print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) == len(oracle_actions)",
"gold_amr.alignmentsToken2Node(tok_id + 1) # below is coupled with the PRED checks? and also",
"return None is_dependent = False for s, r, t in edges: if r",
"= gold_amr.findSubGraph(gold_nodeids).root for s, r, t in gold_amr.edges: if s == gold_nodeid and",
"if not action: action = self.try_pred() if not action: if len(self.machine.actions) and self.machine.actions[-1]",
"be more than one edges? # currently we only return the first one.",
"the state machine self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action self.multitask_words",
"DEPENDENT action. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor node_id",
"None new_id = None for s, r, t in edges: if s not",
"left arc from the current node to the previous node at location pos",
"token at last position is added as a node from the beginning, so",
"reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is None: continue # for multiple nodes out of one",
"has been predicted already 2) Only for :polarity and :mode, if an edge",
"transition-based combined with pointers for long distance arcs. Actions are SHIFT : move",
"(max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, 'repeated sents', max( count for",
"to single node aligned to each of these two tokens if len(nodes1) >",
"parser.add_argument( \"--out-actions\", help=\"actions given by oracle\", type=str ) parser.add_argument( \"--out-action-stats\", help=\"statistics about actions\",",
"transition_amr_parser.io import read_propbank, read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine, get_spacy_lemmatizer ) \"\"\"",
"== 0, \"Oracle can\\'t blacklist actions\" action = valid_actions[0] # update the machine",
"next action # NOTE the order here is important, which is based on",
"check why this happens in the data reading process # TODO and fix",
"the next action is ENTITY. TryENTITY before tryPRED. If 1) aligned to more",
"corpus = read_amr(args.in_amr, unicode_fixes=True) gold_amrs = corpus.amrs # sanity check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs)",
"one by one from the current surface token (segments). E.g. a) for one",
"hash of sentence skey = \" \".join(amr.tokens) # count number of time sentence",
"if node_id is None: # NOTE if node_id could be 0, 'if not",
"if not name_node_ids: return None for s, r, t in entity_edges: if t",
"a special token at the end of the sentence for the first unaligned",
"repeated sents (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, max( count for",
"train_amr.tokens[i] ) for node_id, aligned_tokens in alignments.items(): # join multiple words into one",
"arcs] LA(pos,':name') ENTITY('name') PRED('city') [other arcs] LA(pos,':name') \"\"\" machine = self.machine gold_amr =",
"the same node alignment. \"\"\" machine = self.machine gold_amr = self.gold_amr if machine.current_node_id",
"file with open(in_multitask_words) as fid: multitask_words = [line.strip() for line in fid.readlines()] else:",
"in gold_amr.edges: if s == gold_nodeid and r in [':polarity', ':mode']: if (node_id,",
"new node by copying lemma and add '01' DEPENDENT(edge,node) : Add a node",
"r, t) for s, r, t in gold_amr.edges if s in align and",
"unaligned node # whose label is in `included_unaligned` to align to # repeat",
"num_inconsistent, num_sentences, perc, 'inconsistent labelings from repeated sents' ) print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions):",
"in edges: if r == ':name' and gold_amr.nodes[t] == 'name': return None if",
"treated same as <eos> in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules for idx,",
"get root of subgraph aligned to token 2 node2 = gold_amr.findSubGraph(nodes2).root else: node2",
"'.'] # TODO if not dealt with, this causes a problem when the",
"rank + 1 len(node_counts) > rank + 1 and node_counts.most_common(rank + 1)[-1][0] ==",
"\"<ROOT>\" token at last position is added as a node from the beginning,",
"there be more than one edges? # currently we only return the first",
"alignments: sometimes the alignments are outside of the sentence boundary # TODO check",
"to avoid subgraph ENTITY after named entities if tok_id in machine.entity_tokenids: return None",
"entity, or a subgraph PRED(label) : form a new node with label COPY_LEMMA",
"else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for s, r, t in gold_amr.edges: if s ==",
"node-arc actions, arc subsequence comes highest, then named entity subsequence, etc. # debug",
"action = f'PRED({new_node})' return action else: return None def try_dependent(self): \"\"\" Check if",
"for now assert len(valid_actions) == 1, \"Oracle must be deterministic\" assert len(invalid_actions) ==",
"AMR notation and actions given by oracle\", type=str ) parser.add_argument( \"--out-sentences\", help=\"tokenized sentences",
"as fid: for word in multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words: assert not multitask_max_words assert",
"some info print(f'{len(amrs)} sentences') node_label_count = Counter([ n for amr in amrs for",
"in amrs for t in amr.edges]) edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count",
"the possible edges continue if t not in gold_nodeids and (t in gold_amr.alignments",
"the arcs that involve the current token aligned node. If 1) currently is",
"be applied more # transparently print(f'Reading {args.in_amr}') corpus = read_amr(args.in_amr, unicode_fixes=True) gold_amrs =",
"subgraph aligned to token 2 node2 = gold_amr.findSubGraph(nodes2).root else: node2 = nodes2[0] #",
"return 'MERGE' return None else: return None def try_named_entities(self): \"\"\" Get the named",
"token aligned node. If 1) currently is on a node that was just",
"this behavior, we need to be careful about the root node id which",
"token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics def main(): # Argument handling args =",
"when the sentence is # ['Among', 'common', 'birds', ',', 'a', 'rather', 'special', 'one',",
"= arc # avoid repetitive edges if arc_name == 'LA': if (node_id, arc_label,",
"# parser.add_argument( \"--verbose\", action='store_true', help=\"verbose processing\" ) # parser.add_argument( \"--multitask-max-words\", type=int, help=\"number of",
"def print_corpus_info(amrs): # print some info print(f'{len(amrs)} sentences') node_label_count = Counter([ n for",
"break if t not in self.built_gold_nodeids: new_id = t break if new_id !=",
"do multiple PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root # TODO for multiple PREDs, we need",
"automatically added at the beginning # NOTE to change this behavior, we need",
"{:2.4f} % inconsistent labelings from repeated sents'.format( num_inconsistent, num_sentences, perc ) print(yellow_font(alert_str)) def",
"= 0 for skey, sent_count in sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) >",
"== new_node: action = 'COPY_SENSE01' else: action = f'PRED({new_node})' else: action = f'PRED({new_node})'",
"results as the rank and node in that rank matches len(node_counts) == rank",
"# Argument handling args = argument_parser() global entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\") # Load",
"appearing less times than count\", type=int ) parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma separated",
"= gold_amr.findSubGraph(tok_alignment).edges if not edges: return None is_dependent = False for s, r,",
"edges = [ (s, r, t) for s, r, t in gold_amr.edges if",
"not been built with this node \"\"\" machine = self.machine node_id = machine.current_node_id",
"gold_amr = self.gold_amr tok_id = machine.tok_cursor # to avoid subgraph ENTITY after named",
"sentence in tokenized_corpus: word_count.update([x for x in sentence]) # Restrict to top-k words",
"help=\"corresponding AMR\", type=str ) # parser.add_argument( \"--verbose\", action='store_true', help=\"verbose processing\" ) # parser.add_argument(",
"return None def run_oracle(gold_amrs, copy_lemma_action, multitask_words): # Initialize lemmatizer as this is slow",
"get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root ) # store in file with open(out_multitask_words, 'w') as",
"def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string entities_with_preds = [] def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None,",
"range(len(train_amr.tokens)): for al_node in train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append( train_amr.tokens[i] ) for node_id, aligned_tokens",
"TODO deprecate `multitask_words` or change for a better name such as `shift_label_words` #",
"in multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words: assert not multitask_max_words assert not out_multitask_words # store",
"= machine.get_current_token(lemma=True) if lemma == new_node: action = 'COPY_LEMMA' elif f'{lemma}-01' == new_node:",
"= machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE the index + 1",
"s in align and t in align ] if not edges: remove =",
"--in-amr\", type=str ) parser.add_argument( \"--out-actions\", help=\"actions given by oracle\", type=str ) parser.add_argument( \"--out-action-stats\",",
"= nodes1[0] if len(nodes2) > 1: # get root of subgraph aligned to",
"for DEPENDENT missing # if self.tokens == ['The', 'cyber', 'attacks', 'were', 'unprecedented', '.',",
"if there is any edge with the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if",
"happens in the data reading process # TODO and fix that and remove",
"in amrs for w in amr.tokens]) word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class",
"the target nodes in the subgraph # gold_nodeids = self.nodeid_to_gold_nodeid[node_id] # gold_nodeids =",
"not been predicted yet \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id =",
"value arc_pos = act_id return f'{arc_name}({arc_pos},{arc_label})' return None def get_arc(self, node_id1, node_id2): \"\"\"",
"1 node1 = gold_amr.findSubGraph(nodes1).root else: node1 = nodes1[0] if len(nodes2) > 1: #",
"if alignment empty (or singleton) if len(tok_alignment) <= 1: return None # check",
"'{:d}/{:d} {:2.4f} % {:s}'.format( num_inconsistent, num_sentences, perc, 'inconsistent labelings from repeated sents' )",
"new node with label COPY_LEMMA : form a new node by copying lemma",
"# If both tokens are mapped to same node or overlap if cur_alignment",
"self.machine.tokseq_len - 1 : action = 'REDUCE' else: action = 'SHIFT' if action",
"# build the oracle actions sequence actions = oracle_builder.build_oracle_actions() # store data statistics['sentence_tokens'].append(oracle_builder.tokens)",
"1) if not cur_alignment or not nxt_alignment: return None # If both tokens",
"in `included_unaligned` to align to # repeat `add_unaligned` times if add_unaligned: for i",
"for sentence in tokenized_corpus: word_count.update([x for x in sentence]) # Restrict to top-k",
"take the source nodes in the aligned subgraph altogether. \"\"\" machine = self.machine",
"arcs] LA(pos,':name') PRED('city') [other arcs] LA(pos,':name') c) for two entities with two surface",
"t in entity_edges: if t not in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)'",
"perc = num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % {:s} (max {:d}",
"if not edges: return None # check if named entity case: (entity_category, ':name',",
"f'PRED({new_node})' return action return None def try_entity(self): \"\"\" Check if the next action",
"= AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words) # build the oracle actions sequence actions =",
"for :polarity and :mode, if an edge and node is aligned to this",
"part gold_amr = gold_amr.copy() gold_amr = preprocess_amr(gold_amr) # Initialize oracle builder oracle_builder =",
"x[1]) )[-max_symbols:]) if add_root: # Add root regardless allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words def",
"in the # aligned subgraph, whereas for the DEPENDENT we are checking the",
"given by oracle\", type=str ) parser.add_argument( \"--out-action-stats\", help=\"statistics about actions\", type=str ) parser.add_argument(",
"more # transparently print(f'Reading {args.in_amr}') corpus = read_amr(args.in_amr, unicode_fixes=True) gold_amrs = corpus.amrs #",
"rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node ) or ( #",
"gold_amr = gold_amr.copy() gold_amr = preprocess_amr(gold_amr) # Initialize oracle builder oracle_builder = AMROracleBuilder(gold_amr,",
"[other arcs] LA(pos,':name') c) for two entities with two surface tokens ENTITY('name') PRED('city')",
"reading process # TODO and fix that and remove this cleaning process #",
"pointer for action in actions: if pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})'",
"self.machine gold_amr = self.gold_amr if machine.current_node_id is not None: # not on the",
"self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})' return None def try_entities_with_pred(self): \"\"\" allow pred inside",
"if t not in gold_nodeids and (t in gold_amr.alignments and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t)",
"as the root node is automatically added at the beginning # NOTE to",
"has not been built at current step return None #for act_id, act_node_id in",
"gold_amr=self.gold_amr) return self.actions def try_reduce(self): \"\"\" Check if the next action is REDUCE.",
"been constructed, for multiple PREDs if gold_nodeid not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid)",
"the next action # NOTE the order here is important, which is based",
"r, t in gold_amr.edges if s in align and t in align ]",
"allowed_words = dict(list(sorted( word_count.items(), key=lambda x: x[1]) )[-max_symbols:]) if add_root: # Add root",
"in file with open(in_multitask_words) as fid: multitask_words = [line.strip() for line in fid.readlines()]",
"# setting a token id to -1 will break the code gold_amr.alignments[root_id] =",
"to this token in the gold amr but does not exist in the",
"SHIFT CLOSE] machine = self.machine while not machine.is_closed: valid_actions, invalid_actions = self.get_valid_actions() #",
"sub-sequences one by one from the current surface token (segments). E.g. a) for",
"len(gold_amr.tokens)] # TODO: describe this # append a special token at the end",
"is an edge `node_id2` <-- `node_id2` Thus the order of inputs matter. (could",
"= gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE the index + 1 if len(tok_alignment) ==",
"action return None def try_entity(self): \"\"\" Check if the next action is ENTITY.",
"process # an example is in training data, when the sentence is #",
"tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment empty",
"(not -1) for nid, tids in gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid for tid in",
"entities with two surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') ENTITY('name') PRED('city') [other",
"[... LA(pos,'root') SHIFT CLOSE] machine = self.machine while not machine.is_closed: valid_actions, invalid_actions =",
"oracle actions sequence actions = oracle_builder.build_oracle_actions() # store data statistics['sentence_tokens'].append(oracle_builder.tokens) # do not",
"order here is important, which is based on priority # e.g. within node-arc",
"num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % repeated sents (max {:d} times)'.format(",
"[len(gold_amr.tokens)] break # add root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root))",
"tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') PRED('city') [other arcs] LA(pos,':name') c) for two",
"# to avoid subgraph ENTITY after named entities if tok_id in machine.entity_tokenids: return",
"is_dependent): return None gold_nodeids = [n for n in tok_alignment if any(s ==",
"machine stats for this sentence if args.out_rule_stats: with open(args.out_rule_stats, 'w') as fid: fid.write(json.dumps(stats['rules']))",
"edges: if s not in self.built_gold_nodeids: new_id = s break if t not",
"s == gold_nodeid and r in [':polarity', ':mode']: if (node_id, r) in [(e[0],",
"If 1) there is nothing aligned to a token. \"\"\" machine = self.machine",
"if the node has been constructed, for multiple PREDs if gold_nodeid not in",
"entities_with_preds = [] def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1): # clean alignments for i,",
"multi-task\" ) parser.add_argument( \"--in-multitask-words\", type=str, help=\"where to read top-k words for multi-task\" )",
"if (act_node_id, arc_label, node_id) in machine.amr.edges: continue # pointer value arc_pos = act_id",
"+ 1)[-1][0] == node ) or ( # more results than the rank,",
"gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ): remove = 0 gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo",
"node with label COPY_LEMMA : form a new node by copying lemma COPY_SENSE01",
"next action is ENTITY. TryENTITY before tryPRED. If 1) aligned to more than",
"NOTE this doesn't work for ENTITY now, as the mapping from ENTITY node",
"format\", type=str, required=True ) parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument data\", type=str, ) parser.add_argument( \"--out-oracle\",",
"[':polarity', ':mode']: if (node_id, r) in [(e[0], e[1]) for e in machine.amr.edges]: #",
"gold_amrs = corpus.amrs # sanity check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load propbank if",
"# action = self.try_named_entities() if not action: action = self.try_entities_with_pred() if not action:",
"> 1: token_str = \" \".join(aligned_tokens) else: token_str = aligned_tokens[0] node = train_amr.nodes[node_id]",
"always [... SHIFT CLOSE] or [... LA(pos,'root') SHIFT CLOSE] machine = self.machine while",
"# join multiple words into one single expression if len(aligned_tokens) > 1: token_str",
"need to be careful about the root node id which should be -1",
"for skey, sent_count in sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) > 1: pass",
"input parameters parser.add_argument( \"--out-amr\", help=\"corresponding AMR\", type=str ) # parser.add_argument( \"--verbose\", action='store_true', help=\"verbose",
"actions: if pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass",
"in that rank matches, and rank # results is more probable than rank",
"print('Most frequent actions:') print(action_count.most_common(10)) if singletons: base_action_count = [x.split('(')[0] for x in singletons]",
"Save statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t' ) #",
"and :mode, if an edge and node is aligned to this token in",
"parser.add_argument( \"--in-amr\", help=\"AMR notation in LDC format\", type=str, required=True ) parser.add_argument( \"--in-propbank-args\", help=\"Propbank",
"in entity_edges: if t not in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)' if",
"not do this; we have made all the token ids natural positive index",
"is_dependent: return None new_id = None for s, r, t in edges: if",
"status and the gold AMR.\"\"\" # find the next action # NOTE the",
"statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t' ) # State",
"= parser.parse_args() return args def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string entities_with_preds = []",
"remove = 0 gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo = {} # clean invalid alignments:",
"= [ (s, r, t) for s, r, t in gold_amr.edges if s",
"f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons = [k for k, c in action_count.items()",
"'common', 'birds', ',', 'a', 'rather', 'special', 'one', 'is', # 'the', 'black', '-', 'faced',",
"if pointer_arc_re.match(action): items = pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons",
"count\", type=int ) parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\", help=\"comma separated list of entity types",
"machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor node_id = machine.current_node_id if",
"# Single input parameters parser.add_argument( \"--in-amr\", help=\"AMR notation in LDC format\", type=str, required=True",
"DEPENDENT we are checking the target nodes in the subgraph # gold_nodeids =",
"about actions\", type=str ) parser.add_argument( \"--out-rule-stats\", # TODO this is accessed by replacing",
"node at location pos CLOSE : complete AMR, run post-processing \"\"\" use_addnode_rules =",
"'is', # 'the', 'black', '-', 'faced', 'spoonbill', '.'] # TODO if not dealt",
"machine = self.machine node_id = machine.current_node_id if node_id is None: # NOTE if",
"or ( # more results than the rank, node in that rank matches,",
"for multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab separation in actions and sentences",
"in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not in",
"in the gold AMR graph nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2] if not",
"first one. \"\"\" gold_amr = self.gold_amr # get the node ids in the",
"gold_amr = self.gold_amr tok_id = machine.tok_cursor if tok_id == machine.tokseq_len - 1: #",
"return None def try_merge(self): \"\"\" Check if the next action is MERGE. If",
"There is more than one labeling for this sentence # amrs = list(amr_by_amrkey_by_sentence[skey].values())",
"# There is more than one labeling for this sentence # amrs =",
"items = line.strip().split('\\t') if len(items) > 2: multitask_words.append(items[1]) return multitask_words def label_shift(state_machine, multitask_words):",
"[-1] # NOTE gold amr root id is fixed at -1 self.built_gold_nodeids =",
"= Counter() for sentence in tokenized_corpus: word_count.update([x for x in sentence]) # Restrict",
"= machine.current_node_id if node_id is None: # NOTE if node_id could be 0,",
"= dict(list(sorted( word_count.items(), key=lambda x: x[1]) )[-max_symbols:]) if add_root: # Add root regardless",
"alignments between nodes and surface words\"\"\" node_by_token = defaultdict(lambda: Counter()) for train_amr in",
"index + 1 if len(tok_alignment) == 0: return 'REDUCE' else: return None def",
"same node alignment. \"\"\" machine = self.machine gold_amr = self.gold_amr if machine.current_node_id is",
"def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words, add_root=False): # Load/Save words for multi-task if multitask_max_words:",
"action = self.try_entity() if not action: action = self.try_pred() if not action: if",
"[]).append(new_id) new_node = gold_amr.nodes[new_id] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node:",
"tqdm from transition_amr_parser.io import read_propbank, read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine, get_spacy_lemmatizer",
"'{:d}/{:d} {:2.1f} % {:s} (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, 'repeated",
"in enumerate(machine.actions_to_nodes): for act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is None: continue #",
"# store in file with open(out_multitask_words, 'w') as fid: for word in multitask_words.keys():",
"in postprocessing to find/add root. return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) #",
"nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None is_dependent = False for",
"been predicted yet \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor",
"machine.amr.edges]: # to prevent same DEPENDENT added twice, as each time we scan",
"stats['oracle_actions']) # Save statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t'",
"or not nxt_alignment: return None # If both tokens are mapped to same",
"by copying lemma and add '01' DEPENDENT(edge,node) : Add a node which is",
"case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id + 1) # below is coupled with the PRED",
"convert to single node aligned to each of these two tokens if len(nodes1)",
"= f'PRED({new_node})' else: action = f'PRED({new_node})' return action else: return None def try_dependent(self):",
"and actions given by oracle\", type=str ) parser.add_argument( \"--out-sentences\", help=\"tokenized sentences from --in-amr\",",
"in amr.tokens]) word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class AMROracleBuilder: \"\"\"Build AMR oracle",
"valid_actions = [action] invalid_actions = [] return valid_actions, invalid_actions def build_oracle_actions(self): \"\"\"Build the",
"help=\"actions given by oracle\", type=str ) parser.add_argument( \"--out-action-stats\", help=\"statistics about actions\", type=str )",
"for nid, tids in gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid for tid in tids if",
"positive index # setting a token id to -1 will break the code",
"aligned to token 2 node2 = gold_amr.findSubGraph(nodes2).root else: node2 = nodes2[0] # find",
"a subgraph PRED(label) : form a new node with label COPY_LEMMA : form",
"entire corpus stats = run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) # print stats about actions sanity_check_actions(stats['sentence_tokens'],",
"max( count for counter in amr_counts_by_sentence.values() for count in counter.values() ) ) print(yellow_font(alert_str))",
"describe this # append a special token at the end of the sentence",
"in self.built_gold_nodeids: new_id = t break if new_id != None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id)",
"= multitask_words # TODO deprecate `multitask_words` or change for a better name such",
"return f'PRED({gold_amr.nodes[s]})' return None def try_entities_with_pred(self): \"\"\" allow pred inside entities that frequently",
"if tok_id in machine.entity_tokenids: return None # NOTE currently do not allow multiple",
"node by copying lemma and add '01' DEPENDENT(edge,node) : Add a node which",
"to -1 will break the code gold_amr.alignments[root_id] = [len(gold_amr.tokens)] # NOTE shifted by",
"word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class AMROracleBuilder: \"\"\"Build AMR oracle for one",
"named entity case: (entity_category, ':name', 'name') # no need, since named entity check",
"separator='\\t' ) write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t' ) # State machine stats for this",
"Initialize oracle builder oracle_builder = AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words) # build the oracle",
"the machine machine.apply_action(action) # close machine # below are equivalent # machine.apply_action('CLOSE', training=True,",
"is empty # no need since the REDUCE check happens first if len(tok_alignment)",
"current token sentence, based on the gold AMR and the alignment. \"\"\" #",
"on the gold AMR and the alignment. \"\"\" # Loop over potential actions",
"\"\"\" use_addnode_rules = True def argument_parser(): parser = argparse.ArgumentParser(description='AMR parser oracle') # Single",
"\"\"\" Check if the next action is MERGE. If 1) the current and",
"perc ) print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words = [] with open(multitask_list) as fid: for",
"# get root of subgraph aligned to token 2 node2 = gold_amr.findSubGraph(nodes2).root else:",
"actions:') print(Counter([k.split('(')[0] for k in action_count.keys()])) print('Most frequent actions:') print(action_count.most_common(10)) if singletons: base_action_count",
"with `node_id2`. RA if there is an edge `node_id1` --> `node_id2` LA if",
"list(set(gold_nodeids)) # just in case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id + 1) # below is",
"arc_label, node_id) in machine.amr.edges: continue # pointer value arc_pos = act_id return f'{arc_name}({arc_pos},{arc_label})'",
"and node2 == s: return ('LA', r) return None def run_oracle(gold_amrs, copy_lemma_action, multitask_words):",
"= { 'sentence_tokens': [], 'oracle_actions': [], 'oracle_amr': [], 'rules': { # Will store",
"return None def try_arcs(self): \"\"\" Get the arcs that involve the current token",
"appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count) num_labelings = 0 for skey, sent_count in sentence_count.items():",
"run_oracle(gold_amrs, copy_lemma_action, multitask_words): # Initialize lemmatizer as this is slow lemmatizer = get_spacy_lemmatizer()",
"happens first if len(tok_alignment) == 1: gold_nodeid = tok_alignment[0] else: # TODO check",
"self.multitask_words = multitask_words # TODO deprecate `multitask_words` or change for a better name",
"is None: # NOTE if node_id could be 0, 'if not node_id' would",
"is an edge `node_id1` --> `node_id2` LA if there is an edge `node_id2`",
": move cursor to next position in the token sequence REDUCE : delete",
"# check if named entity case: (entity_category, ':name', 'name') entity_edges = [] name_node_ids",
"in enumerate(actions): if pred_re.match(action): node_name = pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics",
"nodes out of one token --> need to use node id to check",
"global entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\") # Load AMR (replace some unicode characters) #",
"= oracle_builder.build_oracle_actions() # store data statistics['sentence_tokens'].append(oracle_builder.tokens) # do not write CLOSE action at",
"spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action self.multitask_words = multitask_words # TODO deprecate `multitask_words`",
"> rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node and node_counts.most_common(rank +",
"'a', 'rather', 'special', 'one', 'is', # 'the', 'black', '-', 'faced', 'spoonbill', '.'] #",
"that was just constructed 2) there are edges that have not been built",
"self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if",
"# that is also massively used in postprocessing to find/add root. return None",
"the alignment. \"\"\" # Loop over potential actions # NOTE \"<ROOT>\" token at",
"and gold_amr.nodes[t] == 'name': entity_edges.append((s, r, t)) name_node_ids.append(t) if not name_node_ids: return None",
"self.get_valid_actions() # for now assert len(valid_actions) == 1, \"Oracle must be deterministic\" assert",
"the next DEPEDENT check, but is fine if we always use subgraph root",
"Single input parameters parser.add_argument( \"--in-amr\", help=\"AMR notation in LDC format\", type=str, required=True )",
"PRED(label) : form a new node with label COPY_LEMMA : form a new",
"rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node and node_counts.most_common(rank + 1)[-1][1]",
"subsequence, etc. # debug # on dev set, sentence id 459 (starting from",
"if s == gold_nodeid and r in [':polarity', ':mode']: if (node_id, r) in",
"not is_dependent: return None new_id = None for s, r, t in edges:",
"# not on the first time on a new token return None if",
"self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action def try_pred(self): \"\"\" Check if the next action is",
"might affect the next DEPEDENT check, but is fine if we always use",
"valid_actions[0] # update the machine machine.apply_action(action) # close machine # below are equivalent",
"for s, r, t in gold_amr.edges: if s == gold_nodeid and r in",
"copy lemma action parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use copy action from Spacy lemmas\" )",
"num_unique_sents perc = num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % inconsistent labelings",
"act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is None: continue # for multiple nodes out",
"= train_amr.nodes[node_id] # count number of time a node is aligned to a",
"removing whitespaces\" ) # copy lemma action parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use copy action",
"with the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None is_dependent",
"\"--in-propbank-args\", help=\"Propbank argument data\", type=str, ) parser.add_argument( \"--out-oracle\", help=\"tokens, AMR notation and actions",
"index # setting a token id to -1 will break the code gold_amr.alignments[root_id]",
"important, which is based on priority # e.g. within node-arc actions, arc subsequence",
"None def try_named_entities(self): \"\"\" Get the named entity sub-sequences one by one from",
"parser.add_argument( \"--in-multitask-words\", type=str, help=\"where to read top-k words for multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\",",
"pointer position 'possible_predicates': defaultdict(lambda: Counter()) } } pred_re = re.compile(r'^PRED\\((.*)\\)$') # Process AMRs",
"re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) == len(oracle_actions) source_lengths = [] target_lengths = [] action_count =",
"in enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i + 1) if len(align) == 2: edges =",
"token ids positive natural index # check if the alignment is empty #",
"root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root)) # gold_amr.alignments[root_id] = [-1]",
"more than 1 nodes, and 2) there are edges in the aligned subgraph,",
"'name') entity_edges = [] name_node_ids = [] for s, r, t in edges:",
"for amr in amrs for n in amr.nodes.values() ]) node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens}",
"= True root = gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not in entities_with_preds and not is_dependent:",
"= 'COPY_LEMMA' elif f'{lemma}-01' == new_node: action = 'COPY_SENSE01' else: action = f'PRED({new_node})'",
"num_sentences, perc ) print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words = [] with open(multitask_list) as fid:",
"ENTITY. TryENTITY before tryPRED. If 1) aligned to more than 1 nodes, and",
"the # aligned subgraph, whereas for the DEPENDENT we are checking the target",
"Check if the next action is ENTITY. TryENTITY before tryPRED. If 1) aligned",
"get_arc(self, node_id1, node_id2): \"\"\" Get the arcs between node with `node_id1` and node",
"[] @property def tokens(self): return self.gold_amr.tokens @property def time_step(self): return self.machine.time_step @property def",
"the gold AMR.\"\"\" # find the next action # NOTE the order here",
"gold amr root id is fixed at -1 self.built_gold_nodeids = [] @property def",
"word_count['ROOT']}) return allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words, add_root=False): # Load/Save words for",
"amr.toJAMRString() # store different amr labels for same sent, keep has map if",
"DEPENDENT added twice, as each time we scan all the possible edges continue",
"If 1) currently is on a node that was just constructed 2) there",
"addnode actions appearing less times than count\", type=int ) parser.add_argument( \"--in-pred-entities\", type=str, default=\"person,thing\",",
"root_id=-1): # clean alignments for i, tok in enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i +",
"multi-task if multitask_max_words: assert multitask_max_words assert out_multitask_words # get top words multitask_words =",
"currently we only return the first one. \"\"\" gold_amr = self.gold_amr # get",
"multitask_words = None return multitask_words def print_corpus_info(amrs): # print some info print(f'{len(amrs)} sentences')",
"1) there is nothing aligned to a token. \"\"\" machine = self.machine gold_amr",
"TODO if not dealt with, this causes a problem when the root aligned",
"of the sentence for the first unaligned node # whose label is in",
"# clean alignments for i, tok in enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i + 1)",
"actions # NOTE \"<ROOT>\" token at last position is added as a node",
") print(yellow_font(alert_str)) def read_multitask_words(multitask_list): multitask_words = [] with open(multitask_list) as fid: for line",
"in the predicted amr, the oracle adds it using the DEPENDENT action. \"\"\"",
"= s break if t not in self.built_gold_nodeids: new_id = t break if",
"',', 'a', 'rather', 'special', 'one', 'is', # 'the', 'black', '-', 'faced', 'spoonbill', '.']",
"'repeated sents', max( count for counter in amr_counts_by_sentence.values() for count in counter.values() )",
"return the first one. \"\"\" gold_amr = self.gold_amr # get the node ids",
"r, t)) name_node_ids.append(t) if not name_node_ids: return None for s, r, t in",
"way. The parsing algorithm is transition-based combined with pointers for long distance arcs.",
"not dealt with, this causes a problem when the root aligned token id",
"amr but does not exist in the predicted amr, the oracle adds it",
"def is_most_common(node_counts, node, rank=0): return ( ( # as many results as the",
"= self.get_valid_actions() # for now assert len(valid_actions) == 1, \"Oracle must be deterministic\"",
"current AMR state machine status and the gold AMR.\"\"\" # find the next",
"are equivalent # machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions def try_reduce(self): \"\"\"",
"type=int, help=\"number of woprds to use for multi-task\" ) # Labeled shift args",
"if we always use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge = r[1:] if r.startswith(':')",
"args def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string entities_with_preds = [] def preprocess_amr(gold_amr, add_unaligned=None,",
"# NOTE shifted by 1 for AMR alignment return gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get",
"= re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) == len(oracle_actions) source_lengths = [] target_lengths = [] action_count",
"'birds', ',', 'a', 'rather', 'special', 'one', 'is', # 'the', 'black', '-', 'faced', 'spoonbill',",
"self.nodeid_to_gold_nodeid = {} # key: node id in the state machine, value: list",
"r new_node = gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})' return action return None def try_arcs(self):",
"in included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)] break # add root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] =",
"'<ROOT>']: # if self.time_step >= 8: # breakpoint() action = self.try_reduce() if not",
"inform user if num_sentences > num_unique_sents: num_repeated = num_sentences - num_unique_sents perc =",
": merge two tokens (for MWEs) ENTITY(type) : form a named entity, or",
"edges: if r == ':name' and gold_amr.nodes[t] == 'name': is_named = True if",
"entities_with_preds = args.in_pred_entities.split(\",\") # Load AMR (replace some unicode characters) # TODO: unicode",
"(t in gold_amr.alignments and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) # NOTE this might affect the",
"the DEPENDENT action. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor",
"gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt + 1) if not cur_alignment or not",
"inputs matter. (could also change to follow strict orders between these 2 ids)",
"subsequence comes highest, then named entity subsequence, etc. # debug # on dev",
"next action is MERGE. If 1) the current and the next token have",
"of entity types that can have pred\" ) args = parser.parse_args() return args",
"whereas for the DEPENDENT we are checking the target nodes in the subgraph",
"follow strict orders between these 2 ids) # TODO could there be more",
"t and node2 == s: return ('LA', r) return None def run_oracle(gold_amrs, copy_lemma_action,",
"else: return None def try_named_entities(self): \"\"\" Get the named entity sub-sequences one by",
"arc is None: continue arc_name, arc_label = arc # avoid repetitive edges if",
"\"\"\" # Loop over potential actions # NOTE \"<ROOT>\" token at last position",
"+ 1)[-1][1] > node_counts.most_common(rank + 2)[-1][1] ) ) def sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs)",
"tokenized_corpus, add_root=add_root ) # store in file with open(out_multitask_words, 'w') as fid: for",
"with this node \"\"\" machine = self.machine node_id = machine.current_node_id if node_id is",
"node, or multiple nodes? (figure out) 2) the aligned node has not been",
"machine.tok_cursor if tok_id == machine.tokseq_len - 1: # never do PRED(<ROOT>) currently, as",
"loop here # check if the node has been constructed, for multiple PREDs",
"read_propbank, read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine, get_spacy_lemmatizer ) \"\"\" This algorithm",
"the index + 1 if len(tok_alignment) == 0: return 'REDUCE' else: return None",
"num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % inconsistent labelings from repeated sents'.format(",
"that is also massively used in postprocessing to find/add root. return None tok_alignment",
"doesn't work for ENTITY now, as the mapping from ENTITY node is only",
"each of these two tokens if len(nodes1) > 1: # get root of",
"get the node ids in the gold AMR graph nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2",
"if arc_name == 'RA': if (act_node_id, arc_label, node_id) in machine.amr.edges: continue # pointer",
"return \"\\033[93m%s\\033[0m\" % string num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict)",
"comes highest, then named entity subsequence, etc. # debug # on dev set,",
"subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge = r[1:] if r.startswith(':') else r new_node =",
"n not in gold_amr.alignments or not gold_amr.alignments[n]: if gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n] =",
"argparse.ArgumentParser(description='AMR parser oracle') # Single input parameters parser.add_argument( \"--in-amr\", help=\"AMR notation in LDC",
"== 1] print('Base actions:') print(Counter([k.split('(')[0] for k in action_count.keys()])) print('Most frequent actions:') print(action_count.most_common(10))",
"the aligned node has been predicted already 2) Only for :polarity and :mode,",
"num_unique_sents: num_inconsistent = num_labelings - num_unique_sents perc = num_inconsistent / num_sentences alert_str =",
"to align to # repeat `add_unaligned` times if add_unaligned: for i in range(add_unaligned):",
"`node_id2` <-- `node_id2` Thus the order of inputs matter. (could also change to",
"this doesn't work for ENTITY now, as the mapping from ENTITY node is",
"amr in amrs for n in amr.nodes.values() ]) node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node",
") parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument data\", type=str, ) parser.add_argument( \"--out-oracle\", help=\"tokens, AMR notation",
"':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root if not is_named and ( gold_amr.nodes[root]",
"= run_oracle(gold_amrs, args.copy_lemma_action, multitask_words) # print stats about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save",
"ENTITY here on a single token if machine.current_node_id in machine.entities: return None tok_alignment",
"each time we scan all the possible edges continue if t not in",
"- num_unique_sents perc = num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % inconsistent",
"update the machine machine.apply_action(action) # close machine # below are equivalent # machine.apply_action('CLOSE',",
"= gold_amr.findSubGraph(tok_alignment).edges if not edges: return None # check if named entity case:",
"entities_with_preds and not is_dependent: return None new_id = None for s, r, t",
"= t break if new_id != None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node = gold_amr.nodes[new_id]",
"= argparse.ArgumentParser(description='AMR parser oracle') # Single input parameters parser.add_argument( \"--in-amr\", help=\"AMR notation in",
"sentence_count.update([skey]) # hash of AMR labeling akey = amr.toJAMRString() # store different amr",
"and gold_amr.nodes[t] == 'name': return None if r in [':polarity', ':mode']: is_dependent =",
"tok_id = machine.tok_cursor if tok_id == machine.tokseq_len - 1: # never do PRED(<ROOT>)",
"continue # for multiple nodes out of one token --> need to use",
"next token have the same node alignment. \"\"\" machine = self.machine gold_amr =",
"arc # avoid repetitive edges if arc_name == 'LA': if (node_id, arc_label, act_node_id)",
"multiple PRED? gold_nodeid = gold_amr.findSubGraph(tok_alignment).root # TODO for multiple PREDs, we need to",
"time a node is aligned to a token, indexed by # token node_by_token[token_str].update([node])",
"x in singletons] msg = f'{len(singletons)} singleton actions' print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def",
"current node LA(pos,label) : form a left arc from the current node to",
"CLOSE action is internally managed, and treated same as <eos> in training statistics['oracle_actions'].append(actions[:-1])",
"i.e. person, thing \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor",
"AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action self.multitask_words = multitask_words # TODO deprecate",
"adds it using the DEPENDENT action. \"\"\" machine = self.machine gold_amr = self.gold_amr",
"overlap if cur_alignment == nxt_alignment: return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return None",
"are edges in the aligned subgraph, and then 3) take the source nodes",
"and sentences by removing whitespaces\" ) # copy lemma action parser.add_argument( \"--copy-lemma-action\", action='store_true',",
"# Get alignments alignments = defaultdict(list) for i in range(len(train_amr.tokens)): for al_node in",
"# This will store the oracle stats statistics = { 'sentence_tokens': [], 'oracle_actions':",
"# key: node id in the state machine, value: list of node ids",
"try_dependent(self): \"\"\" Check if the next action is DEPENDENT. If 1) the aligned",
"= False for s, r, t in edges: if r == ':name' and",
"== len(oracle_actions) source_lengths = [] target_lengths = [] action_count = Counter() for tokens,",
"0, 'if not node_id' would cause a bug # the node has not",
"gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of alignments between nodes and surface words\"\"\" node_by_token",
"in gold_amrs: # hash of sentence skey = \" \".join(amr.tokens) # count number",
"sent_idx, gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO: See if we can remove this",
"check happens first is_dependent = False is_named = False for s, r, t",
"# count number of time a node is aligned to a token, indexed",
"oracle stats statistics = { 'sentence_tokens': [], 'oracle_actions': [], 'oracle_amr': [], 'rules': {",
"= Counter([w for amr in amrs for w in amr.tokens]) word_tokens = sum(word_label_count.values())",
"we only return the first one. \"\"\" gold_amr = self.gold_amr # get the",
"action = f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons = [k for k, c",
"arc = self.get_arc(act_node_id, node_id) if arc is None: continue arc_name, arc_label = arc",
"= Counter([t[1] for amr in amrs for t in amr.edges]) edge_tokens = sum(edge_label_count.values())",
"file with open(out_multitask_words, 'w') as fid: for word in multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words:",
"num_sentences, perc, 'inconsistent labelings from repeated sents' ) print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re",
"= corpus.amrs # sanity check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load propbank if provided",
"and add '01' DEPENDENT(edge,node) : Add a node which is a dependent of",
"statistics['sentence_tokens'].append(oracle_builder.tokens) # do not write CLOSE action at the end; # CLOSE action",
"# NOTE \"<ROOT>\" token at last position is added as a node from",
"fix that and remove this cleaning process # an example is in training",
"(entity_category, ':name', 'name') # no need, since named entity check happens first is_dependent",
"person, thing \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor tok_alignment",
"is in training data, when the sentence is # ['Among', 'common', 'birds', ',',",
"hash of AMR labeling akey = amr.toJAMRString() # store different amr labels for",
"that can have pred\" ) args = parser.parse_args() return args def yellow_font(string): return",
"there is nothing aligned to a token. \"\"\" machine = self.machine gold_amr =",
"not name_node_ids: return None for s, r, t in entity_edges: if t not",
"notation in LDC format\", type=str, required=True ) parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument data\", type=str,",
"the current token sentence, based on the gold AMR and the alignment. \"\"\"",
"aligned to more than 1 nodes, and 2) there are edges in the",
"in actions and sentences by removing whitespaces\" ) # copy lemma action parser.add_argument(",
"if there is an edge `node_id2` <-- `node_id2` Thus the order of inputs",
"built at current step return None #for act_id, act_node_id in enumerate(machine.actions_to_nodes): for act_id,",
"Labeled shift args parser.add_argument( \"--out-multitask-words\", type=str, help=\"where to store top-k words for multi-task\"",
"train_amr.nodes[node_id] # count number of time a node is aligned to a token,",
"of txt reader propbank_args = None if args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args) # read/write",
"will break the code gold_amr.alignments[root_id] = [len(gold_amr.tokens)] # NOTE shifted by 1 for",
"print(yellow_font(alert_str)) if num_labelings > num_unique_sents: num_inconsistent = num_labelings - num_unique_sents perc = num_inconsistent",
"[]).append(s) return f'PRED({gold_amr.nodes[s]})' return None def try_entities_with_pred(self): \"\"\" allow pred inside entities that",
"fid: for word in multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words: assert not multitask_max_words assert not",
"len(tok_alignment) == 1: gold_nodeid = tok_alignment[0] else: # TODO check when this happens",
"for e in machine.amr.edges]: # to prevent same DEPENDENT added twice, as each",
"= machine.tok_cursor node_id = machine.current_node_id if node_id is None: # NOTE if node_id",
"key=lambda x: x[1]) )[-max_symbols:]) if add_root: # Add root regardless allowed_words.update({'ROOT': word_count['ROOT']}) return",
"COPY_SENSE01. If 1) the current token is aligned to a single node, or",
"None #for act_id, act_node_id in enumerate(machine.actions_to_nodes): for act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id",
"multiple ENTITY here on a single token if machine.current_node_id in machine.entities: return None",
"return 'SHIFT' def get_multitask_actions(max_symbols, tokenized_corpus, add_root=False): word_count = Counter() for sentence in tokenized_corpus:",
"if len(nodes1) > 1: # get root of subgraph aligned to token 1",
"for s, r, t in edges: if r == ':name' and gold_amr.nodes[t] ==",
"check AMRS print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load propbank if provided # TODO: Use here",
"AMR alignment return gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of alignments between nodes and",
"the current node from the previous node at location pos CLOSE : complete",
"node_id) if arc is None: continue arc_name, arc_label = arc # avoid repetitive",
"entity_edges.append((s, r, t)) name_node_ids.append(t) if not name_node_ids: return None for s, r, t",
"and rank # results is more probable than rank + 1 len(node_counts) >",
"nxt_alignment: return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return None else: return None def",
"1) currently is on a node that was just constructed 2) there are",
"if provided # TODO: Use here XML propbank reader instead of txt reader",
"of one token --> need to use node id to check edges arc",
"action is MERGE. If 1) the current and the next token have the",
"multitask_words = get_multitask_actions( multitask_max_words, tokenized_corpus, add_root=add_root ) # store in file with open(out_multitask_words,",
"has been constructed, for multiple PREDs if gold_nodeid not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id,",
"# Add root regardless allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words,",
"# TODO: See if we can remove this part gold_amr = gold_amr.copy() gold_amr",
"def tokens(self): return self.gold_amr.tokens @property def time_step(self): return self.machine.time_step @property def actions(self): return",
"action is REDUCE. If 1) there is nothing aligned to a token. \"\"\"",
"# do not write CLOSE action at the end; # CLOSE action is",
": form a left arc from the current node to the previous node",
"Load/Save words for multi-task if multitask_max_words: assert multitask_max_words assert out_multitask_words # get top",
"time we scan all the possible edges continue if t not in gold_nodeids",
"== t: return ('RA', r) if node1 == t and node2 == s:",
"gold_amr.edges if s in align and t in align ] if not edges:",
"entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\") # Load AMR (replace some unicode characters) # TODO:",
"can have pred\" ) args = parser.parse_args() return args def yellow_font(string): return \"\\033[93m%s\\033[0m\"",
"'attacks', 'were', 'unprecedented', '.', '<ROOT>']: # if self.time_step >= 8: # breakpoint() action",
"1 if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ): remove = 0 gold_amr.alignments[align[remove]].remove(i",
"from repeated sents' ) print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens)",
"if add_root: # Add root regardless allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words,",
"for s, r, t in entity_edges: if t not in self.built_gold_nodeids: self.built_gold_nodeids.append(t) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id,",
"LA if there is an edge `node_id2` <-- `node_id2` Thus the order of",
"new_node: action = 'COPY_LEMMA' elif f'{lemma}-01' == new_node: action = 'COPY_SENSE01' else: action",
"write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t' ) # State machine stats for this sentence if",
"# TODO if not dealt with, this causes a problem when the root",
"default=\"person,thing\", help=\"comma separated list of entity types that can have pred\" ) args",
"k in action_count.keys()])) print('Most frequent actions:') print(action_count.most_common(10)) if singletons: base_action_count = [x.split('(')[0] for",
"[] name_node_ids = [] for s, r, t in edges: if r ==",
"is only to the source nodes in the # aligned subgraph, whereas for",
"possible edges continue if t not in gold_nodeids and (t in gold_amr.alignments and",
"\"<ROOT>\" gold_amr.edges.append((root_id, \"root\", gold_amr.root)) # gold_amr.alignments[root_id] = [-1] # NOTE do not do",
"Only for :polarity and :mode, if an edge and node is aligned to",
"in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules for idx, action in enumerate(actions): if",
"= self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1, list): nodes1 = [nodes1] if not isinstance(nodes2, list):",
"the rank, node in that rank matches, and rank # results is more",
"amrs for n in amr.nodes.values() ]) node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count",
"in edges)] new_nodes = ','.join([gold_amr.nodes[n] for n in gold_nodeids]) action = f'ENTITY({new_nodes})' self.built_gold_nodeids.extend(gold_nodeids)",
"need to use node id to check edges arc = self.get_arc(act_node_id, node_id) if",
"the first time on a new token return None tok_id = machine.tok_cursor tok_alignment",
"edge `node_id1` --> `node_id2` LA if there is an edge `node_id2` <-- `node_id2`",
"for s, r, t in edges: if s not in self.built_gold_nodeids: new_id =",
"for node_id, aligned_tokens in alignments.items(): # join multiple words into one single expression",
"nothing aligned to a token. \"\"\" machine = self.machine gold_amr = self.gold_amr if",
"than 1 nodes, and 2) there are edges in the aligned subgraph, and",
"% inconsistent labelings from repeated sents'.format( num_inconsistent, num_sentences, perc ) print(yellow_font(alert_str)) def read_multitask_words(multitask_list):",
"\"\"\" allow pred inside entities that frequently need it i.e. person, thing \"\"\"",
"node is only to the source nodes in the # aligned subgraph, whereas",
"class AMROracleBuilder: \"\"\"Build AMR oracle for one sentence.\"\"\" def __init__(self, gold_amr, lemmatizer, copy_lemma_action,",
"is slow lemmatizer = get_spacy_lemmatizer() # This will store the oracle stats statistics",
"tid in tids if tid <= len(gold_amr.tokens)] # TODO: describe this # append",
"gold_amr.nodes[root] not in entities_with_preds and not is_dependent: return None new_id = None for",
"frequent actions:') print(action_count.most_common(10)) if singletons: base_action_count = [x.split('(')[0] for x in singletons] msg",
"multitask_words def print_corpus_info(amrs): # print some info print(f'{len(amrs)} sentences') node_label_count = Counter([ n",
"entity case: (entity_category, ':name', 'name') # no need, since named entity check happens",
"try_named_entities(self): \"\"\" Get the named entity sub-sequences one by one from the current",
"if self.tokens == ['The', 'cyber', 'attacks', 'were', 'unprecedented', '.', '<ROOT>']: # if self.time_step",
"for k, c in action_count.items() if c == 1] print('Base actions:') print(Counter([k.split('(')[0] for",
"action: if len(self.machine.actions) and self.machine.actions[-1] == 'SHIFT' and self.machine.tok_cursor != self.machine.tokseq_len - 1",
"1 nodes, and 2) there are edges in the aligned subgraph, and then",
"could there be more than one edges? # currently we only return the",
"from 0) -> for DEPENDENT missing # if self.tokens == ['The', 'cyber', 'attacks',",
"pass # There is more than one labeling for this sentence # amrs",
"print_corpus_info(amrs): # print some info print(f'{len(amrs)} sentences') node_label_count = Counter([ n for amr",
"self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node: action = 'COPY_LEMMA' elif f'{lemma}-01'",
"form a new node by copying lemma COPY_SENSE01 : form a new node",
"two entities with same surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') PRED('city') [other",
"node by copying lemma COPY_SENSE01 : form a new node by copying lemma",
"f'DEPENDENT({new_node},{new_edge})' return action return None def try_arcs(self): \"\"\" Get the arcs that involve",
"# TODO check why this happens in the data reading process # TODO",
"to # repeat `add_unaligned` times if add_unaligned: for i in range(add_unaligned): gold_amr.tokens.append(\"<unaligned>\") for",
"= line.strip().split('\\t') if len(items) > 2: multitask_words.append(items[1]) return multitask_words def label_shift(state_machine, multitask_words): tok",
"target_lengths = [] action_count = Counter() for tokens, actions in zip(sentence_tokens, oracle_actions): #",
"not action: # action = self.try_dependent() if not action: action = self.try_arcs() #if",
"\"Oracle must be deterministic\" assert len(invalid_actions) == 0, \"Oracle can\\'t blacklist actions\" action",
"tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE the index +",
"continue # pointer value arc_pos = act_id return f'{arc_name}({arc_pos},{arc_label})' return None def get_arc(self,",
"builder oracle_builder = AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words) # build the oracle actions sequence",
"Add conditional if here multitask_words = process_multitask_words( [list(amr.tokens) for amr in gold_amrs], args.multitask_max_words,",
"parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab separation in actions and sentences by removing whitespaces\"",
"ending sequence is always [... SHIFT CLOSE] or [... LA(pos,'root') SHIFT CLOSE] machine",
"LA(pos,':name') ENTITY('name') PRED('city') [other arcs] LA(pos,':name') \"\"\" machine = self.machine gold_amr = self.gold_amr",
"checks? and also the ENTITY if len(gold_nodeids) == 1: gold_nodeid = gold_nodeids[0] else:",
"f'PRED({new_node})' else: action = f'PRED({new_node})' return action return None def try_entity(self): \"\"\" Check",
"amr_counts_by_sentence = defaultdict(lambda: Counter()) for amr in gold_amrs: # hash of sentence skey",
"skey = \" \".join(amr.tokens) # count number of time sentence repeated sentence_count.update([skey]) #",
"[]).append(t) new_edge = r[1:] if r.startswith(':') else r new_node = gold_amr.nodes[t] action =",
"at location pos CLOSE : complete AMR, run post-processing \"\"\" use_addnode_rules = True",
"TODO: See if we can remove this part gold_amr = gold_amr.copy() gold_amr =",
"for multi-task\" ) parser.add_argument( \"--in-multitask-words\", type=str, help=\"where to read top-k words for multi-task\"",
"# NOTE gold amr root id is fixed at -1 self.built_gold_nodeids = []",
"= [tid for tid in tids if tid <= len(gold_amr.tokens)] # TODO: describe",
"node_id1, node_id2): \"\"\" Get the arcs between node with `node_id1` and node with",
"amr.nodes.values() ]) node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count = Counter([t[1] for amr",
"type=str ) # Multiple input parameters parser.add_argument( \"--out-amr\", help=\"corresponding AMR\", type=str ) #",
"# just in case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id + 1) # below is coupled",
"source_lengths = [] target_lengths = [] action_count = Counter() for tokens, actions in",
"if not cur_alignment or not nxt_alignment: return None # If both tokens are",
"aligned node has not been predicted yet \"\"\" machine = self.machine gold_amr =",
"for line in fid: items = line.strip().split('\\t') if len(items) > 2: multitask_words.append(items[1]) return",
"TODO for multiple PREDs, we need to do a for loop here #",
"+ 1 and node_counts.most_common(rank + 1)[-1][0] == node and node_counts.most_common(rank + 1)[-1][1] >",
"node2 = nodes2[0] # find edges for s, r, t in gold_amr.edges: if",
"r, t in gold_amr.edges: if node1 == s and node2 == t: return",
"internally managed, and treated same as <eos> in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred",
"is in `included_unaligned` to align to # repeat `add_unaligned` times if add_unaligned: for",
"gold_nodeid and r in [':polarity', ':mode']: if (node_id, r) in [(e[0], e[1]) for",
"Counter([w for amr in amrs for w in amr.tokens]) word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens}",
"write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t' ) # State machine",
"move cursor to next position in the token sequence REDUCE : delete current",
"root aligned token id is sentence length (not -1) for nid, tids in",
"align and t in align ] if not edges: remove = 1 if",
"# inform user if num_sentences > num_unique_sents: num_repeated = num_sentences - num_unique_sents perc",
"constructed 2) there are edges that have not been built with this node",
"or not gold_amr.alignments[n]: if gold_amr.nodes[n] in included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)] break # add",
"= defaultdict(list) for i in range(len(train_amr.tokens)): for al_node in train_amr.alignmentsToken2Node(i + 1): alignments[al_node].append(",
"highest, then named entity subsequence, etc. # debug # on dev set, sentence",
"have the same node alignment. \"\"\" machine = self.machine gold_amr = self.gold_amr if",
"for two entities with two surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') ENTITY('name')",
"for i, tok in enumerate(gold_amr.tokens): align = gold_amr.alignmentsToken2Node(i + 1) if len(align) ==",
"line.strip().split('\\t') if len(items) > 2: multitask_words.append(items[1]) return multitask_words def label_shift(state_machine, multitask_words): tok =",
"= label_shift(self.machine, self.multitask_words) valid_actions = [action] invalid_actions = [] return valid_actions, invalid_actions def",
"be careful about the root node id which should be -1 now #",
"named entity subsequence, etc. # debug # on dev set, sentence id 459",
"if r == ':name' and gold_amr.nodes[t] == 'name': is_named = True if r",
") write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'], separator='\\t' ) # State machine stats for this sentence",
"defaultdict(lambda: Counter()) for amr in gold_amrs: # hash of sentence skey = \"",
"= gold_amr.nodes[new_id] if self.copy_lemma_action: lemma = machine.get_current_token(lemma=True) if lemma == new_node: action =",
"for n in gold_amr.nodes: if n not in gold_amr.alignments or not gold_amr.alignments[n]: if",
"gold_amr, lemmatizer, copy_lemma_action, multitask_words): self.gold_amr = gold_amr # initialize the state machine self.machine",
"arc_label = arc # avoid repetitive edges if arc_name == 'LA': if (node_id,",
"2 ids) # TODO could there be more than one edges? # currently",
"self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(t) return 'ENTITY(name)' if s not in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return",
"gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions def try_reduce(self): \"\"\" Check if the next action",
"node has not been built at current step return None # NOTE this",
"None # check if named entity case: (entity_category, ':name', 'name') entity_edges = []",
"gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) # NOTE this might affect the next DEPEDENT check, but",
"PRED(<ROOT>) currently, as the root node is automatically added at the beginning #",
"len(valid_actions) == 1, \"Oracle must be deterministic\" assert len(invalid_actions) == 0, \"Oracle can\\'t",
"node with `node_id2`. RA if there is an edge `node_id1` --> `node_id2` LA",
"a token id to -1 will break the code gold_amr.alignments[root_id] = [len(gold_amr.tokens)] #",
"pointer_arc_re = re.compile(r'^(LA|RA)\\(([0-9]+),(.*)\\)$') assert len(sentence_tokens) == len(oracle_actions) source_lengths = [] target_lengths = []",
"n for amr in amrs for n in amr.nodes.values() ]) node_tokens = sum(node_label_count.values())",
"= self.get_arc(act_node_id, node_id) if arc is None: continue arc_name, arc_label = arc #",
"import tqdm from transition_amr_parser.io import read_propbank, read_amr, write_tokenized_sentences from transition_amr_parser.action_pointer.o8_state_machine import ( AMRStateMachine,",
"not out_multitask_words # store in file with open(in_multitask_words) as fid: multitask_words = [line.strip()",
"do not do this; we have made all the token ids natural positive",
"a node which is a dependent of the current node LA(pos,label) : form",
"type=str, help=\"where to store top-k words for multi-task\" ) parser.add_argument( \"--in-multitask-words\", type=str, help=\"where",
"current token aligned node. If 1) currently is on a node that was",
"for idx, action in enumerate(actions): if pred_re.match(action): node_name = pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx]",
"> 2: multitask_words.append(items[1]) return multitask_words def label_shift(state_machine, multitask_words): tok = state_machine.get_current_token(lemma=False) if tok",
"on priority # e.g. within node-arc actions, arc subsequence comes highest, then named",
"types/tokens') word_label_count = Counter([w for amr in amrs for w in amr.tokens]) word_tokens",
"perc, 'inconsistent labelings from repeated sents' ) print(yellow_font(alert_str)) def sanity_check_actions(sentence_tokens, oracle_actions): pointer_arc_re =",
"dealt with, this causes a problem when the root aligned token id is",
"id is sentence length (not -1) for nid, tids in gold_amr.alignments.items(): gold_amr.alignments[nid] =",
"copy_lemma_action self.multitask_words = multitask_words # TODO deprecate `multitask_words` or change for a better",
"for s, r, t in gold_amr.edges: if node1 == s and node2 ==",
"process # TODO and fix that and remove this cleaning process # an",
"( # as many results as the rank and node in that rank",
"with the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None #",
"by oracle\", type=str ) parser.add_argument( \"--out-sentences\", help=\"tokenized sentences from --in-amr\", type=str ) parser.add_argument(",
"Counter() for tokens, actions in zip(sentence_tokens, oracle_actions): # filter actions to remove pointer",
"# no need since the REDUCE check happens first if len(tok_alignment) == 1:",
"'name': entity_edges.append((s, r, t)) name_node_ids.append(t) if not name_node_ids: return None for s, r,",
"nid, tids in gold_amr.alignments.items(): gold_amr.alignments[nid] = [tid for tid in tids if tid",
"Counter()) } } pred_re = re.compile(r'^PRED\\((.*)\\)$') # Process AMRs one by one for",
"is any edge with the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges:",
"t in edges: if s not in self.built_gold_nodeids: new_id = s break if",
"\"\"\" machine = self.machine gold_amr = self.gold_amr if machine.current_node_id is not None: #",
"= [] return valid_actions, invalid_actions def build_oracle_actions(self): \"\"\"Build the oracle action sequence for",
"labeling akey = amr.toJAMRString() # store different amr labels for same sent, keep",
"print stats about actions sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t'",
"node1 == s and node2 == t: return ('RA', r) if node1 ==",
"gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not in entities_with_preds and not is_dependent: return None new_id =",
"to '_' help=\"statistics about alignments\", type=str ) # Multiple input parameters parser.add_argument( \"--out-amr\",",
"matches, and rank # results is more probable than rank + 1 len(node_counts)",
"if len(items) > 2: multitask_words.append(items[1]) return multitask_words def label_shift(state_machine, multitask_words): tok = state_machine.get_current_token(lemma=False)",
"in file with open(out_multitask_words, 'w') as fid: for word in multitask_words.keys(): fid.write(f'{word}\\n') elif",
"statistics def main(): # Argument handling args = argument_parser() global entities_with_preds entities_with_preds =",
"of the current node LA(pos,label) : form a left arc from the current",
"- num_unique_sents perc = num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % {:s}'.format(",
"Counter() for sentence in tokenized_corpus: word_count.update([x for x in sentence]) # Restrict to",
"list): nodes2 = [nodes2] if not nodes1 or not nodes2: return None #",
"NOTE this might affect the next DEPEDENT check, but is fine if we",
"# find edges for s, r, t in gold_amr.edges: if node1 == s",
"and self.machine.tok_cursor != self.machine.tokseq_len - 1 : action = 'REDUCE' else: action =",
"PREDs, we need to do a for loop here # check if the",
"node in that rank matches len(node_counts) == rank + 1 and node_counts.most_common(rank +",
"Check if the next action is DEPENDENT. If 1) the aligned node has",
"def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence",
"info print(f'{len(amrs)} sentences') node_label_count = Counter([ n for amr in amrs for n",
"assert not out_multitask_words # store in file with open(in_multitask_words) as fid: multitask_words =",
"= self.try_pred() if not action: if len(self.machine.actions) and self.machine.actions[-1] == 'SHIFT' and self.machine.tok_cursor",
"def try_reduce(self): \"\"\" Check if the next action is REDUCE. If 1) there",
"states info self.nodeid_to_gold_nodeid = {} # key: node id in the state machine,",
"contains heuristics for generating linearized action sequences for AMR graphs in a rule",
"for AMR graphs in a rule based way. The parsing algorithm is transition-based",
"top-k words for multi-task\" ) parser.add_argument( \"--in-multitask-words\", type=str, help=\"where to read top-k words",
"multitask_words = [] with open(multitask_list) as fid: for line in fid: items =",
"multitask_words # TODO deprecate `multitask_words` or change for a better name such as",
"the next action is PRED, COPY_LEMMA, COPY_SENSE01. If 1) the current token is",
"== node and node_counts.most_common(rank + 1)[-1][1] > node_counts.most_common(rank + 2)[-1][1] ) ) def",
"(max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, max( count for counter in",
"self.built_gold_nodeids = [] @property def tokens(self): return self.gold_amr.tokens @property def time_step(self): return self.machine.time_step",
"edge `node_id2` <-- `node_id2` Thus the order of inputs matter. (could also change",
"if not isinstance(nodes1, list): nodes1 = [nodes1] if not isinstance(nodes2, list): nodes2 =",
"= self.try_named_entities() if not action: action = self.try_entities_with_pred() if not action: action =",
"filter actions to remove pointer for action in actions: if pointer_arc_re.match(action): items =",
"len(self.machine.actions) and self.machine.actions[-1] == 'SHIFT' and self.machine.tok_cursor != self.machine.tokseq_len - 1 : action",
"line in fid.readlines()] else: multitask_words = None return multitask_words def print_corpus_info(amrs): # print",
"t in edges: if r == ':name' and gold_amr.nodes[t] == 'name': return None",
"fixes and other normalizations should be applied more # transparently print(f'Reading {args.in_amr}') corpus",
"tokenized_corpus, add_root=False): word_count = Counter() for sentence in tokenized_corpus: word_count.update([x for x in",
"sent_count in sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey]) > 1: pass # There",
"no need since the REDUCE check happens first if len(tok_alignment) == 1: gold_nodeid",
"times)'.format( num_repeated, num_sentences, 100 * perc, max( count for counter in amr_counts_by_sentence.values() for",
": form a new node with label COPY_LEMMA : form a new node",
"AMR graphs in a rule based way. The parsing algorithm is transition-based combined",
") # copy lemma action parser.add_argument( \"--copy-lemma-action\", action='store_true', help=\"Use copy action from Spacy",
"% repeated sents (max {:d} times)'.format( num_repeated, num_sentences, 100 * perc, max( count",
"= sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class AMROracleBuilder: \"\"\"Build AMR oracle for one sentence.\"\"\"",
"= self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor if tok_id == machine.tokseq_len -",
"nodes2: return None # convert to single node aligned to each of these",
"if akey not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr # count how many time",
"`multitask_words` or change for a better name such as `shift_label_words` # AMR construction",
"sentence, based on the gold AMR and the alignment. \"\"\" # Loop over",
"<eos> in training statistics['oracle_actions'].append(actions[:-1]) statistics['oracle_amr'].append(oracle_builder.machine.amr.toJAMRString()) # pred rules for idx, action in enumerate(actions):",
"\"\"\" Check if the next action is REDUCE. If 1) there is nothing",
"tokens if len(nodes1) > 1: # get root of subgraph aligned to token",
"tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO: See if we can remove this part gold_amr =",
"num_labelings = 0 for skey, sent_count in sentence_count.items(): num_labelings += len(amr_counts_by_sentence[skey]) if len(amr_counts_by_sentence[skey])",
"machine.get_current_token(lemma=True) if lemma == new_node: action = 'COPY_LEMMA' elif f'{lemma}-01' == new_node: action",
"NOTE gold amr root id is fixed at -1 self.built_gold_nodeids = [] @property",
"action is DEPENDENT. If 1) the aligned node has been predicted already 2)",
"an edge `node_id1` --> `node_id2` LA if there is an edge `node_id2` <--",
"not None: action = label_shift(self.machine, self.multitask_words) valid_actions = [action] invalid_actions = [] return",
"self.try_arcs() #if not action: # action = self.try_named_entities() if not action: action =",
"> 1: # get root of subgraph aligned to token 1 node1 =",
"we have made all the token ids natural positive index # setting a",
"form a left arc from the current node to the previous node at",
"lemma COPY_SENSE01 : form a new node by copying lemma and add '01'",
"nodes and surface words\"\"\" node_by_token = defaultdict(lambda: Counter()) for train_amr in gold_amrs_train: #",
"( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ): remove = 0 gold_amr.alignments[align[remove]].remove(i + 1)",
"node \"\"\" machine = self.machine node_id = machine.current_node_id if node_id is None: #",
"(labeled shift) action # TODO: Add conditional if here multitask_words = process_multitask_words( [list(amr.tokens)",
"rank, node in that rank matches, and rank # results is more probable",
"= Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda: Counter()) for amr in gold_amrs:",
"== 'RA': if (act_node_id, arc_label, node_id) in machine.amr.edges: continue # pointer value arc_pos",
"this part gold_amr = gold_amr.copy() gold_amr = preprocess_amr(gold_amr) # Initialize oracle builder oracle_builder",
"we make all token ids positive natural index # check if the alignment",
"continue arc_name, arc_label = arc # avoid repetitive edges if arc_name == 'LA':",
"TODO and fix that and remove this cleaning process # an example is",
"sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count = Counter([w for amr in amrs for w",
"s not in self.built_gold_nodeids: self.built_gold_nodeids.append(s) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(s) return f'PRED({gold_amr.nodes[s]})' return None def try_entities_with_pred(self):",
"if here multitask_words = process_multitask_words( [list(amr.tokens) for amr in gold_amrs], args.multitask_max_words, args.in_multitask_words, args.out_multitask_words,",
"[(e[0], e[1]) for e in machine.amr.edges]: # to prevent same DEPENDENT added twice,",
"enumerate(actions): if pred_re.match(action): node_name = pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics def",
"actions and sentences by removing whitespaces\" ) # copy lemma action parser.add_argument( \"--copy-lemma-action\",",
"the aligned nodes edges = gold_amr.findSubGraph(tok_alignment).edges if not edges: return None is_dependent =",
"ids) # TODO could there be more than one edges? # currently we",
"node_id2): \"\"\" Get the arcs between node with `node_id1` and node with `node_id2`.",
"to follow strict orders between these 2 ids) # TODO could there be",
"':name' and gold_amr.nodes[t] == 'name': is_named = True if r in [':polarity', ':mode']:",
"# AMR construction states info self.nodeid_to_gold_nodeid = {} # key: node id in",
"sanity_check_actions(stats['sentence_tokens'], stats['oracle_actions']) # Save statistics write_tokenized_sentences( args.out_actions, stats['oracle_actions'], separator='\\t' ) write_tokenized_sentences( args.out_sentences, stats['sentence_tokens'],",
"{:d} times)'.format( num_repeated, num_sentences, 100 * perc, 'repeated sents', max( count for counter",
"arc_name == 'LA': if (node_id, arc_label, act_node_id) in machine.amr.edges: continue if arc_name ==",
"propbank_args = None if args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args) # read/write multi-task (labeled shift)",
"act_id return f'{arc_name}({arc_pos},{arc_label})' return None def get_arc(self, node_id1, node_id2): \"\"\" Get the arcs",
"parser oracle') # Single input parameters parser.add_argument( \"--in-amr\", help=\"AMR notation in LDC format\",",
"== new_node: action = 'COPY_LEMMA' elif f'{lemma}-01' == new_node: action = 'COPY_SENSE01' else:",
"COPY_LEMMA : form a new node by copying lemma COPY_SENSE01 : form a",
"= \" \".join(aligned_tokens) else: token_str = aligned_tokens[0] node = train_amr.nodes[node_id] # count number",
"about alignments\", type=str ) # Multiple input parameters parser.add_argument( \"--out-amr\", help=\"corresponding AMR\", type=str",
"[]).extend(gold_nodeids) return action def try_pred(self): \"\"\" Check if the next action is PRED,",
"transparently print(f'Reading {args.in_amr}') corpus = read_amr(args.in_amr, unicode_fixes=True) gold_amrs = corpus.amrs # sanity check",
"gold_amr.alignments[root_id] = [len(gold_amr.tokens)] # NOTE shifted by 1 for AMR alignment return gold_amr",
"[other arcs] LA(pos,':name') PRED('city') [other arcs] LA(pos,':name') c) for two entities with two",
"root of subgraph aligned to token 2 node2 = gold_amr.findSubGraph(nodes2).root else: node2 =",
") def sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence",
"how many time each hash appears amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count) num_labelings = 0",
"in gold_amrs_train: # Get alignments alignments = defaultdict(list) for i in range(len(train_amr.tokens)): for",
"machine, value: list of node ids in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] #",
"word_count.update([x for x in sentence]) # Restrict to top-k words allowed_words = dict(list(sorted(",
"num_sentences alert_str = '{:d}/{:d} {:2.4f} % {:s}'.format( num_inconsistent, num_sentences, perc, 'inconsistent labelings from",
"by replacing '-' to '_' help=\"statistics about alignments\", type=str ) # Multiple input",
"= defaultdict(lambda: Counter()) for amr in gold_amrs: # hash of sentence skey =",
"based way. The parsing algorithm is transition-based combined with pointers for long distance",
"# no need, since named entity check happens first is_dependent = False is_named",
"if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return None else: return None def try_named_entities(self): \"\"\" Get",
"next action is PRED, COPY_LEMMA, COPY_SENSE01. If 1) the current token is aligned",
"if cur_alignment == nxt_alignment: return 'MERGE' if set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return None else:",
"gold_nodeids = [n for n in tok_alignment if any(s == n for s,",
"token MERGE : merge two tokens (for MWEs) ENTITY(type) : form a named",
"not been built at current step return None # NOTE this doesn't work",
"rank and node in that rank matches len(node_counts) == rank + 1 and",
"regardless allowed_words.update({'ROOT': word_count['ROOT']}) return allowed_words def process_multitask_words(tokenized_corpus, multitask_max_words, in_multitask_words, out_multitask_words, add_root=False): # Load/Save",
"# NOTE do not do this; we have made all the token ids",
"+ 1) # check if alignment empty (or singleton) if len(tok_alignment) <= 1:",
"entities_with_preds or is_dependent): return None gold_nodeids = [n for n in tok_alignment if",
"# NOTE this doesn't work for ENTITY now, as the mapping from ENTITY",
"is coupled with the PRED checks? and also the ENTITY if len(gold_nodeids) ==",
"machine.current_node_id is not None: # not on the first time on a new",
"[len(gold_amr.tokens)] # NOTE shifted by 1 for AMR alignment return gold_amr def get_node_alignment_counts(gold_amrs_train):",
"help=\"Propbank argument data\", type=str, ) parser.add_argument( \"--out-oracle\", help=\"tokens, AMR notation and actions given",
"'one', 'is', # 'the', 'black', '-', 'faced', 'spoonbill', '.'] # TODO if not",
"If 1) the aligned node has been predicted already 2) Only for :polarity",
"/ num_sentences alert_str = '{:d}/{:d} {:2.4f} % inconsistent labelings from repeated sents'.format( num_inconsistent,",
"the gold AMR and the alignment. \"\"\" # Loop over potential actions #",
"gold_nodeids = self.nodeid_to_gold_nodeid[node_id] # gold_nodeids = list(set(gold_nodeids)) # just in case gold_nodeids =",
"try_entities_with_pred(self): \"\"\" allow pred inside entities that frequently need it i.e. person, thing",
"actions' print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string num_sentences =",
"action = 'SHIFT' if action == 'SHIFT' and self.multitask_words is not None: action",
"of AMR labeling akey = amr.toJAMRString() # store different amr labels for same",
"from collections import Counter, defaultdict import re from tqdm import tqdm from transition_amr_parser.io",
"invalid_actions def build_oracle_actions(self): \"\"\"Build the oracle action sequence for the current token sentence,",
"both tokens are mapped to same node or overlap if cur_alignment == nxt_alignment:",
"get_spacy_lemmatizer() # This will store the oracle stats statistics = { 'sentence_tokens': [],",
"num_sentences > num_unique_sents: num_repeated = num_sentences - num_unique_sents perc = num_repeated / num_sentences",
"if not action: action = self.try_entities_with_pred() if not action: action = self.try_entity() if",
"that frequently need it i.e. person, thing \"\"\" machine = self.machine gold_amr =",
"root of subgraph aligned to token 1 node1 = gold_amr.findSubGraph(nodes1).root else: node1 =",
"argument_parser() global entities_with_preds entities_with_preds = args.in_pred_entities.split(\",\") # Load AMR (replace some unicode characters)",
"= gold_amr.alignmentsToken2Node(nxt + 1) if not cur_alignment or not nxt_alignment: return None #",
"yellow_font(string): return \"\\033[93m%s\\033[0m\" % string entities_with_preds = [] def preprocess_amr(gold_amr, add_unaligned=None, included_unaligned=None, root_id=-1):",
"import argparse from collections import Counter, defaultdict import re from tqdm import tqdm",
") parser.add_argument( \"--in-multitask-words\", type=str, help=\"where to read top-k words for multi-task\" ) parser.add_argument(",
"= gold_amr.findSubGraph(tok_alignment).root if gold_amr.nodes[root] not in entities_with_preds and not is_dependent: return None new_id",
"node is aligned to a token, indexed by # token node_by_token[token_str].update([node]) return node_by_token",
"arc from the current node to the previous node at location pos RA(pos,label)",
"s and node2 == t: return ('RA', r) if node1 == t and",
"for sent_idx, gold_amr in tqdm(enumerate(gold_amrs), desc='Oracle'): # TODO: See if we can remove",
") parser.add_argument( \"--out-oracle\", help=\"tokens, AMR notation and actions given by oracle\", type=str )",
"len(aligned_tokens) > 1: token_str = \" \".join(aligned_tokens) else: token_str = aligned_tokens[0] node =",
"AMR self.nodeid_to_gold_nodeid[self.machine.root_id] = [-1] # NOTE gold amr root id is fixed at",
"one entity ENTITY('name') PRED('city') [other arcs] LA(pos,':name') b) for two entities with same",
"r[1:] if r.startswith(':') else r new_node = gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})' return action",
"# if self.time_step >= 8: # breakpoint() action = self.try_reduce() if not action:",
"not nxt_alignment: return None # If both tokens are mapped to same node",
"statistics of alignments between nodes and surface words\"\"\" node_by_token = defaultdict(lambda: Counter()) for",
"not node_id' would cause a bug # the node has not been built",
"initialize the state machine self.machine = AMRStateMachine(gold_amr.tokens, spacy_lemmatizer=lemmatizer, amr_graph=True, entities_with_preds=entities_with_preds) self.copy_lemma_action = copy_lemma_action",
"affect the next DEPEDENT check, but is fine if we always use subgraph",
"args parser.add_argument( \"--out-multitask-words\", type=str, help=\"where to store top-k words for multi-task\" ) parser.add_argument(",
"= num_inconsistent / num_sentences alert_str = '{:d}/{:d} {:2.4f} % {:s}'.format( num_inconsistent, num_sentences, perc,",
"in LDC format\", type=str, required=True ) parser.add_argument( \"--in-propbank-args\", help=\"Propbank argument data\", type=str, )",
"must be deterministic\" assert len(invalid_actions) == 0, \"Oracle can\\'t blacklist actions\" action =",
"beginning # NOTE to change this behavior, we need to be careful about",
"about the root node id which should be -1 now # that is",
"[], 'oracle_amr': [], 'rules': { # Will store count of PREDs given pointer",
"--> need to use node id to check edges arc = self.get_arc(act_node_id, node_id)",
"self.built_gold_nodeids: new_id = t break if new_id != None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node",
"ENTITY('name') PRED('city') [other arcs] LA(pos,':name') PRED('city') [other arcs] LA(pos,':name') c) for two entities",
"not action: action = self.try_entities_with_pred() if not action: action = self.try_entity() if not",
"in machine.amr.edges: continue if arc_name == 'RA': if (act_node_id, arc_label, node_id) in machine.amr.edges:",
"edge types/tokens') word_label_count = Counter([w for amr in amrs for w in amr.tokens])",
"alert_str = '{:d}/{:d} {:2.1f} % repeated sents (max {:d} times)'.format( num_repeated, num_sentences, 100",
"action: action = self.try_arcs() #if not action: # action = self.try_named_entities() if not",
"pred inside entities that frequently need it i.e. person, thing \"\"\" machine =",
"pred\" ) args = parser.parse_args() return args def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string",
"t break if new_id != None: self.built_gold_nodeids.append(new_id) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(new_id) new_node = gold_amr.nodes[new_id] if",
"TODO this is accessed by replacing '-' to '_' help=\"statistics about alignments\", type=str",
"= num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % repeated sents (max {:d}",
"r in [':polarity', ':mode']: if (node_id, r) in [(e[0], e[1]) for e in",
"the gold amr but does not exist in the predicted amr, the oracle",
"words for multi-task if multitask_max_words: assert multitask_max_words assert out_multitask_words # get top words",
"it here; the ending sequence is always [... SHIFT CLOSE] or [... LA(pos,'root')",
"on the first time on a new token return None tok_id = machine.tok_cursor",
"node # whose label is in `included_unaligned` to align to # repeat `add_unaligned`",
"node ids in the gold AMR graph nodes1 = self.nodeid_to_gold_nodeid[node_id1] nodes2 = self.nodeid_to_gold_nodeid[node_id2]",
"f'PRED({gold_amr.nodes[s]})' return None def try_entities_with_pred(self): \"\"\" allow pred inside entities that frequently need",
"# avoid repetitive edges if arc_name == 'LA': if (node_id, arc_label, act_node_id) in",
"def get_valid_actions(self): \"\"\"Get the valid actions and invalid actions based on the current",
"`included_unaligned` to align to # repeat `add_unaligned` times if add_unaligned: for i in",
"msg = f'{len(singletons)} singleton actions' print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def yellow_font(string): return \"\\033[93m%s\\033[0m\"",
"'SHIFT' and self.machine.tok_cursor != self.machine.tokseq_len - 1 : action = 'REDUCE' else: action",
"= gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment empty (or singleton) if len(tok_alignment)",
"some unicode characters) # TODO: unicode fixes and other normalizations should be applied",
"gold_amr.nodes[t] action = f'DEPENDENT({new_node},{new_edge})' return action return None def try_arcs(self): \"\"\" Get the",
"(s, r, t) for s, r, t in gold_amr.edges if s in align",
"action = 'COPY_LEMMA' elif f'{lemma}-01' == new_node: action = 'COPY_SENSE01' else: action =",
"return None # check if there is any edge with the aligned nodes",
"is fine if we always use subgraph root self.nodeid_to_gold_nodeid.setdefault(node_id, []).append(t) new_edge = r[1:]",
"thing \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor tok_alignment =",
"':name', 'name') entity_edges = [] name_node_ids = [] for s, r, t in",
"root = gold_amr.findSubGraph(tok_alignment).root if not is_named and ( gold_amr.nodes[root] in entities_with_preds or is_dependent):",
"= True def argument_parser(): parser = argparse.ArgumentParser(description='AMR parser oracle') # Single input parameters",
"= 'COPY_SENSE01' else: action = f'PRED({new_node})' else: action = f'PRED({new_node})' return action else:",
"nodes2 = self.nodeid_to_gold_nodeid[node_id2] if not isinstance(nodes1, list): nodes1 = [nodes1] if not isinstance(nodes2,",
"return None if r in [':polarity', ':mode']: is_dependent = True root = gold_amr.findSubGraph(tok_alignment).root",
"end of the sentence for the first unaligned node # whose label is",
"self.try_entity() if not action: action = self.try_pred() if not action: if len(self.machine.actions) and",
"node_name = pred_re.match(action).groups()[0] token = oracle_builder.machine.actions_tokcursor[idx] statistics['rules']['possible_predicates'][token].update(node_name) return statistics def main(): # Argument",
"@property def time_step(self): return self.machine.time_step @property def actions(self): return self.machine.actions def get_valid_actions(self): \"\"\"Get",
"form a named entity, or a subgraph PRED(label) : form a new node",
"def argument_parser(): parser = argparse.ArgumentParser(description='AMR parser oracle') # Single input parameters parser.add_argument( \"--in-amr\",",
"aligned token id is sentence length (not -1) for nid, tids in gold_amr.alignments.items():",
"= gold_amr.alignmentsToken2Node(cur + 1) nxt_alignment = gold_amr.alignmentsToken2Node(nxt + 1) if not cur_alignment or",
"token have the same node alignment. \"\"\" machine = self.machine gold_amr = self.gold_amr",
"s, r, t in edges: if s not in self.built_gold_nodeids: new_id = s",
"store data statistics['sentence_tokens'].append(oracle_builder.tokens) # do not write CLOSE action at the end; #",
"tids if tid <= len(gold_amr.tokens)] # TODO: describe this # append a special",
"`node_id1` and node with `node_id2`. RA if there is an edge `node_id1` -->",
"as `shift_label_words` # AMR construction states info self.nodeid_to_gold_nodeid = {} # key: node",
"run post-processing \"\"\" use_addnode_rules = True def argument_parser(): parser = argparse.ArgumentParser(description='AMR parser oracle')",
"list(amr_by_amrkey_by_sentence[skey].values()) # inform user if num_sentences > num_unique_sents: num_repeated = num_sentences - num_unique_sents",
"= [] with open(multitask_list) as fid: for line in fid: items = line.strip().split('\\t')",
"if not action: if len(self.machine.actions) and self.machine.actions[-1] == 'SHIFT' and self.machine.tok_cursor != self.machine.tokseq_len",
"of these two tokens if len(nodes1) > 1: # get root of subgraph",
"of PREDs given pointer position 'possible_predicates': defaultdict(lambda: Counter()) } } pred_re = re.compile(r'^PRED\\((.*)\\)$')",
"# whose label is in `included_unaligned` to align to # repeat `add_unaligned` times",
"nodes1 = [nodes1] if not isinstance(nodes2, list): nodes2 = [nodes2] if not nodes1",
"in the gold amr but does not exist in the predicted amr, the",
"help=\"tokenized sentences from --in-amr\", type=str ) parser.add_argument( \"--out-actions\", help=\"actions given by oracle\", type=str",
"for t in amr.edges]) edge_tokens = sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count = Counter([w",
"if len(tok_alignment) == 1: gold_nodeid = tok_alignment[0] else: # TODO check when this",
"self.gold_amr if machine.current_node_id is not None: # not on the first time on",
"subgraph PRED(label) : form a new node with label COPY_LEMMA : form a",
"change for a better name such as `shift_label_words` # AMR construction states info",
"gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for s, r, t in gold_amr.edges: if s == gold_nodeid",
"2: multitask_words.append(items[1]) return multitask_words def label_shift(state_machine, multitask_words): tok = state_machine.get_current_token(lemma=False) if tok in",
"args.multitask_max_words, args.in_multitask_words, args.out_multitask_words, add_root=True ) # run the oracle for the entire corpus",
"here is important, which is based on priority # e.g. within node-arc actions,",
"can remove this part gold_amr = gold_amr.copy() gold_amr = preprocess_amr(gold_amr) # Initialize oracle",
"this causes a problem when the root aligned token id is sentence length",
"= self.gold_amr tok_id = machine.tok_cursor node_id = machine.current_node_id if node_id is None: #",
"r) return None def run_oracle(gold_amrs, copy_lemma_action, multitask_words): # Initialize lemmatizer as this is",
"not None: # not on the first time on a new token return",
"sentence skey = \" \".join(amr.tokens) # count number of time sentence repeated sentence_count.update([skey])",
"form a new node with label COPY_LEMMA : form a new node by",
"this; we have made all the token ids natural positive index # setting",
"\".join(aligned_tokens) else: token_str = aligned_tokens[0] node = train_amr.nodes[node_id] # count number of time",
"= machine.tok_cursor # to avoid subgraph ENTITY after named entities if tok_id in",
"self.machine.tok_cursor != self.machine.tokseq_len - 1 : action = 'REDUCE' else: action = 'SHIFT'",
"> len(gold_amr.alignments[align[1]]) ): remove = 0 gold_amr.alignments[align[remove]].remove(i + 1) gold_amr.token2node_memo = {} #",
"in gold_amr.alignments and gold_amr.alignments[t]): continue self.built_gold_nodeids.append(t) # NOTE this might affect the next",
") # Labeled shift args parser.add_argument( \"--out-multitask-words\", type=str, help=\"where to store top-k words",
"named entity case: (entity_category, ':name', 'name') entity_edges = [] name_node_ids = [] for",
"type=str ) # parser.add_argument( \"--verbose\", action='store_true', help=\"verbose processing\" ) # parser.add_argument( \"--multitask-max-words\", type=int,",
"self.gold_amr tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment",
"is_dependent = False for s, r, t in edges: if r == ':name'",
"not in entities_with_preds and not is_dependent: return None new_id = None for s,",
"entities if tok_id in machine.entity_tokenids: return None # NOTE currently do not allow",
"# pred rules for idx, action in enumerate(actions): if pred_re.match(action): node_name = pred_re.match(action).groups()[0]",
"node_counts.most_common(rank + 1)[-1][0] == node ) or ( # more results than the",
"+ 1 if len(tok_alignment) == 0: return 'REDUCE' else: return None def try_merge(self):",
"breakpoint() action = self.try_reduce() if not action: action = self.try_merge() #if not action:",
"dict(list(sorted( word_count.items(), key=lambda x: x[1]) )[-max_symbols:]) if add_root: # Add root regardless allowed_words.update({'ROOT':",
"self.gold_amr tok_id = machine.tok_cursor # to avoid subgraph ENTITY after named entities if",
"self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor if tok_id == machine.tokseq_len - 1:",
"PRED('city') [other arcs] LA(pos,':name') \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id =",
"== gold_nodeid and r in [':polarity', ':mode']: if (node_id, r) in [(e[0], e[1])",
"if args.in_propbank_args: propbank_args = read_propbank(args.in_propbank_args) # read/write multi-task (labeled shift) action # TODO:",
"if action == 'SHIFT' and self.multitask_words is not None: action = label_shift(self.machine, self.multitask_words)",
"stats statistics = { 'sentence_tokens': [], 'oracle_actions': [], 'oracle_amr': [], 'rules': { #",
"surface tokens ENTITY('name') PRED('city') [other arcs] LA(pos,':name') ENTITY('name') PRED('city') [other arcs] LA(pos,':name') \"\"\"",
"# if self.tokens == ['The', 'cyber', 'attacks', 'were', 'unprecedented', '.', '<ROOT>']: # if",
"node types/tokens') edge_label_count = Counter([t[1] for amr in amrs for t in amr.edges])",
"'cyber', 'attacks', 'were', 'unprecedented', '.', '<ROOT>']: # if self.time_step >= 8: # breakpoint()",
"type=str, ) parser.add_argument( \"--out-oracle\", help=\"tokens, AMR notation and actions given by oracle\", type=str",
"isinstance(nodes1, list): nodes1 = [nodes1] if not isinstance(nodes2, list): nodes2 = [nodes2] if",
"not edges: remove = 1 if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ):",
"node_id, aligned_tokens in alignments.items(): # join multiple words into one single expression if",
"== rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node ) or (",
"This algorithm contains heuristics for generating linearized action sequences for AMR graphs in",
"the alignments are outside of the sentence boundary # TODO check why this",
"map if akey not in amr_by_amrkey_by_sentence[skey]: amr_by_amrkey_by_sentence[skey][akey] = amr # count how many",
"not in self.built_gold_nodeids: self.built_gold_nodeids.append(gold_nodeid) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).append(gold_nodeid) new_node = gold_amr.nodes[gold_nodeid] if self.copy_lemma_action: lemma =",
"multitask_words) # build the oracle actions sequence actions = oracle_builder.build_oracle_actions() # store data",
"entity_edges = [] name_node_ids = [] for s, r, t in edges: if",
"action = self.try_arcs() #if not action: # action = self.try_named_entities() if not action:",
"is not None: action = label_shift(self.machine, self.multitask_words) valid_actions = [action] invalid_actions = []",
") ) def sanity_check_amr(gold_amrs): num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict)",
"machine.entities: return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment empty",
"current node from the previous node at location pos CLOSE : complete AMR,",
"included_unaligned: gold_amr.alignments[n] = [len(gold_amr.tokens)] break # add root node gold_amr.tokens.append(\"<ROOT>\") gold_amr.nodes[root_id] = \"<ROOT>\"",
"amr_counts_by_sentence[skey].update([akey]) num_unique_sents = len(sentence_count) num_labelings = 0 for skey, sent_count in sentence_count.items(): num_labelings",
"such as `shift_label_words` # AMR construction states info self.nodeid_to_gold_nodeid = {} # key:",
"n in amr.nodes.values() ]) node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count = Counter([t[1]",
"if node_id could be 0, 'if not node_id' would cause a bug #",
"'oracle_actions': [], 'oracle_amr': [], 'rules': { # Will store count of PREDs given",
"aligned to this token in the gold amr but does not exist in",
"get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of alignments between nodes and surface words\"\"\" node_by_token = defaultdict(lambda:",
"try_arcs(self): \"\"\" Get the arcs that involve the current token aligned node. If",
"deterministic\" assert len(invalid_actions) == 0, \"Oracle can\\'t blacklist actions\" action = valid_actions[0] #",
"if the next action is DEPENDENT. If 1) the aligned node has been",
"missing # if self.tokens == ['The', 'cyber', 'attacks', 'were', 'unprecedented', '.', '<ROOT>']: #",
"node at location pos RA(pos,label) : form a left arc to the current",
"(for MWEs) ENTITY(type) : form a named entity, or a subgraph PRED(label) :",
"and node_counts.most_common(rank + 1)[-1][1] > node_counts.most_common(rank + 2)[-1][1] ) ) def sanity_check_amr(gold_amrs): num_sentences",
"parser.add_argument( \"--out-amr\", help=\"corresponding AMR\", type=str ) # parser.add_argument( \"--verbose\", action='store_true', help=\"verbose processing\" )",
"= 1 if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ): remove = 0",
"gold_amr.findSubGraph(gold_nodeids).root for s, r, t in gold_amr.edges: if s == gold_nodeid and r",
"node from the previous node at location pos CLOSE : complete AMR, run",
"pointer_arc_re.match(action).groups() action = f'{items[0]}({items[2]})' action_count.update([action]) source_lengths.append(len(tokens)) target_lengths.append(len(actions)) pass singletons = [k for k,",
"self.gold_amr tok_id = machine.tok_cursor if tok_id == machine.tokseq_len - 1: # never do",
"\"\"\" Check if the next action is PRED, COPY_LEMMA, COPY_SENSE01. If 1) the",
"and node in that rank matches len(node_counts) == rank + 1 and node_counts.most_common(rank",
"for n in amr.nodes.values() ]) node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count =",
"top-k words allowed_words = dict(list(sorted( word_count.items(), key=lambda x: x[1]) )[-max_symbols:]) if add_root: #",
"sentence.\"\"\" def __init__(self, gold_amr, lemmatizer, copy_lemma_action, multitask_words): self.gold_amr = gold_amr # initialize the",
"machine.tokseq_len - 1: # never do PRED(<ROOT>) currently, as the root node is",
"amrs for w in amr.tokens]) word_tokens = sum(word_label_count.values()) print(f'{len(word_label_count)}/{word_tokens} word types/tokens') class AMROracleBuilder:",
"= gold_amr.findSubGraph(nodes1).root else: node1 = nodes1[0] if len(nodes2) > 1: # get root",
"parser.add_argument( \"--out-rule-stats\", # TODO this is accessed by replacing '-' to '_' help=\"statistics",
"open(out_multitask_words, 'w') as fid: for word in multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words: assert not",
"n in gold_amr.nodes: if n not in gold_amr.alignments or not gold_amr.alignments[n]: if gold_amr.nodes[n]",
"set, sentence id 459 (starting from 0) -> for DEPENDENT missing # if",
"debug # on dev set, sentence id 459 (starting from 0) -> for",
"[] action_count = Counter() for tokens, actions in zip(sentence_tokens, oracle_actions): # filter actions",
"num_sentences = len(gold_amrs) sentence_count = Counter() amr_by_amrkey_by_sentence = defaultdict(dict) amr_counts_by_sentence = defaultdict(lambda: Counter())",
"= sum(edge_label_count.values()) print(f'{len(edge_label_count)}/{edge_tokens} edge types/tokens') word_label_count = Counter([w for amr in amrs for",
"action = self.try_merge() #if not action: # action = self.try_dependent() if not action:",
"if len(align) == 2: edges = [ (s, r, t) for s, r,",
"the current surface token (segments). E.g. a) for one entity ENTITY('name') PRED('city') [other",
"token_str = aligned_tokens[0] node = train_amr.nodes[node_id] # count number of time a node",
"else: action = f'PRED({new_node})' else: action = f'PRED({new_node})' return action else: return None",
"REDUCE : delete current token MERGE : merge two tokens (for MWEs) ENTITY(type)",
"oracle') # Single input parameters parser.add_argument( \"--in-amr\", help=\"AMR notation in LDC format\", type=str,",
"# append a special token at the end of the sentence for the",
"gold_amr = self.gold_amr tok_id = machine.tok_cursor node_id = machine.current_node_id if node_id is None:",
"help=\"comma separated list of entity types that can have pred\" ) args =",
"node id which should be -1 now # that is also massively used",
"action = self.try_dependent() if not action: action = self.try_arcs() #if not action: #",
"# gold_nodeids = list(set(gold_nodeids)) # just in case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id + 1)",
"on a new token return None if machine.tok_cursor < machine.tokseq_len - 1: cur",
"distance arcs. Actions are SHIFT : move cursor to next position in the",
"or change for a better name such as `shift_label_words` # AMR construction states",
"currently, as the root node is automatically added at the beginning # NOTE",
"outside of the sentence boundary # TODO check why this happens in the",
"last position is added as a node from the beginning, so no prediction",
"between node with `node_id1` and node with `node_id2`. RA if there is an",
"action at the end; # CLOSE action is internally managed, and treated same",
"]) node_tokens = sum(node_label_count.values()) print(f'{len(node_label_count)}/{node_tokens} node types/tokens') edge_label_count = Counter([t[1] for amr in",
"arcs that involve the current token aligned node. If 1) currently is on",
"gold_nodeid = gold_nodeids[0] else: gold_nodeid = gold_amr.findSubGraph(gold_nodeids).root for s, r, t in gold_amr.edges:",
"node with `node_id1` and node with `node_id2`. RA if there is an edge",
"def actions(self): return self.machine.actions def get_valid_actions(self): \"\"\"Get the valid actions and invalid actions",
"self.built_gold_nodeids.extend(gold_nodeids) self.nodeid_to_gold_nodeid.setdefault(machine.new_node_id, []).extend(gold_nodeids) return action def try_pred(self): \"\"\" Check if the next action",
"= gold_amr.copy() gold_amr = preprocess_amr(gold_amr) # Initialize oracle builder oracle_builder = AMROracleBuilder(gold_amr, lemmatizer,",
"a new token return None if machine.tok_cursor < machine.tokseq_len - 1: cur =",
"edges: remove = 1 if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ): remove",
"- num_unique_sents perc = num_repeated / num_sentences alert_str = '{:d}/{:d} {:2.1f} % repeated",
"for this sentence if args.out_rule_stats: with open(args.out_rule_stats, 'w') as fid: fid.write(json.dumps(stats['rules'])) if __name__",
"* perc, 'repeated sents', max( count for counter in amr_counts_by_sentence.values() for count in",
"= [] action_count = Counter() for tokens, actions in zip(sentence_tokens, oracle_actions): # filter",
"= f'PRED({new_node})' return action return None def try_entity(self): \"\"\" Check if the next",
"if node1 == s and node2 == t: return ('RA', r) if node1",
"\"--verbose\", action='store_true', help=\"verbose processing\" ) # parser.add_argument( \"--multitask-max-words\", type=int, help=\"number of woprds to",
"causes a problem when the root aligned token id is sentence length (not",
"if ( gold_amr.nodes[align[1]].startswith(tok[:2]) or len(gold_amr.alignments[align[0]]) > len(gold_amr.alignments[align[1]]) ): remove = 0 gold_amr.alignments[align[remove]].remove(i +",
"provided # TODO: Use here XML propbank reader instead of txt reader propbank_args",
"which should be -1 now # that is also massively used in postprocessing",
"the source nodes in the aligned subgraph altogether. \"\"\" machine = self.machine gold_amr",
"== ':name' and gold_amr.nodes[t] == 'name': return None if r in [':polarity', ':mode']:",
"- 1: # never do PRED(<ROOT>) currently, as the root node is automatically",
"machine # below are equivalent # machine.apply_action('CLOSE', training=True, gold_amr=self.gold_amr) machine.CLOSE(training=True, gold_amr=self.gold_amr) return self.actions",
"is also massively used in postprocessing to find/add root. return None tok_alignment =",
": Add a node which is a dependent of the current node LA(pos,label)",
"from the current node to the previous node at location pos RA(pos,label) :",
"lemma == new_node: action = 'COPY_LEMMA' elif f'{lemma}-01' == new_node: action = 'COPY_SENSE01'",
"root. return None tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # NOTE we make all",
"id which should be -1 now # that is also massively used in",
"= self.nodeid_to_gold_nodeid[node_id] # gold_nodeids = list(set(gold_nodeids)) # just in case gold_nodeids = gold_amr.alignmentsToken2Node(tok_id",
"edges arc = self.get_arc(act_node_id, node_id) if arc is None: continue arc_name, arc_label =",
"set(cur_alignment).intersection(set(nxt_alignment)): return 'MERGE' return None else: return None def try_named_entities(self): \"\"\" Get the",
"processing\" ) # parser.add_argument( \"--multitask-max-words\", type=int, help=\"number of woprds to use for multi-task\"",
"we can remove this part gold_amr = gold_amr.copy() gold_amr = preprocess_amr(gold_amr) # Initialize",
"# Initialize oracle builder oracle_builder = AMROracleBuilder(gold_amr, lemmatizer, copy_lemma_action, multitask_words) # build the",
"the state machine, value: list of node ids in gold AMR self.nodeid_to_gold_nodeid[self.machine.root_id] =",
"RA(pos,label) : form a left arc to the current node from the previous",
"actions given by oracle\", type=str ) parser.add_argument( \"--out-sentences\", help=\"tokenized sentences from --in-amr\", type=str",
"at -1 self.built_gold_nodeids = [] @property def tokens(self): return self.gold_amr.tokens @property def time_step(self):",
"a rule based way. The parsing algorithm is transition-based combined with pointers for",
"any(s == n for s, r, t in edges)] new_nodes = ','.join([gold_amr.nodes[n] for",
"given by oracle\", type=str ) parser.add_argument( \"--out-sentences\", help=\"tokenized sentences from --in-amr\", type=str )",
"alignments[al_node].append( train_amr.tokens[i] ) for node_id, aligned_tokens in alignments.items(): # join multiple words into",
"there is an edge `node_id1` --> `node_id2` LA if there is an edge",
"words for multi-task\" ) parser.add_argument( \"--no-whitespace-in-actions\", action='store_true', help=\"avoid tab separation in actions and",
"word in multitask_words.keys(): fid.write(f'{word}\\n') elif in_multitask_words: assert not multitask_max_words assert not out_multitask_words #",
"\"\"\" machine = self.machine gold_amr = self.gold_amr tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id",
"and self.machine.actions[-1] == 'SHIFT' and self.machine.tok_cursor != self.machine.tokseq_len - 1 : action =",
"has not been predicted yet \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id",
"do this; we have made all the token ids natural positive index #",
") args = parser.parse_args() return args def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string entities_with_preds",
"rank matches len(node_counts) == rank + 1 and node_counts.most_common(rank + 1)[-1][0] == node",
"with pointers for long distance arcs. Actions are SHIFT : move cursor to",
"1: gold_nodeid = tok_alignment[0] else: # TODO check when this happens -> should",
"return None else: return None def try_named_entities(self): \"\"\" Get the named entity sub-sequences",
"AMR.\"\"\" # find the next action # NOTE the order here is important,",
"1 for AMR alignment return gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics of alignments between",
"lemmatizer, copy_lemma_action, multitask_words): self.gold_amr = gold_amr # initialize the state machine self.machine =",
"new_node: action = 'COPY_SENSE01' else: action = f'PRED({new_node})' else: action = f'PRED({new_node})' return",
"= f'{len(singletons)} singleton actions' print(yellow_font(msg)) print(Counter(base_action_count)) def alert_inconsistencies(gold_amrs): def yellow_font(string): return \"\\033[93m%s\\033[0m\" %",
"print_corpus_info(gold_amrs) sanity_check_amr(gold_amrs) # Load propbank if provided # TODO: Use here XML propbank",
"NOTE shifted by 1 for AMR alignment return gold_amr def get_node_alignment_counts(gold_amrs_train): \"\"\"Get statistics",
"gold_amr.findSubGraph(tok_alignment).edges if not edges: return None is_dependent = False for s, r, t",
"alignment. \"\"\" machine = self.machine gold_amr = self.gold_amr if machine.current_node_id is not None:",
"} pred_re = re.compile(r'^PRED\\((.*)\\)$') # Process AMRs one by one for sent_idx, gold_amr",
"The parsing algorithm is transition-based combined with pointers for long distance arcs. Actions",
"the named entity sub-sequences one by one from the current surface token (segments).",
"# token node_by_token[token_str].update([node]) return node_by_token def is_most_common(node_counts, node, rank=0): return ( ( #",
"data statistics['sentence_tokens'].append(oracle_builder.tokens) # do not write CLOSE action at the end; # CLOSE",
"not nodes1 or not nodes2: return None # convert to single node aligned",
"there are edges that have not been built with this node \"\"\" machine",
"args.out_sentences, stats['sentence_tokens'], separator='\\t' ) # State machine stats for this sentence if args.out_rule_stats:",
"checking the target nodes in the subgraph # gold_nodeids = self.nodeid_to_gold_nodeid[node_id] # gold_nodeids",
"read_propbank(args.in_propbank_args) # read/write multi-task (labeled shift) action # TODO: Add conditional if here",
"new token return None tok_id = machine.tok_cursor tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) #",
"amr in gold_amrs: # hash of sentence skey = \" \".join(amr.tokens) # count",
"in the aligned subgraph altogether. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id",
"the aligned subgraph altogether. \"\"\" machine = self.machine gold_amr = self.gold_amr tok_id =",
"== ':name' and gold_amr.nodes[t] == 'name': is_named = True if r in [':polarity',",
"Restrict to top-k words allowed_words = dict(list(sorted( word_count.items(), key=lambda x: x[1]) )[-max_symbols:]) if",
"to a single node, or multiple nodes? (figure out) 2) the aligned node",
"!= self.machine.tokseq_len - 1 : action = 'REDUCE' else: action = 'SHIFT' if",
"heuristics for generating linearized action sequences for AMR graphs in a rule based",
"ids natural positive index # setting a token id to -1 will break",
"tokens are mapped to same node or overlap if cur_alignment == nxt_alignment: return",
"tok_alignment = gold_amr.alignmentsToken2Node(tok_id + 1) # check if alignment empty (or singleton) if",
"#for act_id, act_node_id in enumerate(machine.actions_to_nodes): for act_id, act_node_id in reversed(list(enumerate(machine.actions_to_nodes))): if act_node_id is",
"singleton) if len(tok_alignment) <= 1: return None # check if there is any",
"parser.parse_args() return args def yellow_font(string): return \"\\033[93m%s\\033[0m\" % string entities_with_preds = [] def",
"cleaning process # an example is in training data, when the sentence is",
"is more probable than rank + 1 len(node_counts) > rank + 1 and",
"= gold_amr.findSubGraph(nodes2).root else: node2 = nodes2[0] # find edges for s, r, t",
"node and node_counts.most_common(rank + 1)[-1][1] > node_counts.most_common(rank + 2)[-1][1] ) ) def sanity_check_amr(gold_amrs):"
] |
[
"'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError( Mock(), Mock(), Mock(), Mock(),",
"CollectorTestCase from test import get_collector_config from test import unittest from urllib2 import HTTPError",
"2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12 }, )",
"'hacheck.outbound_request_queue_size': 12 }, ) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect =",
"mock import Mock from mock import patch from test import CollectorTestCase from test",
"publish_mock): urlopen_mock.side_effect = HTTPError( Mock(), Mock(), Mock(), Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector,",
"import get_collector_config from test import unittest from urllib2 import HTTPError from diamond.collector import",
"}, ) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError( Mock(),",
"Mock from mock import patch from test import CollectorTestCase from test import get_collector_config",
"urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics') self.collector.collect() self.assertPublishedMany(publish_mock, {}) ################################################################################ if __name__ == \"__main__\":",
"# coding=utf-8 ################################################################################ from mock import Mock from mock import patch from test",
"{}) self.collector = HacheckCollector(config, None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value",
"None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect() self.assertPublishedMany(",
"Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value",
"import patch from test import CollectorTestCase from test import get_collector_config from test import",
"@patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics') self.collector.collect() self.assertPublishedMany(publish_mock, {})",
"@patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics') self.collector.collect() self.assertPublishedMany(publish_mock, {}) ################################################################################ if",
"= get_collector_config('HacheckCollector', {}) self.collector = HacheckCollector(config, None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock,",
"{ 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12",
"get_collector_config from test import unittest from urllib2 import HTTPError from diamond.collector import Collector",
"@patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError( Mock(), Mock(), Mock(), Mock(), Mock())",
"get_collector_config('HacheckCollector', {}) self.collector = HacheckCollector(config, None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock, publish_mock):",
"unittest from urllib2 import HTTPError from diamond.collector import Collector from hacheck import HacheckCollector",
"self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713,",
"from urllib2 import HTTPError from diamond.collector import Collector from hacheck import HacheckCollector ################################################################################",
"import Collector from hacheck import HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase): def setUp(self): config =",
"patch from test import CollectorTestCase from test import get_collector_config from test import unittest",
"@patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError( Mock(), Mock(), Mock(),",
"from test import CollectorTestCase from test import get_collector_config from test import unittest from",
"@patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations':",
"import Mock from mock import patch from test import CollectorTestCase from test import",
"from hacheck import HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HacheckCollector', {})",
"'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12 }, ) @patch.object(Collector,",
"2713, 'hacheck.outbound_request_queue_size': 12 }, ) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect",
"from diamond.collector import Collector from hacheck import HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase): def setUp(self):",
"28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12 }, ) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def",
"HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HacheckCollector', {}) self.collector = HacheckCollector(config,",
"from mock import patch from test import CollectorTestCase from test import get_collector_config from",
"'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12 }, ) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self,",
"urllib2 import HTTPError from diamond.collector import Collector from hacheck import HacheckCollector ################################################################################ class",
"urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713,",
"{}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics') self.collector.collect() self.assertPublishedMany(publish_mock,",
"Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value =",
"test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets':",
"Mock(), Mock(), Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock,",
"25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12 }, ) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock,",
"hacheck import HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HacheckCollector', {}) self.collector",
"Mock(), Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock):",
"self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747,",
"self.collector.collect() self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses':",
"self.collector = HacheckCollector(config, None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value =",
"test import unittest from urllib2 import HTTPError from diamond.collector import Collector from hacheck",
"from test import unittest from urllib2 import HTTPError from diamond.collector import Collector from",
"'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12 }, ) @patch.object(Collector, 'publish') @patch('urllib2.urlopen')",
"@patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock,",
"diamond.collector import Collector from hacheck import HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase): def setUp(self): config",
"HTTPError from diamond.collector import Collector from hacheck import HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase): def",
"import HTTPError from diamond.collector import Collector from hacheck import HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase):",
"HTTPError( Mock(), Mock(), Mock(), Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def",
"def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError( Mock(), Mock(), Mock(), Mock(), Mock()) self.collector.collect()",
"TestHacheckCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HacheckCollector', {}) self.collector = HacheckCollector(config, None) @patch.object(Collector, 'publish')",
"def test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations': 2692,",
"class TestHacheckCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HacheckCollector', {}) self.collector = HacheckCollector(config, None) @patch.object(Collector,",
"2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12 }, ) @patch.object(Collector, 'publish')",
"<reponame>rohangulati/fullerite #!/usr/bin/python # coding=utf-8 ################################################################################ from mock import Mock from mock import patch",
"################################################################################ class TestHacheckCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HacheckCollector', {}) self.collector = HacheckCollector(config, None)",
"################################################################################ from mock import Mock from mock import patch from test import CollectorTestCase",
"'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12 }, ) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock):",
"HacheckCollector(config, None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect()",
"test import CollectorTestCase from test import get_collector_config from test import unittest from urllib2",
") @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError( Mock(), Mock(),",
"config = get_collector_config('HacheckCollector', {}) self.collector = HacheckCollector(config, None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self,",
"setUp(self): config = get_collector_config('HacheckCollector', {}) self.collector = HacheckCollector(config, None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def",
"publish_mock): urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets':",
"import HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HacheckCollector', {}) self.collector =",
"urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460,",
"publish_mock, { 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size':",
"'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics') self.collector.collect() self.assertPublishedMany(publish_mock, {}) ################################################################################",
"self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics') self.collector.collect()",
"test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics') self.collector.collect() self.assertPublishedMany(publish_mock, {}) ################################################################################ if __name__ ==",
"test import get_collector_config from test import unittest from urllib2 import HTTPError from diamond.collector",
"#!/usr/bin/python # coding=utf-8 ################################################################################ from mock import Mock from mock import patch from",
"urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError( Mock(), Mock(), Mock(), Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {})",
"from mock import Mock from mock import patch from test import CollectorTestCase from",
"= HacheckCollector(config, None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('metrics')",
"def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics') self.collector.collect() self.assertPublishedMany(publish_mock, {}) ################################################################################ if __name__",
"from test import get_collector_config from test import unittest from urllib2 import HTTPError from",
"coding=utf-8 ################################################################################ from mock import Mock from mock import patch from test import",
"test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError( Mock(), Mock(), Mock(), Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock,",
"12 }, ) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_http_error(self, urlopen_mock, publish_mock): urlopen_mock.side_effect = HTTPError(",
"import CollectorTestCase from test import get_collector_config from test import unittest from urllib2 import",
"def setUp(self): config = get_collector_config('HacheckCollector', {}) self.collector = HacheckCollector(config, None) @patch.object(Collector, 'publish') @patch('urllib2.urlopen')",
"mock import patch from test import CollectorTestCase from test import get_collector_config from test",
"Mock(), Mock(), Mock(), Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self,",
"Collector from hacheck import HacheckCollector ################################################################################ class TestHacheckCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HacheckCollector',",
"publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics') self.collector.collect() self.assertPublishedMany(publish_mock, {}) ################################################################################ if __name__ == \"__main__\": unittest.main()",
"'publish') @patch('urllib2.urlopen') def test_works_with_real_data(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock, {",
"urlopen_mock.side_effect = HTTPError( Mock(), Mock(), Mock(), Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish')",
"self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen') def test_graceful_failure_on_json_error(self, urlopen_mock, publish_mock): urlopen_mock.return_value = self.getFixture('bad_metrics')",
"import unittest from urllib2 import HTTPError from diamond.collector import Collector from hacheck import",
"'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits': 25747, 'hacheck.cache.misses': 2713, 'hacheck.outbound_request_queue_size': 12 },",
"= self.getFixture('metrics') self.collector.collect() self.assertPublishedMany( publish_mock, { 'hacheck.cache.expirations': 2692, 'hacheck.cache.sets': 2713, 'hacheck.cache.gets': 28460, 'hacheck.cache.hits':",
"= HTTPError( Mock(), Mock(), Mock(), Mock(), Mock()) self.collector.collect() self.assertPublishedMany(publish_mock, {}) @patch.object(Collector, 'publish') @patch('urllib2.urlopen')"
] |
[
"'weights.pth') if os.path.isfile(model_path): print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer =",
"= 'train', **kwargs): assert mode == 'train' # Single epoch metric_context = MetricContext()",
"range(30): print('Starting epoch %s' % (i + 1)) process() def default_args(): return dict()",
"__init__(self, deconv_cell_size, transform = None): self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform",
"= list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform self.deconv_cell_size = deconv_cell_size def __len__(self): return len(self.images) def",
"self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32),",
"HouseDataset(Dataset): def __init__(self, deconv_cell_size, transform = None): self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images =",
"metric_context) def create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size) def _initialize(self): model = Model(3, 6).to(self.main_device) model_path",
"1 print('Epoch done with loss=%s' % (total_loss / total_updates)) return (1, (1, 1),",
"deconv_cell_size, transform = None): self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform =",
"= self.main_device) (r_depth, r_segmentation, _), _ = self.model.forward_deconv(((image, zeros1), None), None, None) (_,",
"import os import torch import numpy as np from torch.utils.data import Dataset,DataLoader from",
"== 'train' # Single epoch metric_context = MetricContext() dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4)",
"enumerate(dataloader): loss = self.optimize(*item) print('loss is %s' % loss) total_loss += loss total_updates",
"depth = self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) depth",
"r_goal_segmentation), _ = self.model.forward_deconv(((zeros2, image), None,), None, None) loss = F.mse_loss(r_depth, depth) +",
"/ total_updates)) return (1, (1, 1), metric_context) def create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size) def",
"if os.path.isfile(model_path): print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters())",
"deep_rl.configuration import configuration from environments.gym_house.goal import GoalImageCache import os import torch import numpy",
"compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) ret = (image,",
"def save(self, path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving to %s' % os.path.join(path, 'weights.pth'))",
"= 1) class SupervisedTrained(AbstractTrainer): def __init__(self, name, **kwargs): super().__init__(dict(), dict()) self.name = name",
"self.images[index] image = self.image_cache.read_image(image) depth = self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32),",
"0 for i, item in enumerate(dataloader): loss = self.optimize(*item) print('loss is %s' %",
"dict()) self.name = name self.batch_size = 32 self.main_device = torch.device('cuda') def optimize(self, image,",
"32 self.main_device = torch.device('cuda') def optimize(self, image, depth, segmentation): image = image.to(self.main_device) depth",
"in enumerate(dataloader): loss = self.optimize(*item) print('loss is %s' % loss) total_loss += loss",
"run(self, process, **kwargs): self.model = self._initialize() for i in range(30): print('Starting epoch %s'",
"= self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) depth =",
"os import torch import numpy as np from torch.utils.data import Dataset,DataLoader from models",
"self.model = self._initialize() for i in range(30): print('Starting epoch %s' % (i +",
"metric_context = MetricContext() dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss = 0 total_updates =",
"1), metric_context) def create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size) def _initialize(self): model = Model(3, 6).to(self.main_device)",
"None) loss = F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation, segmentation) loss =",
"class HouseDataset(Dataset): def __init__(self, deconv_cell_size, transform = None): self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images",
"/ 255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42,",
"import torch import numpy as np from torch.utils.data import Dataset,DataLoader from models import",
"os.path.join(path, 'weights.pth')) def process(self, mode = 'train', **kwargs): assert mode == 'train' #",
"F from experiments.ai2_auxiliary.trainer import compute_auxiliary_target class HouseDataset(Dataset): def __init__(self, deconv_cell_size, transform = None):",
"name, **kwargs): super().__init__(dict(), dict()) self.name = name self.batch_size = 32 self.main_device = torch.device('cuda')",
"Model(3, 6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path): print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path))",
"deep_rl import register_trainer from deep_rl.core import AbstractTrainer from deep_rl.core import MetricContext from deep_rl.configuration",
"= self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters()) return model def run(self, process, **kwargs): self.model =",
"transform self.deconv_cell_size = deconv_cell_size def __len__(self): return len(self.images) def __getitem__(self, index): image, depth,",
"= Adam(model.parameters()) return model def run(self, process, **kwargs): self.model = self._initialize() for i",
"total_updates += 1 print('Epoch done with loss=%s' % (total_loss / total_updates)) return (1,",
"= image.to(self.main_device) depth = depth.to(self.main_device) segmentation = segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0], 1, 3,174,174),",
"segmentation = self.images[index] image = self.image_cache.read_image(image) depth = self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation) image",
"image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation",
"mode = 'train', **kwargs): assert mode == 'train' # Single epoch metric_context =",
"total_updates = 0 for i, item in enumerate(dataloader): loss = self.optimize(*item) print('loss is",
"**kwargs): assert mode == 'train' # Single epoch metric_context = MetricContext() dataloader =",
"return (1, (1, 1), metric_context) def create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size) def _initialize(self): model",
"segmentation) if self.transform: ret = self.transform(ret) return ret @register_trainer(save = True, saving_period =",
"segmentation) loss = loss / 3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def save(self,",
"segmentation): image = image.to(self.main_device) depth = depth.to(self.main_device) segmentation = segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0],",
"print('loss is %s' % loss) total_loss += loss total_updates += 1 print('Epoch done",
"from experiments.ai2_auxiliary.trainer import compute_auxiliary_target class HouseDataset(Dataset): def __init__(self, deconv_cell_size, transform = None): self.image_cache",
"torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0),",
"numpy as np from torch.utils.data import Dataset,DataLoader from models import AuxiliaryBigGoalHouseModel as Model",
"device = self.main_device) (r_depth, r_segmentation, _), _ = self.model.forward_deconv(((image, zeros1), None), None, None)",
"loss = loss / 3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def save(self, path):",
"= torch.float32, device = self.main_device) zeros2 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32,",
"None,), None, None) loss = F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation, segmentation)",
"configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform self.deconv_cell_size = deconv_cell_size def __len__(self): return",
"/ 255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) /",
"DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss = 0 total_updates = 0 for i, item in",
"def __init__(self, name, **kwargs): super().__init__(dict(), dict()) self.name = name self.batch_size = 32 self.main_device",
"self.optimize(*item) print('loss is %s' % loss) total_loss += loss total_updates += 1 print('Epoch",
"GoalImageCache import os import torch import numpy as np from torch.utils.data import Dataset,DataLoader",
"loss) total_loss += loss total_updates += 1 print('Epoch done with loss=%s' % (total_loss",
"0 total_updates = 0 for i, item in enumerate(dataloader): loss = self.optimize(*item) print('loss",
"% loss) total_loss += loss total_updates += 1 print('Epoch done with loss=%s' %",
"torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving to %s' % os.path.join(path, 'weights.pth')) def process(self, mode =",
"os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path): print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer",
"self.main_device = torch.device('cuda') def optimize(self, image, depth, segmentation): image = image.to(self.main_device) depth =",
"= torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device) zeros2 = torch.rand((image.size()[0],",
"compute_auxiliary_target class HouseDataset(Dataset): def __init__(self, deconv_cell_size, transform = None): self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path'))",
"class SupervisedTrained(AbstractTrainer): def __init__(self, name, **kwargs): super().__init__(dict(), dict()) self.name = name self.batch_size =",
"+= 1 print('Epoch done with loss=%s' % (total_loss / total_updates)) return (1, (1,",
"_ = self.model.forward_deconv(((image, zeros1), None), None, None) (_, _, r_goal_segmentation), _ = self.model.forward_deconv(((zeros2,",
"import configuration from environments.gym_house.goal import GoalImageCache import os import torch import numpy as",
"def __getitem__(self, index): image, depth, segmentation = self.images[index] image = self.image_cache.read_image(image) depth =",
"total_updates)) return (1, (1, 1), metric_context) def create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size) def _initialize(self):",
"_), _ = self.model.forward_deconv(((image, zeros1), None), None, None) (_, _, r_goal_segmentation), _ =",
"(_, _, r_goal_segmentation), _ = self.model.forward_deconv(((zeros2, image), None,), None, None) loss = F.mse_loss(r_depth,",
"image.to(self.main_device) depth = depth.to(self.main_device) segmentation = segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0], 1, 3,174,174), dtype",
"42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) ret = (image, depth, segmentation) if",
"torch.nn.functional as F from experiments.ai2_auxiliary.trainer import compute_auxiliary_target class HouseDataset(Dataset): def __init__(self, deconv_cell_size, transform",
"= torch.float32, device = self.main_device) (r_depth, r_segmentation, _), _ = self.model.forward_deconv(((image, zeros1), None),",
"self.main_device) (r_depth, r_segmentation, _), _ = self.model.forward_deconv(((image, zeros1), None), None, None) (_, _,",
"self.transform: ret = self.transform(ret) return ret @register_trainer(save = True, saving_period = 1) class",
"loss.item() def save(self, path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving to %s' % os.path.join(path,",
"saving_period = 1) class SupervisedTrained(AbstractTrainer): def __init__(self, name, **kwargs): super().__init__(dict(), dict()) self.name =",
"r_segmentation, _), _ = self.model.forward_deconv(((image, zeros1), None), None, None) (_, _, r_goal_segmentation), _",
"depth, segmentation): image = image.to(self.main_device) depth = depth.to(self.main_device) segmentation = segmentation.to(self.main_device) zeros1 =",
"def _initialize(self): model = Model(3, 6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path): print('Loading",
"+ F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation, segmentation) loss = loss / 3.0 self.optimizer.zero_grad() loss.backward()",
"def run(self, process, **kwargs): self.model = self._initialize() for i in range(30): print('Starting epoch",
"zeros1), None), None, None) (_, _, r_goal_segmentation), _ = self.model.forward_deconv(((zeros2, image), None,), None,",
"index): image, depth, segmentation = self.images[index] image = self.image_cache.read_image(image) depth = self.image_cache.read_image(depth) segmentation",
"= torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation =",
"return loss.item() def save(self, path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving to %s' %",
"os.path.join(path, 'weights.pth')) print('Saving to %s' % os.path.join(path, 'weights.pth')) def process(self, mode = 'train',",
"self.main_device) zeros2 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device) (r_depth,",
"F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation, segmentation) loss = loss / 3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step()",
"(1, (1, 1), metric_context) def create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size) def _initialize(self): model =",
"# Single epoch metric_context = MetricContext() dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss =",
"super().__init__(dict(), dict()) self.name = name self.batch_size = 32 self.main_device = torch.device('cuda') def optimize(self,",
"= self.image_cache.read_image(image) depth = self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) /",
"models import AuxiliaryBigGoalHouseModel as Model from torch.optim import Adam import torch.nn.functional as F",
"= self.main_device) zeros2 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device)",
"epoch metric_context = MetricContext() dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss = 0 total_updates",
"42)).squeeze(0) ret = (image, depth, segmentation) if self.transform: ret = self.transform(ret) return ret",
"'train', **kwargs): assert mode == 'train' # Single epoch metric_context = MetricContext() dataloader",
"from deep_rl.configuration import configuration from environments.gym_house.goal import GoalImageCache import os import torch import",
"self.batch_size = 32 self.main_device = torch.device('cuda') def optimize(self, image, depth, segmentation): image =",
"def __len__(self): return len(self.images) def __getitem__(self, index): image, depth, segmentation = self.images[index] image",
"= torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device) (r_depth, r_segmentation, _),",
"with loss=%s' % (total_loss / total_updates)) return (1, (1, 1), metric_context) def create_dataset(self,",
"= torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) depth =",
"= compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) ret =",
"self.deconv_cell_size = deconv_cell_size def __len__(self): return len(self.images) def __getitem__(self, index): image, depth, segmentation",
"'weights.pth')) def process(self, mode = 'train', **kwargs): assert mode == 'train' # Single",
"**kwargs): self.model = self._initialize() for i in range(30): print('Starting epoch %s' % (i",
"6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path): print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset",
"= segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device)",
"return len(self.images) def __getitem__(self, index): image, depth, segmentation = self.images[index] image = self.image_cache.read_image(image)",
"from torch.utils.data import Dataset,DataLoader from models import AuxiliaryBigGoalHouseModel as Model from torch.optim import",
"(42, 42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) ret = (image, depth, segmentation)",
"self.deconv_cell_size, (42, 42)).squeeze(0) ret = (image, depth, segmentation) if self.transform: ret = self.transform(ret)",
"None), None, None) (_, _, r_goal_segmentation), _ = self.model.forward_deconv(((zeros2, image), None,), None, None)",
"torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device) (r_depth, r_segmentation, _), _",
"loss = self.optimize(*item) print('loss is %s' % loss) total_loss += loss total_updates +=",
"3,174,174), dtype = torch.float32, device = self.main_device) (r_depth, r_segmentation, _), _ = self.model.forward_deconv(((image,",
"segmentation = segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device =",
"'train' # Single epoch metric_context = MetricContext() dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss",
"zeros2 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device) (r_depth, r_segmentation,",
"= os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path): print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size)",
"+ F.mse_loss(r_goal_segmentation, segmentation) loss = loss / 3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item()",
"__len__(self): return len(self.images) def __getitem__(self, index): image, depth, segmentation = self.images[index] image =",
"if self.transform: ret = self.transform(ret) return ret @register_trainer(save = True, saving_period = 1)",
"torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32),",
"_initialize(self): model = Model(3, 6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path): print('Loading %s'",
"def process(self, mode = 'train', **kwargs): assert mode == 'train' # Single epoch",
"return HouseDataset(deconv_cell_size) def _initialize(self): model = Model(3, 6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if",
"path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving to %s' % os.path.join(path, 'weights.pth')) def process(self,",
"configuration from environments.gym_house.goal import GoalImageCache import os import torch import numpy as np",
"self.transform = transform self.deconv_cell_size = deconv_cell_size def __len__(self): return len(self.images) def __getitem__(self, index):",
"'weights.pth')) print('Saving to %s' % os.path.join(path, 'weights.pth')) def process(self, mode = 'train', **kwargs):",
"batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss = 0 total_updates = 0 for i, item in enumerate(dataloader):",
"mode == 'train' # Single epoch metric_context = MetricContext() dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True,",
"register_trainer from deep_rl.core import AbstractTrainer from deep_rl.core import MetricContext from deep_rl.configuration import configuration",
"AuxiliaryBigGoalHouseModel as Model from torch.optim import Adam import torch.nn.functional as F from experiments.ai2_auxiliary.trainer",
"/ 255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42,",
"Model from torch.optim import Adam import torch.nn.functional as F from experiments.ai2_auxiliary.trainer import compute_auxiliary_target",
"image, depth, segmentation = self.images[index] image = self.image_cache.read_image(image) depth = self.image_cache.read_image(depth) segmentation =",
"from deep_rl.core import AbstractTrainer from deep_rl.core import MetricContext from deep_rl.configuration import configuration from",
"torch.device('cuda') def optimize(self, image, depth, segmentation): image = image.to(self.main_device) depth = depth.to(self.main_device) segmentation",
"**kwargs): super().__init__(dict(), dict()) self.name = name self.batch_size = 32 self.main_device = torch.device('cuda') def",
"ret @register_trainer(save = True, saving_period = 1) class SupervisedTrained(AbstractTrainer): def __init__(self, name, **kwargs):",
"F.mse_loss(r_goal_segmentation, segmentation) loss = loss / 3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def",
"= deconv_cell_size def __len__(self): return len(self.images) def __getitem__(self, index): image, depth, segmentation =",
"in range(30): print('Starting epoch %s' % (i + 1)) process() def default_args(): return",
"import GoalImageCache import os import torch import numpy as np from torch.utils.data import",
"optimize(self, image, depth, segmentation): image = image.to(self.main_device) depth = depth.to(self.main_device) segmentation = segmentation.to(self.main_device)",
"(1, 1), metric_context) def create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size) def _initialize(self): model = Model(3,",
"torch.float32, device = self.main_device) zeros2 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device",
"loss / 3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def save(self, path): super().save(path) torch.save(self.model.state_dict(),",
"depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation",
"from environments.gym_house.goal import GoalImageCache import os import torch import numpy as np from",
"AbstractTrainer from deep_rl.core import MetricContext from deep_rl.configuration import configuration from environments.gym_house.goal import GoalImageCache",
"= self.model.forward_deconv(((zeros2, image), None,), None, None) loss = F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation, segmentation)",
"__init__(self, name, **kwargs): super().__init__(dict(), dict()) self.name = name self.batch_size = 32 self.main_device =",
"import torch.nn.functional as F from experiments.ai2_auxiliary.trainer import compute_auxiliary_target class HouseDataset(Dataset): def __init__(self, deconv_cell_size,",
"import compute_auxiliary_target class HouseDataset(Dataset): def __init__(self, deconv_cell_size, transform = None): self.image_cache = GoalImageCache((174,174),",
"self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters()) return model def run(self, process, **kwargs): self.model = self._initialize()",
"None, None) (_, _, r_goal_segmentation), _ = self.model.forward_deconv(((zeros2, image), None,), None, None) loss",
"self.model.forward_deconv(((image, zeros1), None), None, None) (_, _, r_goal_segmentation), _ = self.model.forward_deconv(((zeros2, image), None,),",
"= DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss = 0 total_updates = 0 for i, item",
"device = self.main_device) zeros2 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device =",
"= name self.batch_size = 32 self.main_device = torch.device('cuda') def optimize(self, image, depth, segmentation):",
"torch.float32, device = self.main_device) (r_depth, r_segmentation, _), _ = self.model.forward_deconv(((image, zeros1), None), None,",
"import Adam import torch.nn.functional as F from experiments.ai2_auxiliary.trainer import compute_auxiliary_target class HouseDataset(Dataset): def",
"= (image, depth, segmentation) if self.transform: ret = self.transform(ret) return ret @register_trainer(save =",
"= 32 self.main_device = torch.device('cuda') def optimize(self, image, depth, segmentation): image = image.to(self.main_device)",
"import numpy as np from torch.utils.data import Dataset,DataLoader from models import AuxiliaryBigGoalHouseModel as",
"= loss / 3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def save(self, path): super().save(path)",
"from torch.optim import Adam import torch.nn.functional as F from experiments.ai2_auxiliary.trainer import compute_auxiliary_target class",
"loss total_updates += 1 print('Epoch done with loss=%s' % (total_loss / total_updates)) return",
"%s' % loss) total_loss += loss total_updates += 1 print('Epoch done with loss=%s'",
"self.transform(ret) return ret @register_trainer(save = True, saving_period = 1) class SupervisedTrained(AbstractTrainer): def __init__(self,",
"torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0),",
"model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters()) return model def run(self, process, **kwargs):",
"% os.path.join(path, 'weights.pth')) def process(self, mode = 'train', **kwargs): assert mode == 'train'",
"_, r_goal_segmentation), _ = self.model.forward_deconv(((zeros2, image), None,), None, None) loss = F.mse_loss(r_depth, depth)",
"image = image.to(self.main_device) depth = depth.to(self.main_device) segmentation = segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0], 1,",
"assert mode == 'train' # Single epoch metric_context = MetricContext() dataloader = DataLoader(self.dataset,",
"list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform self.deconv_cell_size = deconv_cell_size def __len__(self): return len(self.images) def __getitem__(self,",
"= Model(3, 6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path): print('Loading %s' % model_path)",
"/ 3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def save(self, path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path,",
"loss=%s' % (total_loss / total_updates)) return (1, (1, 1), metric_context) def create_dataset(self, deconv_cell_size):",
"import MetricContext from deep_rl.configuration import configuration from environments.gym_house.goal import GoalImageCache import os import",
"[2,0,1]) / 255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size,",
"environments.gym_house.goal import GoalImageCache import os import torch import numpy as np from torch.utils.data",
"as F from experiments.ai2_auxiliary.trainer import compute_auxiliary_target class HouseDataset(Dataset): def __init__(self, deconv_cell_size, transform =",
"[2,0,1]) / 255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size,",
"1, 3,174,174), dtype = torch.float32, device = self.main_device) (r_depth, r_segmentation, _), _ =",
"SupervisedTrained(AbstractTrainer): def __init__(self, name, **kwargs): super().__init__(dict(), dict()) self.name = name self.batch_size = 32",
"= transform self.deconv_cell_size = deconv_cell_size def __len__(self): return len(self.images) def __getitem__(self, index): image,",
"print('Saving to %s' % os.path.join(path, 'weights.pth')) def process(self, mode = 'train', **kwargs): assert",
"model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path): print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset =",
"image), None,), None, None) loss = F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation,",
"is %s' % loss) total_loss += loss total_updates += 1 print('Epoch done with",
"= 0 total_updates = 0 for i, item in enumerate(dataloader): loss = self.optimize(*item)",
"% model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters()) return model def run(self,",
"self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0)",
"None) (_, _, r_goal_segmentation), _ = self.model.forward_deconv(((zeros2, image), None,), None, None) loss =",
"= self.model.forward_deconv(((image, zeros1), None), None, None) (_, _, r_goal_segmentation), _ = self.model.forward_deconv(((zeros2, image),",
"= self._initialize() for i in range(30): print('Starting epoch %s' % (i + 1))",
"from deep_rl.core import MetricContext from deep_rl.configuration import configuration from environments.gym_house.goal import GoalImageCache import",
"% (total_loss / total_updates)) return (1, (1, 1), metric_context) def create_dataset(self, deconv_cell_size): return",
"from deep_rl import register_trainer from deep_rl.core import AbstractTrainer from deep_rl.core import MetricContext from",
"model = Model(3, 6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path): print('Loading %s' %",
"3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def save(self, path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth'))",
"= depth.to(self.main_device) segmentation = segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32,",
"%s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters()) return model def",
"dtype = torch.float32, device = self.main_device) (r_depth, r_segmentation, _), _ = self.model.forward_deconv(((image, zeros1),",
"self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform self.deconv_cell_size = deconv_cell_size",
"done with loss=%s' % (total_loss / total_updates)) return (1, (1, 1), metric_context) def",
"process(self, mode = 'train', **kwargs): assert mode == 'train' # Single epoch metric_context",
"from models import AuxiliaryBigGoalHouseModel as Model from torch.optim import Adam import torch.nn.functional as",
"(total_loss / total_updates)) return (1, (1, 1), metric_context) def create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size)",
"save(self, path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving to %s' % os.path.join(path, 'weights.pth')) def",
"self.deconv_cell_size, (42, 42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) ret = (image, depth,",
"create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size) def _initialize(self): model = Model(3, 6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised',",
"= torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation =",
"as Model from torch.optim import Adam import torch.nn.functional as F from experiments.ai2_auxiliary.trainer import",
"= compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) ret = (image, depth, segmentation) if self.transform: ret",
"os.path.isfile(model_path): print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters()) return",
"image, depth, segmentation): image = image.to(self.main_device) depth = depth.to(self.main_device) segmentation = segmentation.to(self.main_device) zeros1",
"self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def save(self, path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving",
"def create_dataset(self, deconv_cell_size): return HouseDataset(deconv_cell_size) def _initialize(self): model = Model(3, 6).to(self.main_device) model_path =",
"super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving to %s' % os.path.join(path, 'weights.pth')) def process(self, mode",
"3,174,174), dtype = torch.float32, device = self.main_device) zeros2 = torch.rand((image.size()[0], 1, 3,174,174), dtype",
"True, saving_period = 1) class SupervisedTrained(AbstractTrainer): def __init__(self, name, **kwargs): super().__init__(dict(), dict()) self.name",
"self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters()) return model def run(self, process, **kwargs): self.model",
"__getitem__(self, index): image, depth, segmentation = self.images[index] image = self.image_cache.read_image(image) depth = self.image_cache.read_image(depth)",
"self.optimizer.step() return loss.item() def save(self, path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving to %s'",
"255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0)",
"MetricContext from deep_rl.configuration import configuration from environments.gym_house.goal import GoalImageCache import os import torch",
"name self.batch_size = 32 self.main_device = torch.device('cuda') def optimize(self, image, depth, segmentation): image",
"def optimize(self, image, depth, segmentation): image = image.to(self.main_device) depth = depth.to(self.main_device) segmentation =",
"Single epoch metric_context = MetricContext() dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss = 0",
"segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device) zeros2",
"segmentation) + F.mse_loss(r_goal_segmentation, segmentation) loss = loss / 3.0 self.optimizer.zero_grad() loss.backward() self.optimizer.step() return",
"HouseDataset(deconv_cell_size) def _initialize(self): model = Model(3, 6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth') if os.path.isfile(model_path):",
"torch.optim import Adam import torch.nn.functional as F from experiments.ai2_auxiliary.trainer import compute_auxiliary_target class HouseDataset(Dataset):",
"255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0)",
"255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0)",
"import register_trainer from deep_rl.core import AbstractTrainer from deep_rl.core import MetricContext from deep_rl.configuration import",
"for i, item in enumerate(dataloader): loss = self.optimize(*item) print('loss is %s' % loss)",
"= self.transform(ret) return ret @register_trainer(save = True, saving_period = 1) class SupervisedTrained(AbstractTrainer): def",
"model def run(self, process, **kwargs): self.model = self._initialize() for i in range(30): print('Starting",
"as np from torch.utils.data import Dataset,DataLoader from models import AuxiliaryBigGoalHouseModel as Model from",
"= F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation, segmentation) loss = loss /",
"= self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) /",
"deep_rl.core import MetricContext from deep_rl.configuration import configuration from environments.gym_house.goal import GoalImageCache import os",
"import AbstractTrainer from deep_rl.core import MetricContext from deep_rl.configuration import configuration from environments.gym_house.goal import",
"loss.backward() self.optimizer.step() return loss.item() def save(self, path): super().save(path) torch.save(self.model.state_dict(), os.path.join(path, 'weights.pth')) print('Saving to",
"[2,0,1]) / 255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1])",
"print('Loading %s' % model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters()) return model",
"= torch.device('cuda') def optimize(self, image, depth, segmentation): image = image.to(self.main_device) depth = depth.to(self.main_device)",
"1, 3,174,174), dtype = torch.float32, device = self.main_device) zeros2 = torch.rand((image.size()[0], 1, 3,174,174),",
"zeros1 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device) zeros2 =",
"self.image_cache.read_image(image) depth = self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0)",
"compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) ret = (image, depth, segmentation) if self.transform: ret =",
"torch import numpy as np from torch.utils.data import Dataset,DataLoader from models import AuxiliaryBigGoalHouseModel",
"for i in range(30): print('Starting epoch %s' % (i + 1)) process() def",
"return model def run(self, process, **kwargs): self.model = self._initialize() for i in range(30):",
"= None): self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform self.deconv_cell_size",
"model_path) model.load_state_dict(torch.load(model_path)) self.dataset = self.create_dataset(model.deconv_cell_size) self.optimizer = Adam(model.parameters()) return model def run(self, process,",
"segmentation = self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) depth = torch.from_numpy(np.transpose(depth[:,:,:1].astype(np.float32), [2,0,1])",
"print('Epoch done with loss=%s' % (total_loss / total_updates)) return (1, (1, 1), metric_context)",
"total_loss += loss total_updates += 1 print('Epoch done with loss=%s' % (total_loss /",
"total_loss = 0 total_updates = 0 for i, item in enumerate(dataloader): loss =",
"= self.images[index] image = self.image_cache.read_image(image) depth = self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation) image =",
"depth, segmentation = self.images[index] image = self.image_cache.read_image(image) depth = self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation)",
"= self.optimize(*item) print('loss is %s' % loss) total_loss += loss total_updates += 1",
"segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) ret",
"depth) + F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation, segmentation) loss = loss / 3.0 self.optimizer.zero_grad()",
"torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device = self.main_device) zeros2 = torch.rand((image.size()[0], 1,",
"deconv_cell_size def __len__(self): return len(self.images) def __getitem__(self, index): image, depth, segmentation = self.images[index]",
"%s' % os.path.join(path, 'weights.pth')) def process(self, mode = 'train', **kwargs): assert mode ==",
"self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform self.deconv_cell_size = deconv_cell_size def __len__(self): return len(self.images)",
"len(self.images) def __getitem__(self, index): image, depth, segmentation = self.images[index] image = self.image_cache.read_image(image) depth",
"= 0 for i, item in enumerate(dataloader): loss = self.optimize(*item) print('loss is %s'",
"num_workers=4) total_loss = 0 total_updates = 0 for i, item in enumerate(dataloader): loss",
"ret = (image, depth, segmentation) if self.transform: ret = self.transform(ret) return ret @register_trainer(save",
"item in enumerate(dataloader): loss = self.optimize(*item) print('loss is %s' % loss) total_loss +=",
"None, None) loss = F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation, segmentation) loss",
"MetricContext() dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss = 0 total_updates = 0 for",
"GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform self.deconv_cell_size = deconv_cell_size def __len__(self):",
"@register_trainer(save = True, saving_period = 1) class SupervisedTrained(AbstractTrainer): def __init__(self, name, **kwargs): super().__init__(dict(),",
"Dataset,DataLoader from models import AuxiliaryBigGoalHouseModel as Model from torch.optim import Adam import torch.nn.functional",
"self.model.forward_deconv(((zeros2, image), None,), None, None) loss = F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation, segmentation) +",
"self._initialize() for i in range(30): print('Starting epoch %s' % (i + 1)) process()",
"= GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform self.deconv_cell_size = deconv_cell_size def",
"None): self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform self.deconv_cell_size =",
"return ret @register_trainer(save = True, saving_period = 1) class SupervisedTrained(AbstractTrainer): def __init__(self, name,",
"deconv_cell_size): return HouseDataset(deconv_cell_size) def _initialize(self): model = Model(3, 6).to(self.main_device) model_path = os.path.join(configuration.get('models_path'),'chouse-auxiliary4-supervised', 'weights.pth')",
"i in range(30): print('Starting epoch %s' % (i + 1)) process() def default_args():",
"F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation, segmentation) loss = loss / 3.0",
"deep_rl.core import AbstractTrainer from deep_rl.core import MetricContext from deep_rl.configuration import configuration from environments.gym_house.goal",
"+= loss total_updates += 1 print('Epoch done with loss=%s' % (total_loss / total_updates))",
"depth.to(self.main_device) segmentation = segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0], 1, 3,174,174), dtype = torch.float32, device",
"(image, depth, segmentation) if self.transform: ret = self.transform(ret) return ret @register_trainer(save = True,",
"loss = F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation, segmentation) + F.mse_loss(r_goal_segmentation, segmentation) loss = loss",
"process, **kwargs): self.model = self._initialize() for i in range(30): print('Starting epoch %s' %",
"(r_depth, r_segmentation, _), _ = self.model.forward_deconv(((image, zeros1), None), None, None) (_, _, r_goal_segmentation),",
"experiments.ai2_auxiliary.trainer import compute_auxiliary_target class HouseDataset(Dataset): def __init__(self, deconv_cell_size, transform = None): self.image_cache =",
"segmentation = torch.from_numpy(np.transpose(segmentation.astype(np.float32), [2,0,1]) / 255.0).unsqueeze(0) segmentation = compute_auxiliary_target(segmentation.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) depth",
"to %s' % os.path.join(path, 'weights.pth')) def process(self, mode = 'train', **kwargs): assert mode",
"ret = self.transform(ret) return ret @register_trainer(save = True, saving_period = 1) class SupervisedTrained(AbstractTrainer):",
"Adam(model.parameters()) return model def run(self, process, **kwargs): self.model = self._initialize() for i in",
"torch.utils.data import Dataset,DataLoader from models import AuxiliaryBigGoalHouseModel as Model from torch.optim import Adam",
"dtype = torch.float32, device = self.main_device) zeros2 = torch.rand((image.size()[0], 1, 3,174,174), dtype =",
"self.name = name self.batch_size = 32 self.main_device = torch.device('cuda') def optimize(self, image, depth,",
"image = self.image_cache.read_image(image) depth = self.image_cache.read_image(depth) segmentation = self.image_cache.read_image(segmentation) image = torch.from_numpy(np.transpose(image.astype(np.float32), [2,0,1])",
"dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss = 0 total_updates = 0 for i,",
"i, item in enumerate(dataloader): loss = self.optimize(*item) print('loss is %s' % loss) total_loss",
"= MetricContext() dataloader = DataLoader(self.dataset, batch_size=self.batch_size,shuffle=True, num_workers=4) total_loss = 0 total_updates = 0",
"(42, 42)).squeeze(0) ret = (image, depth, segmentation) if self.transform: ret = self.transform(ret) return",
"import AuxiliaryBigGoalHouseModel as Model from torch.optim import Adam import torch.nn.functional as F from",
"= True, saving_period = 1) class SupervisedTrained(AbstractTrainer): def __init__(self, name, **kwargs): super().__init__(dict(), dict())",
"import Dataset,DataLoader from models import AuxiliaryBigGoalHouseModel as Model from torch.optim import Adam import",
"depth, segmentation) if self.transform: ret = self.transform(ret) return ret @register_trainer(save = True, saving_period",
"transform = None): self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation'])) self.transform = transform",
"np from torch.utils.data import Dataset,DataLoader from models import AuxiliaryBigGoalHouseModel as Model from torch.optim",
"_ = self.model.forward_deconv(((zeros2, image), None,), None, None) loss = F.mse_loss(r_depth, depth) + F.mse_loss(r_segmentation,",
"depth = compute_auxiliary_target(depth.unsqueeze(0), self.deconv_cell_size, (42, 42)).squeeze(0) ret = (image, depth, segmentation) if self.transform:",
"self.optimizer = Adam(model.parameters()) return model def run(self, process, **kwargs): self.model = self._initialize() for",
"depth = depth.to(self.main_device) segmentation = segmentation.to(self.main_device) zeros1 = torch.rand((image.size()[0], 1, 3,174,174), dtype =",
"def __init__(self, deconv_cell_size, transform = None): self.image_cache = GoalImageCache((174,174), configuration.get('house3d.dataset_path')) self.images = list(self.image_cache.all_image_paths(['rgb','depth','segmentation']))",
"1) class SupervisedTrained(AbstractTrainer): def __init__(self, name, **kwargs): super().__init__(dict(), dict()) self.name = name self.batch_size",
"Adam import torch.nn.functional as F from experiments.ai2_auxiliary.trainer import compute_auxiliary_target class HouseDataset(Dataset): def __init__(self,"
] |
[
"self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False)",
"20, 1, 1, 2) self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair,",
"0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1)",
"QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41)) self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521,",
"self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget)",
"self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1, 2) self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\")",
"self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1, 2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\")",
"self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1, 2) self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck",
"= QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41)) self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820,",
"self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None))",
"self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget)",
"QPushButton, QSizePolicy, QSlider, QWidget) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\")",
"self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget)",
"self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1, 3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText)",
"u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen",
"sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1, 1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2)",
"QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck =",
"self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\")",
"self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow)",
"self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length,",
"= QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1, 1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget)",
"self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1, 3)",
"= QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766)) self.gridLayout =",
"= QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1, 1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget)",
"Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy =",
"QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication, QComboBox, QFrame, QGraphicsView, QGridLayout, QHBoxLayout, QLabel, QLayout,",
"MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy)",
"self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1, 2) self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\")",
"self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1, 2)",
"self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1, 2) self.lbl_outer_lines_opacity",
"self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1, 1) self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off,",
"retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\",",
"= QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1, 1) self.lbl_center_dot = QLabel(self.gridLayoutWidget)",
"= QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1, 1) self.lbl_inner_lines_length =",
"QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication,",
"self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1, 2) self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\")",
"sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\")",
"self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None))",
"0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1, 2) self.btn_inner_on =",
"None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None))",
"QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1,",
"self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100)",
"self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1, 3)",
"self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230,",
"= QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4)",
"None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res / Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\",",
"= QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1, 3) self.lbl_inner_lines",
"u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res / Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\",",
"self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center",
"16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow)",
"UI file 'main_window.ui' ## ## Created by: Qt User Interface Compiler version 6.2.2",
"QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform)",
"version 6.2.2 ## ## WARNING! All changes made in this file will be",
"u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\", None))",
"self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck)",
"self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1, 1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\")",
"self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1, 1) self.lbl_inner_lines_length",
"= QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity",
"-*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'main_window.ui'",
"self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck)",
"be lost when recompiling UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime,",
"None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\",",
"sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1, 2) self.btn_save_ch = QPushButton(self.centralwidget)",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10,",
"self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0)",
"self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10)",
"self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget)",
"1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1, 1) self.btn_dot_on",
"self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1, 1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13,",
"self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0))",
"QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1, 3) self.lbl_screen_stretch =",
"= QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken)",
"self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1, 1) self.lbl_center_dot_thck =",
"1, 1, 1) self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1)",
"self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1, 1) self.lbl_outline_thck =",
"16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow)",
"self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1, 1) self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12,",
"self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1, 1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth())",
"= QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck",
"1, 2) self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41)) self.lbl_link = QLabel(self.centralwidget)",
"849) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\")",
"1, 1) self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0,",
"self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1, 2) self.hlay_outline_thck =",
"self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1, 1) self.hlay_outline_opacity",
"self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1, 1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth())",
"self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1, 2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2)",
"self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5,",
"self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1, 1) self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True)",
"self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50))",
"41)) self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False)",
"self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1, 2) self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck =",
"self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1)",
"self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230,",
"self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20)",
"1) self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0))",
"Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None))",
"self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1, 1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 =",
"self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1, 2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\")",
"241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41))",
"self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity)",
"self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1, 2) self.hlay_ch_select",
"Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\",",
"sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\")",
"self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0))",
"self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1, 1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth())",
"10, 0, 1, 3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1,",
"23, 0, 1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4",
"= QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1,",
"self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1, 1) self.horizontalLayout = QHBoxLayout()",
"sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1, 1) self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck =",
"0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0)",
"Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\",",
"self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner",
"50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1, 2) self.lbl_outer_lines_opacity =",
"self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1, 1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity,",
"0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1, 2) self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800,",
"self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget)",
"self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1, 1) self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot,",
"QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication, QComboBox, QFrame, QGraphicsView, QGridLayout, QHBoxLayout, QLabel,",
"sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\")",
"self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1, 1) self.btn_dot_off =",
"self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50,",
"QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1, 1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\")",
"= QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215))",
"self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1, 1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color,",
"self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity)",
"self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1, 1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth())",
"self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1,",
"self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1, 2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24,",
"1, 1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1, 1)",
"self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\",",
"u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project Home</a>\", None)) self.btn_del_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Delete",
"self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1, 1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12,",
"= QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1,",
"QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont()",
"19, 1, 1, 2) self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth())",
"1, 1) self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1, 1)",
"0, 1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 =",
"self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer",
"None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None))",
"sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter)",
"self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1, 2) self.lbl_crosshair = QLabel(self.gridLayoutWidget)",
"None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\",",
"changes made in this file will be lost when recompiling UI file! ################################################################################",
"self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1, 1) self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget)",
"21, 0, 1, 1) self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth())",
"1) self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0))",
"QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1,",
"sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1, 3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\")",
"self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines",
"u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None))",
"sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1, 1) self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False)",
"sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\")",
"self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0))",
"self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1, 1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset,",
"self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1)",
"self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0))",
"16, 0, 1, 1) self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth())",
"2, 1, 1) self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1)",
"self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget)",
"Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot",
"self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\",",
"self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine)",
"self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0))",
"self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w =",
"self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1, 1) self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\")",
"self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1, 1) self.lbl_inner_lines_length_2 =",
"Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\",",
"self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41)) self.lbl_err_msg =",
"self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1, 2) self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select,",
"Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner",
"0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000)",
"QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets",
"self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1, 2) self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget)",
"= QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1, 1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget)",
"self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow)",
"self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1, 2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget)",
"= QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215))",
"QTime, QUrl, Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient,",
"QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines,",
"self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1, 2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show,",
"self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1, 1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth())",
"MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget =",
"QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1, 2)",
"2) self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1, 1)",
"self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0)",
"QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication, QComboBox, QFrame,",
"1, 2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1, 1) self.btn_outline_off =",
"QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17,",
"self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50,",
"16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow)",
"self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\")",
"1, 1, 1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1,",
"8, 0, 1, 1) self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0,",
"self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4)",
"1, 2) self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1, 1)",
"self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None))",
"self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity)",
"self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity,",
"None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\",",
"coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'main_window.ui' ##",
"0, 1, 1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1,",
"1, 1) self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0,",
"self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\")",
"u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None))",
"sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget)",
"self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230,",
"QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1,",
"1, 1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1, 1)",
"QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter)",
"self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length)",
"self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1, 1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3",
"= QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16,",
"Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\",",
"= QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset",
"= QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1, 1) self.btn_outer_off = QPushButton(self.gridLayoutWidget)",
"= QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1, 1) self.hlay_inner_offset = QHBoxLayout()",
"self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False)",
"= QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter)",
"by: Qt User Interface Compiler version 6.2.2 ## ## WARNING! All changes made",
"QSize, QTime, QUrl, Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase,",
"self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget)",
"0, 1, 3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10,",
"None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\",",
"from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime,",
"self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1,",
"16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow)",
"0, 1, 1) self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1,",
"sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521,",
"1, 1, 2) self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1)",
"self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1, 2) self.lbl_outer_lines_thck =",
"= QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1, 1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget)",
"QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter)",
"u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None))",
"self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1, 1) self.btn_inner_off =",
"self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41)) self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280,",
"= QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\")",
"= QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length",
"QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1,",
"16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal)",
"QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\")",
"u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None))",
"self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1, 1) self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck =",
"self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1, 1) self.lbl_outer_lines_offset =",
"self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1, 2) self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select =",
"u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\",",
"font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1, 3) self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth())",
"u\"Inner Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\",",
"PySide6.QtWidgets import (QApplication, QComboBox, QFrame, QGraphicsView, QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit, QMainWindow, QPushButton,",
"self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1, 2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1,",
"0, 1, 1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1,",
"1) self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1, 1)",
"20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41)) self.lbl_err_msg",
"sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1, 3)",
"None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\",",
"16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal)",
"self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1, 1) self.hlay_inner_offset =",
"QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1,",
"None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\",",
"= QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1, 1) self.lbl_crosshair_color",
"self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity,",
"self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230,",
"0, 1, 1) self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1,",
"self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1, 1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)",
"self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1, 1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity,",
"= QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215))",
"self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\", None))",
"self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity)",
"= QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1, 1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget)",
"self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1)",
"= QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset",
"Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\",",
"3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1, 1) self.horizontalLayout =",
"self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1, 1) self.lbl_outer_lines =",
"self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line =",
"Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None))",
"self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout,",
"1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1, 1) self.lbl_outer_lines",
"self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck)",
"1, 1, 1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0)",
"self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1, 2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3,",
"self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1, 1) self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity",
"self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50,",
"self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines",
"sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\")",
"self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1, 2) self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on,",
"self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1, 1) self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\")",
"21, 1, 1, 2) self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0,",
"sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1, 1) self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False)",
"None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\",",
"self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow)",
"sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0)",
"self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow)",
"self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget)",
"u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\",",
"0, 1, 1) self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1)",
"self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h)",
"QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth())",
"0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0)",
"sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1, 1) self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True)",
"sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1, 1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 =",
"QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\")",
"self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1)",
"self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1,",
"self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset)",
"self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a",
"None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project Home</a>\", None)) self.btn_del_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Delete Crosshair\", None)) self.lbl_err_msg.setText(\"\") # retranslateUi",
"None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\",",
"sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\")",
"QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1,",
"self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2)",
"when recompiling UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject,",
"self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1, 1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8,",
"self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215))",
"Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project Home</a>\", None)) self.btn_del_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Delete Crosshair\", None)) self.lbl_err_msg.setText(\"\") #",
"self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1, 3) self.lbl_outlines",
"self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1, 1) self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset",
"50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1, 2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\")",
"QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1, 1) self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\")",
"= QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity",
"self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1, 2) self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\")",
"self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1, 2) self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\")",
"self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res / Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None))",
"self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1, 1) self.lbl_inner_lines_opacity =",
"self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50,",
"20, 0, 1, 1) self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2,",
"self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select",
"3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1,",
"self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230,",
"self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1, 1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset,",
"QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui",
"= QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False)",
"1, 1, 2) self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1,",
"self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth())",
"MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1, 3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font)",
"QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None))",
"QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity",
"1, 1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1, 1)",
"QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from",
"self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5)",
"0, 1, 1) self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1,",
"18, 0, 1, 1) self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2,",
"1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1, 1) self.btn_outer_off",
"None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\",",
"= QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0)",
"self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1, 1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\")",
"= QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5,",
"self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal)",
"Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\", None))",
"1, 1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1, 1)",
"QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1, 2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2)",
"sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1, 2) self.btn_save_ch",
"QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1, 3) self.lbl_inner_lines =",
"self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False)",
"Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\",",
"self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow)",
"self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1, 1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14,",
"1, 2) self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select)",
"sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\")",
"self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1, 1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2)",
"= QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText)",
"QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui import (QBrush, QColor,",
"QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1, 1) self.hlay_outer_offset = QHBoxLayout()",
"self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1, 2) self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length =",
"None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\",",
"Res / Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\",",
"WARNING! All changes made in this file will be lost when recompiling UI",
"self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1, 2) self.btn_inner_on = QPushButton(self.gridLayoutWidget)",
"self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget)",
"self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1, 2) self.qcb_crosshair_color =",
"16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50,",
"None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\",",
"self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0))",
"1, 1) self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0,",
"None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines",
"self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1, 1) self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True)",
"self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair =",
"1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred,",
"self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1, 3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth())",
"QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter)",
"1, 1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1, 1)",
"self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\",",
"1, 2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1, 1)",
"u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines",
"1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1, 1) self.hlay_outer_length",
"## Created by: Qt User Interface Compiler version 6.2.2 ## ## WARNING! All",
"self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1, 1) self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on,",
"= QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1, 2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth())",
"= QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1, 1) self.btn_outer_on = QPushButton(self.gridLayoutWidget)",
"None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\",",
"820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141,",
"self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow)",
"self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair",
"14, 1, 1, 2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1, 1)",
"QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply)",
"self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1, 1) self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False)",
"self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1, 2) self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41))",
"QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1, 1) self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\")",
"sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1,",
"None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\",",
"2) self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1, 1) self.btn_outer_on",
"self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1, 1) self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset",
"1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1, 1) self.lbl_outer_lines_offset",
"0, 1, 1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1,",
"file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect,",
"self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None))",
"self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1, 1) self.lbl_inner_lines_show =",
"this file will be lost when recompiling UI file! ################################################################################ from PySide6.QtCore import",
"self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1, 2) self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\")",
"0) self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)",
"self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1, 1) self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity =",
"1, 1) self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0,",
"1) self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1, 1) self.lbl_inner_lines_show",
"self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1, 2) self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10,",
"self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1,",
"in this file will be lost when recompiling UI file! ################################################################################ from PySide6.QtCore",
"self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\",",
"self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1, 1) self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True)",
"self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal)",
"MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\",",
"sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1, 1) self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False)",
"self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1, 2) self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget)",
"QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766)) self.gridLayout = QGridLayout(self.gridLayoutWidget)",
"self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1, 1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2)",
"self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1, 1) self.lbl_inner_lines_thck =",
"self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1, 2) self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth())",
"self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1, 2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1,",
"= QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1, 1) self.hlay_dot_thck = QHBoxLayout()",
"1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1, 1) self.lbl_inner_lines_thck",
"QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0,",
"self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1, 2) self.hlay_outer_thck = QHBoxLayout()",
"0, 1, 1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1,",
"= QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1, 1) self.btn_inner_off = QPushButton(self.gridLayoutWidget)",
"file will be lost when recompiling UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication,",
"self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w",
"Qt User Interface Compiler version 6.2.2 ## ## WARNING! All changes made in",
"= QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21,",
"0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1, 2) self.lbl_crosshair",
"self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1, 1) self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget)",
"u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot",
"self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1, 1) self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True)",
"None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\",",
"self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1, 1) self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth())",
"if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0))",
"self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1, 2) self.lbl_ch_select = QLabel(self.gridLayoutWidget)",
"800, 141, 41)) self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)",
"u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines",
"u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\",",
"QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1, 1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget)",
"2) self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair",
"sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1, 1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\")",
"2, 1, 1) self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1)",
"self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1, 1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9,",
"= QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0,",
"self.gridLayout.setContentsMargins(0, 0, 0, 0) self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1",
"= QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\")",
"Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer",
"= QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget =",
"self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1, 2)",
"None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\",",
"sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1, 1) self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length =",
"= QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1, 1) self.hlay_outer_length = QHBoxLayout()",
"self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity,",
"self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1, 2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1,",
"import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter,",
"self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1, 2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18,",
"self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8,",
"## ## Created by: Qt User Interface Compiler version 6.2.2 ## ## WARNING!",
"self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1, 2) self.hlay_outer_opacity =",
"import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt)",
"1, 1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1, 1)",
"13, 0, 1, 1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0,",
"QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity =",
"self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow)",
"self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\")",
"self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1, 2)",
"self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset,",
"self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50,",
"15, 0, 1, 1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0,",
"sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1, 1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2)",
"self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50,",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10,",
"-*- ################################################################################ ## Form generated from reading UI file 'main_window.ui' ## ## Created",
"None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\",",
"self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1, 1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth())",
"self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck)",
"self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck)",
"521, 766)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.hlay_inner_opacity =",
"20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self,",
"5, 0, 1, 1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0,",
"self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1, 2) self.hlay_inner_length = QHBoxLayout()",
"self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font",
"sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1,",
"self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1, 1) self.lbl_inner_lines_offset =",
"Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\",",
"= QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215))",
"= QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck",
"sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w =",
"self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1, 2) self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget)",
"1, 2) self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0,",
"self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1, 1) self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget)",
"self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget)",
"self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1, 1) self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off,",
"QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50,",
"16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal)",
"0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0)",
"/ Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None))",
"None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\",",
"1, 1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4,",
"2, 1, 1) self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1)",
"self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13,",
"1, 1) self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0,",
"sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter)",
"self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1, 1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget)",
"QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4)",
"u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project Home</a>\", None)) self.btn_del_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Delete Crosshair\", None)) self.lbl_err_msg.setText(\"\")",
"self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1, 1) self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\")",
"u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None))",
"QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication, QComboBox, QFrame, QGraphicsView, QGridLayout, QHBoxLayout,",
"self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0))",
"u\"Inner Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\",",
"QLayout, QLineEdit, QMainWindow, QPushButton, QSizePolicy, QSlider, QWidget) class Ui_MainWindow(object): def setupUi(self, MainWindow): if",
"self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res / Game Res\", None))",
"self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True)",
"= QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1, 1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget)",
"self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230,",
"QWidget) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849)",
"1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1, 1) self.hlay_inner_offset",
"self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180,",
"self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset)",
"self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1, 2)",
"0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1)",
"sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1, 1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2)",
"self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1, 2) self.hlay_inner_length",
"sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1, 3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\")",
"1) self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0))",
"sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1, 1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2)",
"1, 1) self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1,",
"self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset,",
"u\"Outer Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines",
"1, 0, 1, 1) self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18,",
"22, 0, 1, 1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0,",
"u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\",",
"3) self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1, 1) self.btn_inner_off",
"1, 1, 2) self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41)) self.lbl_link =",
"self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1, 1) self.hlay_dot_opacity =",
"QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth())",
"141, 41)) self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False)",
"reading UI file 'main_window.ui' ## ## Created by: Qt User Interface Compiler version",
"self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1)",
"self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget)",
"self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20)",
"sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1, 1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2)",
"0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1, 2) self.hlay_ch_select =",
"self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0)",
"self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1, 1) self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\")",
"self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint)",
"self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0))",
"self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1, 2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth())",
"= QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14,",
"QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1, 1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\")",
"self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\", None))",
"Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None))",
"self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1,",
"self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1, 1) self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True)",
"self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1, 2) self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141,",
"self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\",",
"made in this file will be lost when recompiling UI file! ################################################################################ from",
"Form generated from reading UI file 'main_window.ui' ## ## Created by: Qt User",
"self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\",",
"1, 3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1, 1) self.horizontalLayout",
"self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity,",
"1, 1, 2) self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1)",
"9, 0, 1, 1) self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7,",
"1, 1, 2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1,",
"2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1, 1) self.btn_dot_off",
"self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230,",
"QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1, 1) self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False)",
"self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1, 1) self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget)",
"self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1, 1) self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off,",
"None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None))",
"QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1, 1) self.lbl_outline_opacity =",
"12, 1, 1, 1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0,",
"self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1,",
"0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000)",
"6.2.2 ## ## WARNING! All changes made in this file will be lost",
"1, 1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1, 1)",
"= QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1, 1) self.hlay_outline_opacity =",
"self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1, 2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res,",
"QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication, QComboBox, QFrame, QGraphicsView, QGridLayout,",
"7, 0, 1, 1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0,",
"self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow)",
"1) self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1, 1) self.hlay_inner_thck",
"QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1, 3) self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\")",
"= QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1, 1) self.hlay_dot_opacity = QHBoxLayout()",
"self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1, 2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color,",
"2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1, 2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget)",
"self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1, 2)",
"self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save",
"None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines",
"self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter)",
"self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False)",
"QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h",
"1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1,",
"self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\",",
"self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1, 2) self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget)",
"self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1, 2) self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\")",
"QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter)",
"QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum,",
"u\"Screen Res / Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\",",
"1, 2) self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0,",
"sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget)",
"self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4)",
"self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5",
"self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1, 1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum,",
"from PySide6.QtWidgets import (QApplication, QComboBox, QFrame, QGraphicsView, QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit, QMainWindow,",
"self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck)",
"self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1, 2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21,",
"generated from reading UI file 'main_window.ui' ## ## Created by: Qt User Interface",
"self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100)",
"file 'main_window.ui' ## ## Created by: Qt User Interface Compiler version 6.2.2 ##",
"self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50,",
"self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1, 2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\")",
"2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1, 1) self.btn_outline_off = QPushButton(self.gridLayoutWidget)",
"self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project Home</a>\", None)) self.btn_del_ch.setText(QCoreApplication.translate(\"MainWindow\",",
"1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)",
"self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1, 1) self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False)",
"1) self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0))",
"QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\")",
"self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1, 1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6,",
"None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\",",
"self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1, 2) self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\")",
"# setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\",",
"self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1, 1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth())",
"self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1, 1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck,",
"0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1, 2) self.lbl_ch_select",
"Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline",
"1) self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0))",
"self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False)",
"self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1)",
"2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1, 1) self.lbl_center_dot_thck",
"1, 2) self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1,",
"QObject, QPoint, QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient,",
"## ## WARNING! All changes made in this file will be lost when",
"= QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1, 3) self.lbl_outlines = QLabel(self.gridLayoutWidget)",
"(QApplication, QComboBox, QFrame, QGraphicsView, QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit, QMainWindow, QPushButton, QSizePolicy, QSlider,",
"QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1, 1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget)",
"u\"Show Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\",",
"self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False)",
"self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1, 1) self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18,",
"self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1, 2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19,",
"self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False)",
"= QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1, 1) self.lbl_center_dot_opacity =",
"7, 1, 1, 1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0,",
"QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1,",
"1) self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1, 1) self.hlay_dot_opacity",
"def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy = QSizePolicy(QSizePolicy.Fixed,",
"1, 1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1, 1)",
"= QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)",
"self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\",",
"self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset)",
"2) self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0))",
"self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1, 2) self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True)",
"self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50,",
"sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1, 1) self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True)",
"2) self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0))",
"Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\",",
"self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False)",
"self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1, 1) self.btn_outer_on =",
"= QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w)",
"self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity)",
"will be lost when recompiling UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate,",
"0, 1, 1) self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1,",
"self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1, 1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum,",
"sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1, 1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth())",
"self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41)) self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\")",
"1, 1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth())",
"self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1, 2) self.hlay_outline_thck = QHBoxLayout()",
"= QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck",
"Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\",",
"2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1, 1) self.hlay_dot_thck",
"self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1, 2) self.lbl_ch_select =",
"self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget)",
"self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1, 1) self.btn_dot_on =",
"24, 1, 1, 2) self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41)) self.lbl_link",
"QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1, 1) self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\")",
"Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\", None))",
"self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41)) self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText)",
"None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines",
"Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\", None))",
"self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\",",
"self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1, 1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22,",
"1) self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1, 1)",
"self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1, 2) self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck =",
"self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1, 2) self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText)",
"self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget)",
"self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1, 1) self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off,",
"= QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215))",
"= QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9,",
"0, 1, 1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1,",
"1, 1, 2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1,",
"self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0,",
"self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\", None))",
"QSlider, QWidget) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541,",
"self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41)) self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241, 20))",
"1) self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0))",
"self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1, 1)",
"self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity,",
"= QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1, 1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget)",
"utf-8 -*- ################################################################################ ## Form generated from reading UI file 'main_window.ui' ## ##",
"self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1,",
"self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1, 2)",
"24, 0, 1, 1) self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4,",
"None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project Home</a>\", None))",
"1, 2) self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0,",
"1, 1) self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1,",
"QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1, 1) self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\")",
"Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\",",
"QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair)",
"from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence,",
"0, 0) self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding,",
"self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\")",
"QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter)",
"Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\",",
"0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0)",
"<gh_stars>0 # -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI",
"= QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1, 1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget)",
"QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1, 1) self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\")",
"QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter)",
"Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None))",
"QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck =",
"self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\",",
"QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui import",
"self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length)",
"self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0, 0)",
"41)) self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch",
"MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget",
"QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1, 1) self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\")",
"self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1, 2) self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font)",
"QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter)",
"QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1, 1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\")",
"self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1, 1) self.hlay_dot_thck =",
"self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0))",
"QUrl, Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon,",
"self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1, 2) self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\")",
"self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2) self.btn_outline_on",
"QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck =",
"self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1, 2) self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget)",
"16, 1, 1, 2) self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth())",
"self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1, 2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\")",
"################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize,",
"self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766)) self.gridLayout",
"self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1, 1) self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset =",
"self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\",",
"self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0,",
"class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy",
"QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck =",
"self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1, 1) self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length",
"self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False)",
"QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter)",
"self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal)",
"QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1, 1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\")",
"sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1, 1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2)",
"self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1, 1) self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\")",
"self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1, 3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget)",
"recompiling UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject,",
"= QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1, 1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget)",
"MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u\"gridLayoutWidget\") self.gridLayoutWidget.setGeometry(QRect(10, 10, 521, 766))",
"setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)",
"1, 1) self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1, 1)",
"self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1, 2) self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select",
"self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\",",
"QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity =",
"self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50,",
"self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1, 1) self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\")",
"0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1, 2) self.qcb_crosshair_color",
"self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False)",
"None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\",",
"QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity)",
"sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\")",
"QTransform) from PySide6.QtWidgets import (QApplication, QComboBox, QFrame, QGraphicsView, QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit,",
"1, 1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1, 1)",
"= QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1, 1) self.lbl_outline_opacity",
"u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\",",
"self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None))",
"font = QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1, 3) self.lbl_outlines =",
"0, 1, 1) self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1,",
"QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length =",
"QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient,",
"2) self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1,",
"self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1)",
"self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1, 1) self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False)",
"780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi",
"self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1, 1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck,",
"QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1, 1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\")",
"QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0,",
"self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1, 2)",
"self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget)",
"1, 1, 2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1,",
"QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line)",
"self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget)",
"self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth()) self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False)",
"self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100)",
"0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000)",
"self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck,",
"self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1, 2) self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\")",
"0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1, 2) self.hlay_outer_thck",
"self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1, 1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck,",
"= QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15,",
"self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1, 1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3,",
"1, 1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0, 1, 1)",
"0, 1, 1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1,",
"521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi def",
"u\"Outer Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\",",
"self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length)",
"self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1)",
"u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\",",
"1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1, 1) self.lbl_center_dot",
"self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\",",
"def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None))",
"self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40,",
"800, 141, 41)) self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow)",
"6, 1, 1, 2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1, 2)",
"self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth())",
"50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1, 2)",
"self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\",",
"sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24,",
"self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1, 2) self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity =",
"u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res / Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\",",
"4, 0, 1, 1) self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2,",
"QSizePolicy, QSlider, QWidget) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True)",
"1, 1, 2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1, 1) self.btn_outline_off",
"self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)",
"1, 1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth())",
"= QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215))",
"Lines Opacity\", None)) self.lbl_center_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center",
"QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False)",
"# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file",
"QHBoxLayout, QLabel, QLayout, QLineEdit, QMainWindow, QPushButton, QSizePolicy, QSlider, QWidget) class Ui_MainWindow(object): def setupUi(self,",
"self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) #",
"self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1, 1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show,",
"self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1, 2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2)",
"QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1,",
"u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None))",
"self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1, 1) self.lbl_center_dot =",
"9, 1, 1, 2) self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth())",
"self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None))",
"Created by: Qt User Interface Compiler version 6.2.2 ## ## WARNING! All changes",
"QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1, 1) self.hlay_outline_opacity = QHBoxLayout()",
"None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer",
"0, 1, 1) self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1)",
"QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui import (QBrush,",
"u\"Show Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\",",
"= QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215))",
"u\"Center Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\", None))",
"= QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1,",
"QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1, 1) self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\")",
"1, 1) self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1,",
"= QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck",
"self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res /",
"16777215)) self.le_outer_thck.setAlignment(Qt.AlignCenter) self.le_outer_thck.setReadOnly(False) self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal)",
"Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\", None))",
"sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1, 1)",
"self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1, 1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)",
"Compiler version 6.2.2 ## ## WARNING! All changes made in this file will",
"u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None))",
"sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\")",
"= QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0)",
"All changes made in this file will be lost when recompiling UI file!",
"2) self.hlay_outer_thck = QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0))",
"16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal)",
"self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1, 1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2,",
"not MainWindow.objectName(): MainWindow.setObjectName(u\"MainWindow\") MainWindow.setEnabled(True) MainWindow.resize(541, 849) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())",
"self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1, 2) self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1,",
"self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth())",
"self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None))",
"QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter)",
"6, 0, 1, 1) self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth())",
"u\"Center Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\",",
"QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1, 1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\")",
"QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1,",
"self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1, 2) self.btn_inner_on",
"sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget",
"None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project Home</a>\", None)) self.btn_del_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Delete Crosshair\",",
"self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget)",
"self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1, 1) self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on,",
"Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\",",
"13, 1, 1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on,",
"QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u\"centralwidget\") self.gridLayoutWidget = QWidget(self.centralwidget)",
"self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\")",
"self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1, 1) self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7,",
"self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1, 2)",
"None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\",",
"self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res / Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None))",
"self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity)",
"self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont() font.setPointSize(12)",
"4, 1, 1, 1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0)",
"self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck,",
"QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter)",
"1, 1, 2) self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1,",
"self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1,",
"self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow)",
"self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False)",
"self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1, 1) self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\")",
"QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity =",
"1, 1) self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0,",
"self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0))",
"1, 2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1, 1)",
"QMainWindow, QPushButton, QSizePolicy, QSlider, QWidget) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName():",
"self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1)",
"self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1, 3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch,",
"0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1, 2) self.lbl_outer_lines_thck",
"2) self.btn_save_ch = QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41)) self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\")",
"self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select,",
"QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity =",
"1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3)",
"QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w)",
"self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230,",
"self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20)",
"self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\", None))",
"################################################################################ ## Form generated from reading UI file 'main_window.ui' ## ## Created by:",
"self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity = QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal)",
"u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\",",
"sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outer_opacity.setAlignment(Qt.AlignCenter) self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\")",
"7, 2, 1, 1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0,",
"self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6)",
"= QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50,",
"QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length =",
"self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1, 2) self.hlay_ch_select = QHBoxLayout()",
"sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0, 1, 1) self.hlay_inner_offset = QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset =",
"None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner",
"sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1, 1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2)",
"self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230, 0)) self.slide_dot_opacity.setMaximum(1000) self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1, 2)",
"self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1, 1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth())",
"self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\", None))",
"1, 1) self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0,",
"self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50,",
"## WARNING! All changes made in this file will be lost when recompiling",
"= QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 =",
"12, 2, 1, 1) self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth())",
"1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1, 1) self.lbl_inner_lines_length_2",
"self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply =",
"self.line.setObjectName(u\"line\") self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h",
"Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None))",
"self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1, 2) self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity",
"12, 0, 1, 1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0)",
"self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1, 2)",
"sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1, 1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2)",
"self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1, 1) self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck",
"self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1, 2) self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length",
"self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6)",
"self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1, 2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget)",
"self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1, 1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth())",
"1, 1, 2) self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1)",
"QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset =",
"from reading UI file 'main_window.ui' ## ## Created by: Qt User Interface Compiler",
"self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1,",
"Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\",",
"= QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1, 1) self.hlay_outer_offset =",
"1, 3) self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1, 1)",
"None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\",",
"QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1,",
"self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1, 1) self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\")",
"self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1, 1) self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\")",
"self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1, 1) self.hlay_outer_length =",
"self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False)",
"self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\",",
"self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1,",
"sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0)) self.le_inner_opacity.setMaximumSize(QSize(50, 16777215)) self.le_inner_opacity.setAlignment(Qt.AlignCenter) self.le_inner_opacity.setReadOnly(False) self.hlay_inner_opacity.addWidget(self.le_inner_opacity) self.slide_inner_opacity =",
"0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000)",
"= QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1, 1) self.hlay_inner_thck = QHBoxLayout()",
"= QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0, 1, 1) self.btn_dot_off = QPushButton(self.gridLayoutWidget)",
"Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer",
"self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1, 2) self.lbl_stretch_res =",
"0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1, 2) self.lbl_stretch_res",
"QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w = QLineEdit(self.gridLayoutWidget) self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth())",
"self.le_outer_opacity.setReadOnly(False) self.hlay_outer_opacity.addWidget(self.le_outer_opacity) self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity)",
"self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply = QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)",
"self.slide_dot_opacity.setOrientation(Qt.Horizontal) self.slide_dot_opacity.setTickPosition(QSlider.TicksBelow) self.slide_dot_opacity.setTickInterval(100) self.hlay_dot_opacity.addWidget(self.slide_dot_opacity) self.gridLayout.addLayout(self.hlay_dot_opacity, 8, 1, 1, 2) self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\")",
"PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl,",
"= QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1, 3) self.lbl_screen_stretch",
"QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit, QMainWindow, QPushButton, QSizePolicy, QSlider, QWidget) class Ui_MainWindow(object): def",
"0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1, 2) self.hlay_outline_thck",
"self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1, 3) self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines,",
"self.hlay_outer_thck.addWidget(self.le_outer_thck) self.slide_outer_thck = QSlider(self.gridLayoutWidget) self.slide_outer_thck.setObjectName(u\"slide_outer_thck\") self.slide_outer_thck.setMinimumSize(QSize(230, 0)) self.slide_outer_thck.setMinimum(0) self.slide_outer_thck.setMaximum(10) self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck)",
"Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\",",
"3, 1, 1, 2) self.lbl_outer_lines_show = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_show.setObjectName(u\"lbl_outer_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_show, 18, 0,",
"self.line.setFrameShape(QFrame.VLine) self.line.setFrameShadow(QFrame.Sunken) self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h =",
"2, 1, 1) self.lbl_inner_lines_show = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1,",
"self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck,",
"QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_opacity, 5, 0, 1, 1) self.lbl_crosshair_color =",
"= QHBoxLayout() self.hlay_outer_thck.setObjectName(u\"hlay_outer_thck\") self.le_outer_thck = QLineEdit(self.gridLayoutWidget) self.le_outer_thck.setObjectName(u\"le_outer_thck\") sizePolicy1.setHeightForWidth(self.le_outer_thck.sizePolicy().hasHeightForWidth()) self.le_outer_thck.setSizePolicy(sizePolicy1) self.le_outer_thck.setMinimumSize(QSize(0, 0)) self.le_outer_thck.setMaximumSize(QSize(50, 16777215))",
"self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1, 1) self.lbl_center_dot_opacity",
"u\"Outer Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\",",
"0, 1, 3) self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1,",
"19, 0, 1, 1) self.lbl_center_dot_thck = QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0,",
"QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont,",
"QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1,",
"QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1, 1) self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\")",
"self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy)",
"self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1, 1) self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7,",
"'main_window.ui' ## ## Created by: Qt User Interface Compiler version 6.2.2 ## ##",
"self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41)) self.lbl_err_msg = QLabel(self.centralwidget)",
"8, 1, 1, 2) self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300,",
"sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth()) self.le_outline_opacity.setSizePolicy(sizePolicy1) self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\")",
"None)) self.le_outer_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res",
"self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\",",
"= QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font =",
"self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1, 3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23,",
"None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res / Game Res\",",
"None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\",",
"u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner",
"QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1, 1) self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\")",
"Dot Thiccness\", None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center",
"self.slide_outer_opacity = QSlider(self.gridLayoutWidget) self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19,",
"u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None))",
"self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1, 1) self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\")",
"766)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.hlay_inner_opacity = QHBoxLayout()",
"1, 1) self.btn_dot_off = QPushButton(self.gridLayoutWidget) self.btn_dot_off.setObjectName(u\"btn_dot_off\") self.btn_dot_off.setCheckable(True) self.btn_dot_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_off, 7, 2, 1, 1)",
"= QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6,",
"QLabel, QLayout, QLineEdit, QMainWindow, QPushButton, QSizePolicy, QSlider, QWidget) class Ui_MainWindow(object): def setupUi(self, MainWindow):",
"Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\",",
"QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1,",
"17, 0, 1, 3) self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0,",
"sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth()) self.le_res_game_h.setSizePolicy(sizePolicy4) self.le_res_game_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_h) self.btn_stretch_apply",
"u\"Center Dot\", None)) self.lbl_inner_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Opacity\", None)) self.lbl_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Thiccness\", None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\",",
"self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1, 2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck,",
"self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50)) self.qgv_crosshair.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.qgv_crosshair.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1,",
"= QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length",
"18, 1, 1, 1) self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth())",
"1, 1, 2) self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2,",
"0, 1, 1) self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True) self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2,",
"QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1, 1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget)",
"self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity = QSlider(self.gridLayoutWidget) self.slide_dot_opacity.setObjectName(u\"slide_dot_opacity\") self.slide_dot_opacity.setMinimumSize(QSize(230,",
"QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1, 1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\")",
"QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u\"horizontalLayout\") self.le_res_screen_w",
"self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1, 1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth())",
"MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow):",
"QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import",
"= QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget)",
"self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1, 2) self.hlay_outer_opacity = QHBoxLayout()",
"self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal) self.slide_outline_thck.setTickPosition(QSlider.TicksBelow) self.slide_outline_thck.setTickInterval(1) self.hlay_outline_thck.addWidget(self.slide_outline_thck) self.gridLayout.addLayout(self.hlay_outline_thck, 6, 1, 1, 2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget)",
"Lines Length\", None)) self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\",",
"u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner",
"QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset =",
"2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1,",
"0, 1, 1) self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1)",
"self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1, 1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2",
"self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1, 1, 2) self.hlay_outer_thck =",
"0, 1, 1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1,",
"1, 3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0,",
"self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230,",
"self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line = QFrame(self.gridLayoutWidget) self.line.setObjectName(u\"line\")",
"self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1, 1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16,",
"self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1, 3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget)",
"self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1, 2) self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2)",
"self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1, 1) self.hlay_outer_offset = QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget)",
"sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font)",
"u\"Outer Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer",
"sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h)",
"self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1, 1) self.hlay_inner_thck =",
"QLineEdit, QMainWindow, QPushButton, QSizePolicy, QSlider, QWidget) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not",
"self.gridLayout.addWidget(self.lbl_inner_lines_length, 14, 0, 1, 1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15,",
"None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None))",
"self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100)",
"QPushButton(self.centralwidget) self.btn_save_ch.setObjectName(u\"btn_save_ch\") self.btn_save_ch.setGeometry(QRect(10, 800, 141, 41)) self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241,",
"self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\") self.btn_outer_on.setCheckable(True) self.btn_outer_on.setChecked(True) self.btn_outer_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_on, 18, 1, 1, 1) self.hlay_outer_offset",
"self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1, 3) self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2)",
"self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41)) self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget)",
"MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline",
"2, 0, 1, 3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font) self.lbl_inner_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_inner_lines,",
"Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project Home</a>\",",
"22, 1, 1, 2) self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth())",
"= QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.le_inner_opacity.sizePolicy().hasHeightForWidth()) self.le_inner_opacity.setSizePolicy(sizePolicy1) self.le_inner_opacity.setMinimumSize(QSize(0, 0))",
"1) self.lbl_crosshair_color = QLabel(self.gridLayoutWidget) self.lbl_crosshair_color.setObjectName(u\"lbl_crosshair_color\") sizePolicy2.setHeightForWidth(self.lbl_crosshair_color.sizePolicy().hasHeightForWidth()) self.lbl_crosshair_color.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_crosshair_color, 3, 0, 1, 1) self.lbl_inner_lines_offset",
"4, 2, 1, 1) self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity = QLineEdit(self.gridLayoutWidget) self.le_outline_opacity.setObjectName(u\"le_outline_opacity\") sizePolicy1.setHeightForWidth(self.le_outline_opacity.sizePolicy().hasHeightForWidth())",
"10, 521, 766)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.hlay_inner_opacity",
"self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1, 2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth())",
"1, 2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0, 1, 1)",
"self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20)",
"5, 1, 1, 2) self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12,",
"u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project",
"None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\",",
"u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\",",
"Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\",",
"self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1, 2) self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True) self.btn_inner_on.setChecked(True) self.btn_inner_on.setAutoDefault(False)",
"u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\",",
"self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\",",
"QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1, 1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\")",
"1, 2) self.hlay_inner_length = QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0,",
"1, 1) self.lbl_outline_thck = QLabel(self.gridLayoutWidget) self.lbl_outline_thck.setObjectName(u\"lbl_outline_thck\") sizePolicy2.setHeightForWidth(self.lbl_outline_thck.sizePolicy().hasHeightForWidth()) self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1, 1)",
"self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0, 1, 1) self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck",
"self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1, 1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2)",
"QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication, QComboBox, QFrame, QGraphicsView,",
"self.gridLayout.addWidget(self.lbl_inner_lines, 10, 0, 1, 3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0,",
"= QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215))",
"0, 1, 1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\") sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0)",
"self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal) self.slide_inner_length.setTickPosition(QSlider.TicksBelow) self.slide_inner_length.setTickInterval(1) self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length,",
"self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1, 2) self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck",
"self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True) self.btn_outline_on.setAutoDefault(False) self.btn_outline_on.setFlat(False) self.gridLayout.addWidget(self.btn_outline_on, 4, 1, 1, 1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\")",
"1) self.btn_dot_on = QPushButton(self.gridLayoutWidget) self.btn_dot_on.setObjectName(u\"btn_dot_on\") self.btn_dot_on.setCheckable(True) self.btn_dot_on.setChecked(True) self.btn_dot_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_dot_on, 7, 1, 1, 1)",
"0, 1, 1) self.lbl_outer_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_offset.setObjectName(u\"lbl_outer_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1,",
"self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1) self.le_outer_opacity.setMinimumSize(QSize(0, 0)) self.le_outer_opacity.setMaximumSize(QSize(50,",
"= QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget)",
"Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None))",
"1) self.lbl_outline_opacity = QLabel(self.gridLayoutWidget) self.lbl_outline_opacity.setObjectName(u\"lbl_outline_opacity\") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lbl_outline_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outline_opacity.setSizePolicy(sizePolicy2)",
"self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50)) self.qgv_crosshair.setMaximumSize(QSize(50, 50)) self.qgv_crosshair.setBaseSize(QSize(50, 50))",
"self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck)",
"self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1, 1) self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity = QLineEdit(self.gridLayoutWidget)",
"lost when recompiling UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,",
"self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck, 9, 1, 1, 2) self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\")",
"self.slide_dot_thck = QSlider(self.gridLayoutWidget) self.slide_dot_thck.setObjectName(u\"slide_dot_thck\") self.slide_dot_thck.setMinimumSize(QSize(230, 0)) self.slide_dot_thck.setMinimum(1) self.slide_dot_thck.setMaximum(6) self.slide_dot_thck.setOrientation(Qt.Horizontal) self.slide_dot_thck.setTickPosition(QSlider.TicksBelow) self.slide_dot_thck.setTickInterval(1) self.hlay_dot_thck.addWidget(self.slide_dot_thck) self.gridLayout.addLayout(self.hlay_dot_thck,",
"self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0, 1, 3) self.lbl_outlines = QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4,",
"self.le_inner_thck.setSizePolicy(sizePolicy1) self.le_inner_thck.setMinimumSize(QSize(0, 0)) self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230,",
"1, 1, 1, 2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity, 19, 0,",
"16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\") self.slide_outline_thck.setMinimumSize(QSize(230, 0)) self.slide_outline_thck.setMinimum(1) self.slide_outline_thck.setMaximum(6) self.slide_outline_thck.setOrientation(Qt.Horizontal)",
"None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\", None)) self.btn_outer_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\",",
"self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\")",
"self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1, 2) self.lbl_crosshair =",
"QComboBox, QFrame, QGraphicsView, QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit, QMainWindow, QPushButton, QSizePolicy, QSlider, QWidget)",
"self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1, 2) self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth())",
"0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1, 2) self.hlay_outer_opacity",
"1) self.lbl_inner_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_opacity.setObjectName(u\"lbl_inner_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_opacity, 13, 0, 1, 1) self.lbl_outline_thck",
"self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False)",
"2) self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0))",
"self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0)) self.le_dot_thck.setMaximumSize(QSize(50, 16777215)) self.le_dot_thck.setAlignment(Qt.AlignCenter) self.le_dot_thck.setReadOnly(False) self.hlay_dot_thck.addWidget(self.le_dot_thck) self.slide_dot_thck = QSlider(self.gridLayoutWidget)",
"PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient,",
"= QHBoxLayout() self.hlay_outer_offset.setObjectName(u\"hlay_outer_offset\") self.le_outer_offset = QLineEdit(self.gridLayoutWidget) self.le_outer_offset.setObjectName(u\"le_outer_offset\") sizePolicy1.setHeightForWidth(self.le_outer_offset.sizePolicy().hasHeightForWidth()) self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215))",
"16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0) self.slide_inner_length.setMaximum(20) self.slide_inner_length.setOrientation(Qt.Horizontal)",
"QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget) self.le_outer_length.setObjectName(u\"le_outer_length\") sizePolicy1.setHeightForWidth(self.le_outer_length.sizePolicy().hasHeightForWidth()) self.le_outer_length.setSizePolicy(sizePolicy1) self.le_outer_length.setMinimumSize(QSize(0, 0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter)",
"= QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0, 1, 1) self.btn_outline_off = QPushButton(self.gridLayoutWidget) self.btn_outline_off.setObjectName(u\"btn_outline_off\") self.btn_outline_off.setCheckable(True)",
"QHBoxLayout() self.hlay_inner_length.setObjectName(u\"hlay_inner_length\") self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter)",
"= QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0)) self.slide_outline_opacity.setMaximum(1000) self.slide_outline_opacity.setOrientation(Qt.Horizontal) self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1,",
"self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Save Crosshair\", None)) self.lbl_link.setText(QCoreApplication.translate(\"MainWindow\", u\"<a href=\\\"http://example.com/\\\">Project Home</a>\", None)) self.btn_del_ch.setText(QCoreApplication.translate(\"MainWindow\", u\"Delete Crosshair\", None))",
"None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Inner Lines\", None)) self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None))",
"0, 0, 0) self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity = QLineEdit(self.gridLayoutWidget) self.le_inner_opacity.setObjectName(u\"le_inner_opacity\") sizePolicy1 =",
"sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50, 16777215)) self.le_outline_thck.setAlignment(Qt.AlignCenter) self.le_outline_thck.setReadOnly(False) self.hlay_outline_thck.addWidget(self.le_outline_thck) self.slide_outline_thck = QSlider(self.gridLayoutWidget) self.slide_outline_thck.setObjectName(u\"slide_outline_thck\")",
"self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_inner_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_inner_lines_length.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Length\", None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner",
"u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.lbl_outer_lines_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Opacity\", None))",
"import (QApplication, QComboBox, QFrame, QGraphicsView, QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit, QMainWindow, QPushButton, QSizePolicy,",
"self.le_inner_length = QLineEdit(self.gridLayoutWidget) self.le_inner_length.setObjectName(u\"le_inner_length\") sizePolicy1.setHeightForWidth(self.le_inner_length.sizePolicy().hasHeightForWidth()) self.le_inner_length.setSizePolicy(sizePolicy1) self.le_inner_length.setMinimumSize(QSize(0, 0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length)",
"self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22, 1, 1, 2) self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\")",
"self.lbl_link.setGeometry(QRect(280, 820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800,",
"self.btn_inner_off.setObjectName(u\"btn_inner_off\") self.btn_inner_off.setCheckable(True) self.btn_inner_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_off, 12, 2, 1, 1) self.hlay_dot_opacity = QHBoxLayout() self.hlay_dot_opacity.setObjectName(u\"hlay_dot_opacity\") self.le_dot_opacity",
"QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap,",
"self.le_outer_offset.setSizePolicy(sizePolicy1) self.le_outer_offset.setMinimumSize(QSize(0, 0)) self.le_outer_offset.setMaximumSize(QSize(50, 16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230,",
"(QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette,",
"self.btn_inner_on.setAutoDefault(False) self.gridLayout.addWidget(self.btn_inner_on, 12, 1, 1, 1) self.lbl_inner_lines_length = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length.setObjectName(u\"lbl_inner_lines_length\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length,",
"self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset)",
"self.gridLayout.addWidget(self.lbl_outer_lines_offset, 22, 0, 1, 1) self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20,",
"self.slide_outline_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outline_opacity.setTickInterval(100) self.hlay_outline_opacity.addWidget(self.slide_outline_opacity) self.gridLayout.addLayout(self.hlay_outline_opacity, 5, 1, 1, 2) self.btn_inner_on = QPushButton(self.gridLayoutWidget) self.btn_inner_on.setObjectName(u\"btn_inner_on\") self.btn_inner_on.setCheckable(True)",
"None)) self.btn_dot_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_center_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot Opacity\", None)) self.lbl_center_dot.setText(QCoreApplication.translate(\"MainWindow\", u\"Center Dot\", None))",
"= QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41)) self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780,",
"QGraphicsView, QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit, QMainWindow, QPushButton, QSizePolicy, QSlider, QWidget) class Ui_MainWindow(object):",
"= QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0) self.slide_outer_length.setMaximum(20) self.slide_outer_length.setOrientation(Qt.Horizontal) self.slide_outer_length.setTickPosition(QSlider.TicksBelow) self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20,",
"QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\") sizePolicy2.setHeightForWidth(self.lbl_ch_select.sizePolicy().hasHeightForWidth()) self.lbl_ch_select.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_ch_select, 1, 0, 1, 1) self.btn_outer_on = QPushButton(self.gridLayoutWidget) self.btn_outer_on.setObjectName(u\"btn_outer_on\")",
"14, 0, 1, 1) self.lbl_inner_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_thck.setObjectName(u\"lbl_inner_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_thck, 15, 0,",
"self.lbl_inner_lines_length_2 = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_length_2.setObjectName(u\"lbl_inner_lines_length_2\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_length_2.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_length_2.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_length_2, 20, 0, 1, 1) self.btn_outer_off =",
"None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Stretch\", None)) self.btn_stretch_apply.setText(QCoreApplication.translate(\"MainWindow\", u\"Apply\", None)) self.btn_save_ch.setText(QCoreApplication.translate(\"MainWindow\",",
"setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Manager\", None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\",",
"self.slide_outer_opacity.setObjectName(u\"slide_outer_opacity\") self.slide_outer_opacity.setMinimumSize(QSize(230, 0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1, 2)",
"self.slide_outer_length.setTickInterval(1) self.hlay_outer_length.addWidget(self.slide_outer_length) self.gridLayout.addLayout(self.hlay_outer_length, 20, 1, 1, 2) self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3)",
"sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.lbl_outer_lines.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines.setSizePolicy(sizePolicy3) font = QFont() font.setPointSize(12) self.lbl_outer_lines.setFont(font) self.lbl_outer_lines.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_outer_lines, 17, 0,",
"u\"Inner Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Length\",",
"3, 0, 1, 1) self.lbl_inner_lines_offset = QLabel(self.gridLayoutWidget) self.lbl_inner_lines_offset.setObjectName(u\"lbl_inner_lines_offset\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_offset.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_offset.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_offset, 16, 0,",
"= QLabel(self.gridLayoutWidget) self.lbl_center_dot_thck.setObjectName(u\"lbl_center_dot_thck\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_thck.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_thck, 9, 0, 1, 1) self.btn_dot_on = QPushButton(self.gridLayoutWidget)",
"15, 1, 1, 2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_thck.setObjectName(u\"lbl_outer_lines_thck\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_thck.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_thck, 21, 0,",
"self.slide_inner_thck.setMaximum(10) self.slide_inner_thck.setOrientation(Qt.Horizontal) self.slide_inner_thck.setTickPosition(QSlider.TicksBelow) self.slide_inner_thck.setTickInterval(1) self.hlay_inner_thck.addWidget(self.slide_inner_thck) self.gridLayout.addLayout(self.hlay_inner_thck, 15, 1, 1, 2) self.lbl_outer_lines_thck = QLabel(self.gridLayoutWidget)",
"1, 1, 2) self.hlay_ch_select = QHBoxLayout() self.hlay_ch_select.setObjectName(u\"hlay_ch_select\") self.qcb_ch_select = QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215))",
"1) self.hlay_dot_thck = QHBoxLayout() self.hlay_dot_thck.setObjectName(u\"hlay_dot_thck\") self.le_dot_thck = QLineEdit(self.gridLayoutWidget) self.le_dot_thck.setObjectName(u\"le_dot_thck\") sizePolicy1.setHeightForWidth(self.le_dot_thck.sizePolicy().hasHeightForWidth()) self.le_dot_thck.setSizePolicy(sizePolicy1) self.le_dot_thck.setMinimumSize(QSize(0, 0))",
"self.hlay_ch_select.addWidget(self.qgv_crosshair) self.gridLayout.addLayout(self.hlay_ch_select, 1, 1, 1, 2) self.lbl_outer_lines_opacity = QLabel(self.gridLayoutWidget) self.lbl_outer_lines_opacity.setObjectName(u\"lbl_outer_lines_opacity\") sizePolicy2.setHeightForWidth(self.lbl_outer_lines_opacity.sizePolicy().hasHeightForWidth()) self.lbl_outer_lines_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outer_lines_opacity,",
"Interface Compiler version 6.2.2 ## ## WARNING! All changes made in this file",
"sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h = QLineEdit(self.gridLayoutWidget) self.le_res_screen_h.setObjectName(u\"le_res_screen_h\") sizePolicy4.setHeightForWidth(self.le_res_screen_h.sizePolicy().hasHeightForWidth()) self.le_res_screen_h.setSizePolicy(sizePolicy4) self.le_res_screen_h.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_h) self.line",
"self.le_outline_opacity.setMinimumSize(QSize(0, 0)) self.le_outline_opacity.setMaximumSize(QSize(50, 16777215)) self.le_outline_opacity.setAlignment(Qt.AlignCenter) self.le_outline_opacity.setReadOnly(False) self.hlay_outline_opacity.addWidget(self.le_outline_opacity) self.slide_outline_opacity = QSlider(self.gridLayoutWidget) self.slide_outline_opacity.setObjectName(u\"slide_outline_opacity\") self.slide_outline_opacity.setMinimumSize(QSize(230, 0))",
"self.le_inner_thck.setMaximumSize(QSize(50, 16777215)) self.le_inner_thck.setAlignment(Qt.AlignCenter) self.le_inner_thck.setReadOnly(False) self.hlay_inner_thck.addWidget(self.le_inner_thck) self.slide_inner_thck = QSlider(self.gridLayoutWidget) self.slide_inner_thck.setObjectName(u\"slide_inner_thck\") self.slide_inner_thck.setMinimumSize(QSize(230, 0)) self.slide_inner_thck.setMinimum(0) self.slide_inner_thck.setMaximum(10)",
"u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair Color\", None)) self.lbl_inner_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\",",
"## Form generated from reading UI file 'main_window.ui' ## ## Created by: Qt",
"self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True) self.btn_del_ch =",
"self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.lbl_inner_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show",
"None)) self.lbl_inner_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines Thiccness\", None)) self.lbl_outer_lines_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Offset\", None)) self.lbl_inner_lines_length_2.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer",
"= QPushButton(self.gridLayoutWidget) self.btn_stretch_apply.setObjectName(u\"btn_stretch_apply\") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0))",
"0)) self.le_inner_length.setMaximumSize(QSize(50, 16777215)) self.le_inner_length.setAlignment(Qt.AlignCenter) self.le_inner_length.setReadOnly(False) self.hlay_inner_length.addWidget(self.le_inner_length) self.slide_inner_length = QSlider(self.gridLayoutWidget) self.slide_inner_length.setObjectName(u\"slide_inner_length\") self.slide_inner_length.setMinimumSize(QSize(230, 0)) self.slide_inner_length.setMinimum(0)",
"self.hlay_inner_length.addWidget(self.slide_inner_length) self.gridLayout.addLayout(self.hlay_inner_length, 14, 1, 1, 2) self.lbl_stretch_res = QLabel(self.gridLayoutWidget) self.lbl_stretch_res.setObjectName(u\"lbl_stretch_res\") self.gridLayout.addWidget(self.lbl_stretch_res, 24, 0,",
"UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint,",
"(QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt) from",
"None)) self.le_outer_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_crosshair.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair\", None)) self.lbl_inner_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Inner Lines\", None)) self.lbl_screen_stretch.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen",
"QSlider(self.gridLayoutWidget) self.slide_inner_offset.setObjectName(u\"slide_inner_offset\") self.slide_inner_offset.setMinimumSize(QSize(230, 0)) self.slide_inner_offset.setMinimum(0) self.slide_inner_offset.setMaximum(20) self.slide_inner_offset.setOrientation(Qt.Horizontal) self.slide_inner_offset.setTickPosition(QSlider.TicksBelow) self.slide_inner_offset.setTickInterval(1) self.hlay_inner_offset.addWidget(self.slide_inner_offset) self.gridLayout.addLayout(self.hlay_inner_offset, 16, 1,",
"self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41)) self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20))",
"self.hlay_outline_thck = QHBoxLayout() self.hlay_outline_thck.setObjectName(u\"hlay_outline_thck\") self.le_outline_thck = QLineEdit(self.gridLayoutWidget) self.le_outline_thck.setObjectName(u\"le_outline_thck\") sizePolicy1.setHeightForWidth(self.le_outline_thck.sizePolicy().hasHeightForWidth()) self.le_outline_thck.setSizePolicy(sizePolicy1) self.le_outline_thck.setMinimumSize(QSize(0, 0)) self.le_outline_thck.setMaximumSize(QSize(50,",
"self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1, 3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3) self.lbl_inner_lines.setFont(font)",
"self.btn_outer_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_inner_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\",",
"u\"Inner Lines Offset\", None)) self.le_inner_offset.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outer_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_ch_select.setText(QCoreApplication.translate(\"MainWindow\", u\"Select Crosshair\",",
"= QHBoxLayout() self.hlay_inner_offset.setObjectName(u\"hlay_inner_offset\") self.le_inner_offset = QLineEdit(self.gridLayoutWidget) self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215))",
"MainWindow.resize(541, 849) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow)",
"self.horizontalLayout.addWidget(self.line) self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\")",
"sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1, 1) self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2)",
"0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2) self.btn_outline_on =",
"self.lbl_outline_thck.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outline_thck, 6, 0, 1, 1) self.hlay_outer_length = QHBoxLayout() self.hlay_outer_length.setObjectName(u\"hlay_outer_length\") self.le_outer_length = QLineEdit(self.gridLayoutWidget)",
"self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show Outer Lines\", None)) self.btn_dot_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\",",
"1) self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1, 1) self.lbl_inner_lines_opacity",
"User Interface Compiler version 6.2.2 ## ## WARNING! All changes made in this",
"self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0, 1, 3) self.lbl_inner_lines = QLabel(self.gridLayoutWidget) self.lbl_inner_lines.setObjectName(u\"lbl_inner_lines\") sizePolicy3.setHeightForWidth(self.lbl_inner_lines.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines.setSizePolicy(sizePolicy3)",
"= QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10, 780, 521, 20)) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False)",
"16777215)) self.le_outer_offset.setAlignment(Qt.AlignCenter) self.le_outer_offset.setReadOnly(False) self.hlay_outer_offset.addWidget(self.le_outer_offset) self.slide_outer_offset = QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal)",
"self.lbl_outer_lines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines\", None)) self.lbl_outlines.setText(QCoreApplication.translate(\"MainWindow\", u\"Outlines\", None)) self.btn_inner_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_dot_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None))",
"QComboBox(self.gridLayoutWidget) self.qcb_ch_select.setObjectName(u\"qcb_ch_select\") self.qcb_ch_select.setMaximumSize(QSize(300, 16777215)) self.hlay_ch_select.addWidget(self.qcb_ch_select) self.qgv_crosshair = QGraphicsView(self.gridLayoutWidget) self.qgv_crosshair.setObjectName(u\"qgv_crosshair\") sizePolicy.setHeightForWidth(self.qgv_crosshair.sizePolicy().hasHeightForWidth()) self.qgv_crosshair.setSizePolicy(sizePolicy) self.qgv_crosshair.setMinimumSize(QSize(50, 50))",
"QFrame, QGraphicsView, QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit, QMainWindow, QPushButton, QSizePolicy, QSlider, QWidget) class",
"QLabel(self.gridLayoutWidget) self.lbl_inner_lines_show.setObjectName(u\"lbl_inner_lines_show\") sizePolicy2.setHeightForWidth(self.lbl_inner_lines_show.sizePolicy().hasHeightForWidth()) self.lbl_inner_lines_show.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_inner_lines_show, 12, 0, 1, 1) self.lbl_outer_lines = QLabel(self.gridLayoutWidget) self.lbl_outer_lines.setObjectName(u\"lbl_outer_lines\")",
"QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication, QComboBox,",
"None)) self.le_inner_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.btn_outline_on.setText(QCoreApplication.translate(\"MainWindow\", u\"On\", None)) self.lbl_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"Outline Opacity\", None)) self.lbl_crosshair_color.setText(QCoreApplication.translate(\"MainWindow\", u\"Crosshair",
"Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage,",
"0, 1, 3) self.lbl_screen_stretch = QLabel(self.gridLayoutWidget) self.lbl_screen_stretch.setObjectName(u\"lbl_screen_stretch\") self.lbl_screen_stretch.setFont(font) self.gridLayout.addWidget(self.lbl_screen_stretch, 23, 0, 1, 1)",
"QLabel(self.gridLayoutWidget) self.lbl_outlines.setObjectName(u\"lbl_outlines\") sizePolicy2.setHeightForWidth(self.lbl_outlines.sizePolicy().hasHeightForWidth()) self.lbl_outlines.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_outlines, 4, 0, 1, 1) self.btn_inner_off = QPushButton(self.gridLayoutWidget) self.btn_inner_off.setObjectName(u\"btn_inner_off\")",
"self.le_res_screen_w.setObjectName(u\"le_res_screen_w\") sizePolicy4 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.le_res_screen_w.sizePolicy().hasHeightForWidth()) self.le_res_screen_w.setSizePolicy(sizePolicy4) self.le_res_screen_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_screen_w) self.le_res_screen_h =",
"u\"0\", None)) self.le_outer_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\", None)) self.le_inner_length.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res / Game",
"self.retranslateUi(MainWindow) self.btn_outline_on.setDefault(False) self.btn_outer_on.setDefault(False) self.btn_outline_off.setDefault(False) self.btn_inner_on.setDefault(False) self.btn_dot_on.setDefault(False) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\",",
"141, 41)) self.lbl_link = QLabel(self.centralwidget) self.lbl_link.setObjectName(u\"lbl_link\") self.lbl_link.setGeometry(QRect(280, 820, 241, 20)) self.lbl_link.setTextFormat(Qt.RichText) self.lbl_link.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.lbl_link.setOpenExternalLinks(True)",
"self.le_inner_offset.setObjectName(u\"le_inner_offset\") sizePolicy1.setHeightForWidth(self.le_inner_offset.sizePolicy().hasHeightForWidth()) self.le_inner_offset.setSizePolicy(sizePolicy1) self.le_inner_offset.setMinimumSize(QSize(0, 0)) self.le_inner_offset.setMaximumSize(QSize(50, 16777215)) self.le_inner_offset.setAlignment(Qt.AlignCenter) self.le_inner_offset.setReadOnly(False) self.hlay_inner_offset.addWidget(self.le_inner_offset) self.slide_inner_offset = QSlider(self.gridLayoutWidget)",
"self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1, 1, 2) self.btn_outline_on = QPushButton(self.gridLayoutWidget) self.btn_outline_on.setObjectName(u\"btn_outline_on\") self.btn_outline_on.setCheckable(True) self.btn_outline_on.setChecked(True)",
"1, 2) self.lbl_crosshair = QLabel(self.gridLayoutWidget) self.lbl_crosshair.setObjectName(u\"lbl_crosshair\") sizePolicy3.setHeightForWidth(self.lbl_crosshair.sizePolicy().hasHeightForWidth()) self.lbl_crosshair.setSizePolicy(sizePolicy3) self.lbl_crosshair.setFont(font) self.lbl_crosshair.setTextFormat(Qt.AutoText) self.gridLayout.addWidget(self.lbl_crosshair, 2, 0,",
"= QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u\"gridLayout\") self.gridLayout.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.hlay_inner_opacity = QHBoxLayout() self.hlay_inner_opacity.setObjectName(u\"hlay_inner_opacity\") self.le_inner_opacity",
"1, 2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1, 2) self.lbl_outer_lines_show =",
"1, 1, 2) self.hlay_outer_opacity = QHBoxLayout() self.hlay_outer_opacity.setObjectName(u\"hlay_outer_opacity\") self.le_outer_opacity = QLineEdit(self.gridLayoutWidget) self.le_outer_opacity.setObjectName(u\"le_outer_opacity\") sizePolicy1.setHeightForWidth(self.le_outer_opacity.sizePolicy().hasHeightForWidth()) self.le_outer_opacity.setSizePolicy(sizePolicy1)",
"self.le_res_game_w = QLineEdit(self.gridLayoutWidget) self.le_res_game_w.setObjectName(u\"le_res_game_w\") sizePolicy4.setHeightForWidth(self.le_res_game_w.sizePolicy().hasHeightForWidth()) self.le_res_game_w.setSizePolicy(sizePolicy4) self.le_res_game_w.setAlignment(Qt.AlignCenter) self.horizontalLayout.addWidget(self.le_res_game_w) self.le_res_game_h = QLineEdit(self.gridLayoutWidget) self.le_res_game_h.setObjectName(u\"le_res_game_h\") sizePolicy4.setHeightForWidth(self.le_res_game_h.sizePolicy().hasHeightForWidth())",
"sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.btn_stretch_apply.sizePolicy().hasHeightForWidth()) self.btn_stretch_apply.setSizePolicy(sizePolicy5) self.btn_stretch_apply.setMinimumSize(QSize(40, 0)) self.horizontalLayout.addWidget(self.btn_stretch_apply) self.gridLayout.addLayout(self.horizontalLayout, 24, 1, 1, 2) self.btn_save_ch =",
"= QSlider(self.gridLayoutWidget) self.slide_outer_offset.setObjectName(u\"slide_outer_offset\") self.slide_outer_offset.setMinimumSize(QSize(230, 0)) self.slide_outer_offset.setMinimum(0) self.slide_outer_offset.setMaximum(20) self.slide_outer_offset.setOrientation(Qt.Horizontal) self.slide_outer_offset.setTickPosition(QSlider.TicksBelow) self.slide_outer_offset.setTickInterval(1) self.hlay_outer_offset.addWidget(self.slide_outer_offset) self.gridLayout.addLayout(self.hlay_outer_offset, 22,",
"0)) self.le_outer_length.setMaximumSize(QSize(50, 16777215)) self.le_outer_length.setAlignment(Qt.AlignCenter) self.le_outer_length.setReadOnly(False) self.hlay_outer_length.addWidget(self.le_outer_length) self.slide_outer_length = QSlider(self.gridLayoutWidget) self.slide_outer_length.setObjectName(u\"slide_outer_length\") self.slide_outer_length.setMinimumSize(QSize(230, 0)) self.slide_outer_length.setMinimum(0)",
"= QLineEdit(self.gridLayoutWidget) self.le_dot_opacity.setObjectName(u\"le_dot_opacity\") sizePolicy1.setHeightForWidth(self.le_dot_opacity.sizePolicy().hasHeightForWidth()) self.le_dot_opacity.setSizePolicy(sizePolicy1) self.le_dot_opacity.setMinimumSize(QSize(0, 0)) self.le_dot_opacity.setMaximumSize(QSize(50, 16777215)) self.le_dot_opacity.setAlignment(Qt.AlignCenter) self.le_dot_opacity.setReadOnly(False) self.hlay_dot_opacity.addWidget(self.le_dot_opacity) self.slide_dot_opacity",
"QPoint, QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,",
"self.btn_del_ch = QPushButton(self.centralwidget) self.btn_del_ch.setObjectName(u\"btn_del_ch\") self.btn_del_ch.setGeometry(QRect(180, 800, 141, 41)) self.lbl_err_msg = QLabel(self.centralwidget) self.lbl_err_msg.setObjectName(u\"lbl_err_msg\") self.lbl_err_msg.setGeometry(QRect(10,",
"= QSlider(self.gridLayoutWidget) self.slide_inner_opacity.setObjectName(u\"slide_inner_opacity\") self.slide_inner_opacity.setMinimumSize(QSize(230, 0)) self.slide_inner_opacity.setMaximum(1000) self.slide_inner_opacity.setOrientation(Qt.Horizontal) self.slide_inner_opacity.setTickPosition(QSlider.TicksBelow) self.slide_inner_opacity.setTickInterval(100) self.hlay_inner_opacity.addWidget(self.slide_inner_opacity) self.gridLayout.addLayout(self.hlay_inner_opacity, 13, 1,",
"self.slide_outer_thck.setOrientation(Qt.Horizontal) self.slide_outer_thck.setTickPosition(QSlider.TicksBelow) self.slide_outer_thck.setTickInterval(1) self.hlay_outer_thck.addWidget(self.slide_outer_thck) self.gridLayout.addLayout(self.hlay_outer_thck, 21, 1, 1, 2) self.lbl_ch_select = QLabel(self.gridLayoutWidget) self.lbl_ch_select.setObjectName(u\"lbl_ch_select\")",
"1, 1, 2) self.qcb_crosshair_color = QComboBox(self.gridLayoutWidget) self.qcb_crosshair_color.setObjectName(u\"qcb_crosshair_color\") self.gridLayout.addWidget(self.qcb_crosshair_color, 3, 1, 1, 2) self.lbl_outer_lines_show",
"1, 1, 1) self.lbl_center_dot_opacity = QLabel(self.gridLayoutWidget) self.lbl_center_dot_opacity.setObjectName(u\"lbl_center_dot_opacity\") sizePolicy2.setHeightForWidth(self.lbl_center_dot_opacity.sizePolicy().hasHeightForWidth()) self.lbl_center_dot_opacity.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot_opacity, 8, 0, 1,",
"1, 1) self.lbl_center_dot = QLabel(self.gridLayoutWidget) self.lbl_center_dot.setObjectName(u\"lbl_center_dot\") sizePolicy2.setHeightForWidth(self.lbl_center_dot.sizePolicy().hasHeightForWidth()) self.lbl_center_dot.setSizePolicy(sizePolicy2) self.gridLayout.addWidget(self.lbl_center_dot, 7, 0, 1, 1)",
"self.lbl_outer_lines_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"Outer Lines Thiccness\", None)) self.le_dot_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.le_outline_thck.setText(QCoreApplication.translate(\"MainWindow\", u\"0\", None)) self.lbl_outer_lines_show.setText(QCoreApplication.translate(\"MainWindow\", u\"Show",
"self.btn_outline_off.setChecked(False) self.btn_outline_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outline_off, 4, 2, 1, 1) self.hlay_outline_opacity = QHBoxLayout() self.hlay_outline_opacity.setObjectName(u\"hlay_outline_opacity\") self.le_outline_opacity =",
"0, 1, 1) self.btn_outer_off = QPushButton(self.gridLayoutWidget) self.btn_outer_off.setObjectName(u\"btn_outer_off\") self.btn_outer_off.setCheckable(True) self.btn_outer_off.setAutoDefault(False) self.gridLayout.addWidget(self.btn_outer_off, 18, 2, 1,",
"None)) self.lbl_stretch_res.setText(QCoreApplication.translate(\"MainWindow\", u\"Screen Res / Game Res\", None)) self.btn_outline_off.setText(QCoreApplication.translate(\"MainWindow\", u\"Off\", None)) self.le_outline_opacity.setText(QCoreApplication.translate(\"MainWindow\", u\"0.000\",",
"18, 2, 1, 1) self.hlay_inner_thck = QHBoxLayout() self.hlay_inner_thck.setObjectName(u\"hlay_inner_thck\") self.le_inner_thck = QLineEdit(self.gridLayoutWidget) self.le_inner_thck.setObjectName(u\"le_inner_thck\") sizePolicy1.setHeightForWidth(self.le_inner_thck.sizePolicy().hasHeightForWidth())",
"0)) self.slide_outer_opacity.setMaximum(1000) self.slide_outer_opacity.setOrientation(Qt.Horizontal) self.slide_outer_opacity.setTickPosition(QSlider.TicksBelow) self.slide_outer_opacity.setTickInterval(100) self.hlay_outer_opacity.addWidget(self.slide_outer_opacity) self.gridLayout.addLayout(self.hlay_outer_opacity, 19, 1, 1, 2) self.hlay_inner_length ="
] |
[
"dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects in Projects)\", \"value\": 1}, ], value=[], switch=True,",
"value=[], switch=True, ) ], className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True,",
"+= 1 print(\"{}: marked ignored\".format(vuln_name)) else: print(\"{}: Unable to change status\".format(vuln_name)) else: print(vuln_name",
"[] num = 0 total = 0 for comp in comps: # print(comp)",
"'componentVersionName' not in comp: continue print(\"- \" + comp['componentName'] + '/' + comp['componentVersionName'])",
"on version applicability but not active - no action\") alreadyignoredcount += 1 else:",
"], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"spdxcard\", ), width=4, ), dbc.Col(",
"{'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components = response.json().get('items', []) active_statuses =",
"], id=\"spdx_collapse\", is_open=False, ), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"spdxcard\",",
"with Mismatched BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"), ], # inline=True, ), html.Div('', id='fixcves_status'), ],",
"== 'vulnerabilities': # custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response = hub.execute_get(x['href'] + \"?limit=9999\",",
"), dbc.Form( [ dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output SPDX file\"),",
"response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components = response.json().get('items', []) active_statuses = [\"NEW\", \"NEEDS_REVIEW\",",
"No action\") except Exception as e: print(\"ERROR: Unable to update vulnerabilities via API\\n\"",
"+ str(e)) return 0 print(\"- {} CVEs already inactive\".format(alreadyignoredcount)) print(\"- {} CVEs newly",
"0 for comp in comps: # print(comp) if 'componentVersionName' not in comp: continue",
"\"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status = \"IGNORED\" comment = \"Ignored as linked BDSA has component",
"except Exception as e: print(\"ERROR: Unable to update vulnerabilities via API\\n\" + str(e))",
"+ \"?limit=9999\", custom_headers=custom_headers) # vulns = response.json().get('items', []) cvulns = bd.get_json(x['href'] + \"?limit=3000\")",
"for y in vuln['_meta']['links']: if y['rel'] == 'related-vulnerabilities': if y['label'] == 'BDSA': #",
"interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.Button(\"Ignore CVEs",
"\"IGNORED\" comment = \"Ignored as linked BDSA has component version as fixed\" print(\"Processing",
"CVEs with associated BDSAs but which do not agree on affected component version\\n\".format(num))",
"SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False, ), ], ), # dbc.CardFooter(dbc.CardLink('Project Version",
"version, vuln_list, vulns): # vulnerable_components_url = hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\" # custom_headers =",
"# in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.Button(\"Ignore CVEs with Mismatched BDSA",
"BDSA which disgrees on version applicability but not active - no action\") alreadyignoredcount",
"comps, vulns): cve_list = [] num = 0 total = 0 for comp",
"{} CVEs newly marked as ignored\".format(ignoredcount)) return ignoredcount def check_cves(bd, projverurl, comps, vulns):",
"def create_actions_tab(projname, vername): return [ dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project: - Version: -",
"active_statuses = [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status = \"IGNORED\" comment = \"Ignored as linked",
"{\"label\": \"Recursive (Projects in Projects)\", \"value\": 1}, ], value=[], switch=True, ) ], className=\"mr-3\",",
"+ '/' + comp['componentVersionName']) for x in comp['_meta']['links']: if x['rel'] == 'vulnerabilities': #",
"id=\"buttons_fixcves\", color=\"primary\"), ], # inline=True, ), html.Div('', id='fixcves_status'), ], ), # dbc.CardFooter(dbc.CardLink('Project Version",
"# response = hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers) # vulns = response.json().get('items', []) cvulns",
"dbc.CardBody( [ dcc.Interval( id='spdx_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400",
"id=\"spdx_collapse\", is_open=False, ), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"spdxcard\", ),",
"comp['_meta']['links']: if x['rel'] == 'vulnerabilities': # custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response =",
"with component version - potential false # positive\".format(vuln['name'])) if vuln['name'] not in cve_list:",
"dcc.Interval( id='spdx_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form(",
"...\") ignoredcount = 0 alreadyignoredcount = 0 try: for vuln in vulns: vuln_name",
"active - no action\") alreadyignoredcount += 1 else: print(vuln_name + \": No action\")",
"= 0 try: for vuln in vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in",
"vuln['name'] not in cve_list: cve_list.append(vuln['name']) num += 1 print(\"Found {} total vulnerabilities\".format(total)) print(\"Found",
"do not agree on affected component version\\n\".format(num)) ret = patch_cves(bd, projverurl, cve_list, vulns)",
"milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.Button(\"Ignore CVEs with Mismatched BDSA Versions\", id=\"buttons_fixcves\",",
"n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output",
"width=4, ), dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore CVEs with BDSA Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'),",
"202: ignoredcount += 1 print(\"{}: marked ignored\".format(vuln_name)) else: print(\"{}: Unable to change status\".format(vuln_name))",
"], id=\"fixcvescard\", ), width=4, ), ], ) ] def patch_cves(bd, version, vuln_list, vulns):",
"positive\".format(vuln['name'])) if vuln['name'] not in cve_list: cve_list.append(vuln['name']) num += 1 print(\"Found {} total",
"1 print(\"Found {} total vulnerabilities\".format(total)) print(\"Found {} CVEs with associated BDSAs but which",
"= bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code == 202: ignoredcount += 1 print(\"{}: marked ignored\".format(vuln_name))",
"], # inline=True, ), html.Div('', id='fixcves_status'), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)),",
"vulnerable_bom_components = response.json().get('items', []) active_statuses = [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status = \"IGNORED\" comment",
"in comps: # print(comp) if 'componentVersionName' not in comp: continue print(\"- \" +",
"for vuln in vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus']",
"data=vuln) r = bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code == 202: ignoredcount += 1 print(\"{}:",
"comp['componentVersionName']) for x in comp['_meta']['links']: if x['rel'] == 'vulnerabilities': # custom_headers = {'Accept':",
"cve_list.append(vuln['name']) num += 1 print(\"Found {} total vulnerabilities\".format(total)) print(\"Found {} CVEs with associated",
"import dash_html_components as html from dash_extensions import Download def create_actions_tab(projname, vername): return [",
"if 'componentVersionName' not in comp: continue print(\"- \" + comp['componentName'] + '/' +",
"), html.Div('', id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False,",
"link', href=projlink)), ], id=\"spdxcard\", ), width=4, ), dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore CVEs with",
"dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output SPDX file\"), ], className=\"mr-3\", ), dbc.FormGroup( [",
"Exception as e: print(\"ERROR: Unable to update vulnerabilities via API\\n\" + str(e)) return",
"vuln['remediationComment'] = comment # result = hub.execute_put(vuln['_meta']['href'], data=vuln) r = bd.session.put(vuln['_meta']['href'], json=vuln) if",
"'related-vulnerabilities': if y['label'] == 'BDSA': # print(\"{} has BDSA which disagrees with component",
"= 0 for comp in comps: # print(comp) if 'componentVersionName' not in comp:",
"), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"fixcvescard\", ), width=4, ), ], )",
"alreadyignoredcount = 0 try: for vuln in vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name",
"* 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.FormGroup( [ dbc.Label(\"Filename\",",
"= \"Ignored as linked BDSA has component version as fixed\" print(\"Processing vulnerabilities ...\")",
"\": has BDSA which disgrees on version applicability but not active - no",
"component version - potential false # positive\".format(vuln['name'])) if vuln['name'] not in cve_list: cve_list.append(vuln['name'])",
"[ dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export SPDX JSON file\", style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody( [",
"ignoredcount def check_cves(bd, projverurl, comps, vulns): cve_list = [] num = 0 total",
"update vulnerabilities via API\\n\" + str(e)) return 0 print(\"- {} CVEs already inactive\".format(alreadyignoredcount))",
"+ comp['componentVersionName']) for x in comp['_meta']['links']: if x['rel'] == 'vulnerabilities': # custom_headers =",
"total vulnerabilities\".format(total)) print(\"Found {} CVEs with associated BDSAs but which do not agree",
"not in comp: continue print(\"- \" + comp['componentName'] + '/' + comp['componentVersionName']) for",
"y['label'] == 'BDSA': # print(\"{} has BDSA which disagrees with component version -",
"output SPDX file\"), ], className=\"mr-3\", ), dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive",
"change status\".format(vuln_name)) else: print(vuln_name + \": has BDSA which disgrees on version applicability",
"vulns = response.json().get('items', []) cvulns = bd.get_json(x['href'] + \"?limit=3000\") for vuln in cvulns['items']:",
"switch=True, ) ], className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True, ),",
"dcc import dash_html_components as html from dash_extensions import Download def create_actions_tab(projname, vername): return",
"id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False, ), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link',",
"\"?limit=9999\" # custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components =",
"(Projects in Projects)\", \"value\": 1}, ], value=[], switch=True, ) ], className=\"mr-3\", ), dbc.Button(\"Export",
"dbc.Card( [ dbc.CardHeader(\"Ignore CVEs with BDSA Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody( [ dcc.Interval(",
"vuln['remediationStatus'] = status vuln['remediationComment'] = comment # result = hub.execute_put(vuln['_meta']['href'], data=vuln) r =",
"vulnerable_components_url = hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\" # custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response =",
"), dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore CVEs with BDSA Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody(",
"[ dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project: - Version: - \"), id='actions_projver'), ), dbc.Row(",
"r.status_code == 202: ignoredcount += 1 print(\"{}: marked ignored\".format(vuln_name)) else: print(\"{}: Unable to",
"BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"), ], # inline=True, ), html.Div('', id='fixcves_status'), ], ), #",
"x in comp['_meta']['links']: if x['rel'] == 'vulnerabilities': # custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} #",
"], # inline=True, ), html.Div('', id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"),",
"if x['rel'] == 'vulnerabilities': # custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response = hub.execute_get(x['href']",
"response.json().get('items', []) active_statuses = [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status = \"IGNORED\" comment = \"Ignored",
"ignoredcount = 0 alreadyignoredcount = 0 try: for vuln in vulns: vuln_name =",
"if vuln['name'] not in cve_list: cve_list.append(vuln['name']) num += 1 print(\"Found {} total vulnerabilities\".format(total))",
"Unable to update vulnerabilities via API\\n\" + str(e)) return 0 print(\"- {} CVEs",
"\" + comp['componentName'] + '/' + comp['componentVersionName']) for x in comp['_meta']['links']: if x['rel']",
"disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.FormGroup(",
"inline=True, ), html.Div('', id='fixcves_status'), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"fixcvescard\",",
"# print(comp) if 'componentVersionName' not in comp: continue print(\"- \" + comp['componentName'] +",
"not in cve_list: cve_list.append(vuln['name']) num += 1 print(\"Found {} total vulnerabilities\".format(total)) print(\"Found {}",
"html.Div('', id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False, ),",
"options=[ {\"label\": \"Recursive (Projects in Projects)\", \"value\": 1}, ], value=[], switch=True, ) ],",
"# custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components = response.json().get('items',",
"for x in comp['_meta']['links']: if x['rel'] == 'vulnerabilities': # custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'}",
"interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.FormGroup( [",
"\"?limit=3000\") for vuln in cvulns['items']: total += 1 if vuln['source'] == 'NVD': for",
"as html from dash_extensions import Download def create_actions_tab(projname, vername): return [ dbc.Row( dbc.Col(html.H2(\"Actions\")),",
"= hub.execute_put(vuln['_meta']['href'], data=vuln) r = bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code == 202: ignoredcount +=",
"via API\\n\" + str(e)) return 0 print(\"- {} CVEs already inactive\".format(alreadyignoredcount)) print(\"- {}",
"{'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response = hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers) # vulns = response.json().get('items',",
"+ comp['componentName'] + '/' + comp['componentVersionName']) for x in comp['_meta']['links']: if x['rel'] ==",
"already inactive\".format(alreadyignoredcount)) print(\"- {} CVEs newly marked as ignored\".format(ignoredcount)) return ignoredcount def check_cves(bd,",
"for comp in comps: # print(comp) if 'componentVersionName' not in comp: continue print(\"-",
"custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response = hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers) # vulns",
"which do not agree on affected component version\\n\".format(num)) ret = patch_cves(bd, projverurl, cve_list,",
"hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers) # vulns = response.json().get('items', []) cvulns = bd.get_json(x['href'] +",
"\": No action\") except Exception as e: print(\"ERROR: Unable to update vulnerabilities via",
"[ dbc.CardHeader(\"Ignore CVEs with BDSA Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody( [ dcc.Interval( id='fixcves_interval',",
"check_cves(bd, projverurl, comps, vulns): cve_list = [] num = 0 total = 0",
"dbc.Col(html.H4(\"Project: - Version: - \"), id='actions_projver'), ), dbc.Row( [ dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export",
"which disagrees with component version - potential false # positive\".format(vuln['name'])) if vuln['name'] not",
"print(\"Found {} CVEs with associated BDSAs but which do not agree on affected",
"try: for vuln in vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in vuln_list: if",
"JSON file\", style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody( [ dcc.Interval( id='spdx_interval', disabled=True, interval=1 * 6000,",
"'card-title'}, id='fixcvestitle'), dbc.CardBody( [ dcc.Interval( id='fixcves_interval', disabled=True, interval=1 * 6000, # in milliseconds",
"not agree on affected component version\\n\".format(num)) ret = patch_cves(bd, projverurl, cve_list, vulns) return",
"cve_list: cve_list.append(vuln['name']) num += 1 print(\"Found {} total vulnerabilities\".format(total)) print(\"Found {} CVEs with",
"), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"spdxcard\", ), width=4, ),",
"action\") alreadyignoredcount += 1 else: print(vuln_name + \": No action\") except Exception as",
"return [ dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project: - Version: - \"), id='actions_projver'), ),",
"Version link', href=projlink)), ], id=\"spdxcard\", ), width=4, ), dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore CVEs",
"# in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\",",
"component version as fixed\" print(\"Processing vulnerabilities ...\") ignoredcount = 0 alreadyignoredcount = 0",
"vuln['source'] == 'NVD': for y in vuln['_meta']['links']: if y['rel'] == 'related-vulnerabilities': if y['label']",
"# dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"spdxcard\", ), width=4, ), dbc.Col( dbc.Card( [",
"color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False, ), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)),",
"- Version: - \"), id='actions_projver'), ), dbc.Row( [ dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export SPDX",
"result = hub.execute_put(vuln['_meta']['href'], data=vuln) r = bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code == 202: ignoredcount",
"dbc.CardBody( [ dcc.Interval( id='fixcves_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400",
"from dash_extensions import Download def create_actions_tab(projname, vername): return [ dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row(",
"CVEs newly marked as ignored\".format(ignoredcount)) return ignoredcount def check_cves(bd, projverurl, comps, vulns): cve_list",
"print(comp) if 'componentVersionName' not in comp: continue print(\"- \" + comp['componentName'] + '/'",
"else: print(\"{}: Unable to change status\".format(vuln_name)) else: print(vuln_name + \": has BDSA which",
"max_intervals=400 ), dbc.Form( [ dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output SPDX",
"width=4, ), ], ) ] def patch_cves(bd, version, vuln_list, vulns): # vulnerable_components_url =",
"bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code == 202: ignoredcount += 1 print(\"{}: marked ignored\".format(vuln_name)) else:",
"[]) cvulns = bd.get_json(x['href'] + \"?limit=3000\") for vuln in cvulns['items']: total += 1",
"vulns): # vulnerable_components_url = hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\" # custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} #",
"marked ignored\".format(vuln_name)) else: print(\"{}: Unable to change status\".format(vuln_name)) else: print(vuln_name + \": has",
"custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components = response.json().get('items', [])",
"as fixed\" print(\"Processing vulnerabilities ...\") ignoredcount = 0 alreadyignoredcount = 0 try: for",
"- no action\") alreadyignoredcount += 1 else: print(vuln_name + \": No action\") except",
"= comment # result = hub.execute_put(vuln['_meta']['href'], data=vuln) r = bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code",
"projverurl, comps, vulns): cve_list = [] num = 0 total = 0 for",
"vuln['_meta']['links']: if y['rel'] == 'related-vulnerabilities': if y['label'] == 'BDSA': # print(\"{} has BDSA",
"linked BDSA has component version as fixed\" print(\"Processing vulnerabilities ...\") ignoredcount = 0",
"response.json().get('items', []) cvulns = bd.get_json(x['href'] + \"?limit=3000\") for vuln in cvulns['items']: total +=",
"id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True, ), html.Div('', id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\",",
"if r.status_code == 202: ignoredcount += 1 print(\"{}: marked ignored\".format(vuln_name)) else: print(\"{}: Unable",
"= response.json().get('items', []) active_statuses = [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status = \"IGNORED\" comment =",
"'/' + comp['componentVersionName']) for x in comp['_meta']['links']: if x['rel'] == 'vulnerabilities': # custom_headers",
"Version link', href=projlink)), ], id=\"fixcvescard\", ), width=4, ), ], ) ] def patch_cves(bd,",
"no action\") alreadyignoredcount += 1 else: print(vuln_name + \": No action\") except Exception",
"vuln_list, vulns): # vulnerable_components_url = hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\" # custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'}",
"[\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status = \"IGNORED\" comment = \"Ignored as linked BDSA has",
"dbc.Card( [ dbc.CardHeader(\"Export SPDX JSON file\", style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody( [ dcc.Interval( id='spdx_interval',",
"def patch_cves(bd, version, vuln_list, vulns): # vulnerable_components_url = hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\" #",
"= \"IGNORED\" comment = \"Ignored as linked BDSA has component version as fixed\"",
"applicability but not active - no action\") alreadyignoredcount += 1 else: print(vuln_name +",
"== 'NVD': for y in vuln['_meta']['links']: if y['rel'] == 'related-vulnerabilities': if y['label'] ==",
"{} CVEs with associated BDSAs but which do not agree on affected component",
"n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.Button(\"Ignore CVEs with Mismatched BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"),",
"+= 1 print(\"Found {} total vulnerabilities\".format(total)) print(\"Found {} CVEs with associated BDSAs but",
"id=\"spdxcard\", ), width=4, ), dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore CVEs with BDSA Mismatch\", style={'classname':",
"id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False, ), ],",
"BDSA has component version as fixed\" print(\"Processing vulnerabilities ...\") ignoredcount = 0 alreadyignoredcount",
"Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False, ), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ],",
"), dbc.Row( [ dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export SPDX JSON file\", style={'classname': 'card-title'}, id='spdxtitle'),",
"with associated BDSAs but which do not agree on affected component version\\n\".format(num)) ret",
"vername): return [ dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project: - Version: - \"), id='actions_projver'),",
"# custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response = hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers) #",
"json=vuln) if r.status_code == 202: ignoredcount += 1 print(\"{}: marked ignored\".format(vuln_name)) else: print(\"{}:",
"1}, ], value=[], switch=True, ) ], className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ],",
"dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True, ), html.Div('', id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download",
"disgrees on version applicability but not active - no action\") alreadyignoredcount += 1",
"dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False, ), ], ), # dbc.CardFooter(dbc.CardLink('Project",
"to change status\".format(vuln_name)) else: print(vuln_name + \": has BDSA which disgrees on version",
"print(\"- \" + comp['componentName'] + '/' + comp['componentVersionName']) for x in comp['_meta']['links']: if",
"= hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components = response.json().get('items', []) active_statuses = [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"]",
"[ dbc.Button(\"Ignore CVEs with Mismatched BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"), ], # inline=True, ),",
"print(vuln_name + \": has BDSA which disgrees on version applicability but not active",
"'BDSA': # print(\"{} has BDSA which disagrees with component version - potential false",
"print(vuln_name + \": No action\") except Exception as e: print(\"ERROR: Unable to update",
"1 else: print(vuln_name + \": No action\") except Exception as e: print(\"ERROR: Unable",
"0 alreadyignoredcount = 0 try: for vuln in vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if",
"file\", style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody( [ dcc.Interval( id='spdx_interval', disabled=True, interval=1 * 6000, #",
"+= 1 if vuln['source'] == 'NVD': for y in vuln['_meta']['links']: if y['rel'] ==",
"else: print(vuln_name + \": has BDSA which disgrees on version applicability but not",
"# inline=True, ), html.Div('', id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ],",
"* 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.Button(\"Ignore CVEs with",
"if y['label'] == 'BDSA': # print(\"{} has BDSA which disagrees with component version",
"vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus'] = status vuln['remediationComment'] = comment # result = hub.execute_put(vuln['_meta']['href'],",
"potential false # positive\".format(vuln['name'])) if vuln['name'] not in cve_list: cve_list.append(vuln['name']) num += 1",
"dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore CVEs with BDSA Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody( [",
"e: print(\"ERROR: Unable to update vulnerabilities via API\\n\" + str(e)) return 0 print(\"-",
"API\\n\" + str(e)) return 0 print(\"- {} CVEs already inactive\".format(alreadyignoredcount)) print(\"- {} CVEs",
"CVEs with Mismatched BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"), ], # inline=True, ), html.Div('', id='fixcves_status'),",
"+ \": has BDSA which disgrees on version applicability but not active -",
"dbc.Row( dbc.Col(html.H4(\"Project: - Version: - \"), id='actions_projver'), ), dbc.Row( [ dbc.Col( dbc.Card( [",
"vuln in cvulns['items']: total += 1 if vuln['source'] == 'NVD': for y in",
"associated BDSAs but which do not agree on affected component version\\n\".format(num)) ret =",
"id='fixcvestitle'), dbc.CardBody( [ dcc.Interval( id='fixcves_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0,",
"as dbc import dash_core_components as dcc import dash_html_components as html from dash_extensions import",
"in active_statuses: vuln['remediationStatus'] = status vuln['remediationComment'] = comment # result = hub.execute_put(vuln['_meta']['href'], data=vuln)",
"Projects)\", \"value\": 1}, ], value=[], switch=True, ) ], className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\",",
"6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.Button(\"Ignore CVEs with Mismatched",
"6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"),",
"return 0 print(\"- {} CVEs already inactive\".format(alreadyignoredcount)) print(\"- {} CVEs newly marked as",
"create_actions_tab(projname, vername): return [ dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project: - Version: - \"),",
"placeholder=\"Enter output SPDX file\"), ], className=\"mr-3\", ), dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\":",
"{} CVEs already inactive\".format(alreadyignoredcount)) print(\"- {} CVEs newly marked as ignored\".format(ignoredcount)) return ignoredcount",
"inactive\".format(alreadyignoredcount)) print(\"- {} CVEs newly marked as ignored\".format(ignoredcount)) return ignoredcount def check_cves(bd, projverurl,",
"cvulns['items']: total += 1 if vuln['source'] == 'NVD': for y in vuln['_meta']['links']: if",
"], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"fixcvescard\", ), width=4, ), ],",
"BDSAs but which do not agree on affected component version\\n\".format(num)) ret = patch_cves(bd,",
"Version: - \"), id='actions_projver'), ), dbc.Row( [ dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export SPDX JSON",
"), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True, ), html.Div('', id='spdx_status'), dbc.Collapse( [",
"custom_headers=custom_headers) # vulns = response.json().get('items', []) cvulns = bd.get_json(x['href'] + \"?limit=3000\") for vuln",
"], className=\"mr-3\", ), dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects in Projects)\",",
"= [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status = \"IGNORED\" comment = \"Ignored as linked BDSA",
"'application/vnd.blackducksoftware.vulnerability-4+json'} # response = hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers) # vulns = response.json().get('items', [])",
"but which do not agree on affected component version\\n\".format(num)) ret = patch_cves(bd, projverurl,",
"SPDX JSON file\", style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody( [ dcc.Interval( id='spdx_interval', disabled=True, interval=1 *",
"html.Div('', id='fixcves_status'), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"fixcvescard\", ), width=4,",
"), ], ) ] def patch_cves(bd, version, vuln_list, vulns): # vulnerable_components_url = hub.get_link(version,",
"has component version as fixed\" print(\"Processing vulnerabilities ...\") ignoredcount = 0 alreadyignoredcount =",
"comp: continue print(\"- \" + comp['componentName'] + '/' + comp['componentVersionName']) for x in",
"dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects in Projects)\", \"value\": 1}, ],",
"style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody( [ dcc.Interval( id='fixcves_interval', disabled=True, interval=1 * 6000, # in",
"), dbc.Form( [ dbc.Button(\"Ignore CVEs with Mismatched BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"), ], #",
"num = 0 total = 0 for comp in comps: # print(comp) if",
"response = hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers) # vulns = response.json().get('items', []) cvulns =",
"disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.Button(\"Ignore",
"print(\"- {} CVEs already inactive\".format(alreadyignoredcount)) print(\"- {} CVEs newly marked as ignored\".format(ignoredcount)) return",
"+ \": No action\") except Exception as e: print(\"ERROR: Unable to update vulnerabilities",
"href=projlink)), ], id=\"spdxcard\", ), width=4, ), dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore CVEs with BDSA",
"comp['componentName'] + '/' + comp['componentVersionName']) for x in comp['_meta']['links']: if x['rel'] == 'vulnerabilities':",
"= [] num = 0 total = 0 for comp in comps: #",
"dash_html_components as html from dash_extensions import Download def create_actions_tab(projname, vername): return [ dbc.Row(",
"SPDX file\"), ], className=\"mr-3\", ), dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects",
"custom_headers=custom_headers) # vulnerable_bom_components = response.json().get('items', []) active_statuses = [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status =",
"[ dcc.Interval( id='spdx_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ),",
"), width=4, ), ], ) ] def patch_cves(bd, version, vuln_list, vulns): # vulnerable_components_url",
"Mismatched BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"), ], # inline=True, ), html.Div('', id='fixcves_status'), ], ),",
"dbc.Form( [ dbc.Button(\"Ignore CVEs with Mismatched BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"), ], # inline=True,",
"str(e)) return 0 print(\"- {} CVEs already inactive\".format(alreadyignoredcount)) print(\"- {} CVEs newly marked",
"in comp: continue print(\"- \" + comp['componentName'] + '/' + comp['componentVersionName']) for x",
"= {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response = hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers) # vulns =",
"BDSA Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody( [ dcc.Interval( id='fixcves_interval', disabled=True, interval=1 * 6000,",
"], value=[], switch=True, ) ], className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], #",
"= hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\" # custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response = hub.execute_get(vulnerable_components_url,",
"dbc.CardHeader(\"Ignore CVEs with BDSA Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody( [ dcc.Interval( id='fixcves_interval', disabled=True,",
"], id=\"spdxcard\", ), width=4, ), dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore CVEs with BDSA Mismatch\",",
"\"), id='actions_projver'), ), dbc.Row( [ dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export SPDX JSON file\", style={'classname':",
"cvulns = bd.get_json(x['href'] + \"?limit=3000\") for vuln in cvulns['items']: total += 1 if",
"as e: print(\"ERROR: Unable to update vulnerabilities via API\\n\" + str(e)) return 0",
"[ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False, ), ], ), #",
"as dcc import dash_html_components as html from dash_extensions import Download def create_actions_tab(projname, vername):",
"max_intervals=400 ), dbc.Form( [ dbc.Button(\"Ignore CVEs with Mismatched BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"), ],",
"import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from",
"in vuln['_meta']['links']: if y['rel'] == 'related-vulnerabilities': if y['label'] == 'BDSA': # print(\"{} has",
"hub.execute_put(vuln['_meta']['href'], data=vuln) r = bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code == 202: ignoredcount += 1",
"inline=True, ), html.Div('', id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\",",
"dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project: - Version: - \"), id='actions_projver'), ), dbc.Row( [",
"dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"fixcvescard\", ), width=4, ), ], ) ] def",
"'NVD': for y in vuln['_meta']['links']: if y['rel'] == 'related-vulnerabilities': if y['label'] == 'BDSA':",
") ] def patch_cves(bd, version, vuln_list, vulns): # vulnerable_components_url = hub.get_link(version, \"vulnerable-components\") +",
"# result = hub.execute_put(vuln['_meta']['href'], data=vuln) r = bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code == 202:",
"0 try: for vuln in vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in vuln_list:",
"+= 1 else: print(vuln_name + \": No action\") except Exception as e: print(\"ERROR:",
"has BDSA which disagrees with component version - potential false # positive\".format(vuln['name'])) if",
"== 'related-vulnerabilities': if y['label'] == 'BDSA': # print(\"{} has BDSA which disagrees with",
"return ignoredcount def check_cves(bd, projverurl, comps, vulns): cve_list = [] num = 0",
"[ dbc.CardHeader(\"Export SPDX JSON file\", style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody( [ dcc.Interval( id='spdx_interval', disabled=True,",
"{} total vulnerabilities\".format(total)) print(\"Found {} CVEs with associated BDSAs but which do not",
"in cve_list: cve_list.append(vuln['name']) num += 1 print(\"Found {} total vulnerabilities\".format(total)) print(\"Found {} CVEs",
"false # positive\".format(vuln['name'])) if vuln['name'] not in cve_list: cve_list.append(vuln['name']) num += 1 print(\"Found",
"in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.Button(\"Ignore CVEs with Mismatched BDSA Versions\",",
"dcc.Interval( id='fixcves_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form(",
"y in vuln['_meta']['links']: if y['rel'] == 'related-vulnerabilities': if y['label'] == 'BDSA': # print(\"{}",
"\"Recursive (Projects in Projects)\", \"value\": 1}, ], value=[], switch=True, ) ], className=\"mr-3\", ),",
"agree on affected component version\\n\".format(num)) ret = patch_cves(bd, projverurl, cve_list, vulns) return ret",
"'card-title'}, id='spdxtitle'), dbc.CardBody( [ dcc.Interval( id='spdx_interval', disabled=True, interval=1 * 6000, # in milliseconds",
"= 0 alreadyignoredcount = 0 try: for vuln in vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName']",
"), dbc.Row( dbc.Col(html.H4(\"Project: - Version: - \"), id='actions_projver'), ), dbc.Row( [ dbc.Col( dbc.Card(",
"), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"spdxcard\", ), width=4, ), dbc.Col( dbc.Card(",
"'vulnerabilities': # custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response = hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers)",
"Unable to change status\".format(vuln_name)) else: print(vuln_name + \": has BDSA which disgrees on",
"# positive\".format(vuln['name'])) if vuln['name'] not in cve_list: cve_list.append(vuln['name']) num += 1 print(\"Found {}",
"in cvulns['items']: total += 1 if vuln['source'] == 'NVD': for y in vuln['_meta']['links']:",
"color=\"primary\"), ], # inline=True, ), html.Div('', id='fixcves_status'), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link',",
"which disgrees on version applicability but not active - no action\") alreadyignoredcount +=",
"= {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components = response.json().get('items', []) active_statuses",
"\"?limit=9999\", custom_headers=custom_headers) # vulns = response.json().get('items', []) cvulns = bd.get_json(x['href'] + \"?limit=3000\") for",
"), html.Div('', id='fixcves_status'), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"fixcvescard\", ),",
"print(\"- {} CVEs newly marked as ignored\".format(ignoredcount)) return ignoredcount def check_cves(bd, projverurl, comps,",
"disagrees with component version - potential false # positive\".format(vuln['name'])) if vuln['name'] not in",
"total = 0 for comp in comps: # print(comp) if 'componentVersionName' not in",
"dash_core_components as dcc import dash_html_components as html from dash_extensions import Download def create_actions_tab(projname,",
"[]) active_statuses = [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status = \"IGNORED\" comment = \"Ignored as",
"], ) ] def patch_cves(bd, version, vuln_list, vulns): # vulnerable_components_url = hub.get_link(version, \"vulnerable-components\")",
"milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter",
"= 0 total = 0 for comp in comps: # print(comp) if 'componentVersionName'",
"Versions\", id=\"buttons_fixcves\", color=\"primary\"), ], # inline=True, ), html.Div('', id='fixcves_status'), ], ), # dbc.CardFooter(dbc.CardLink('Project",
"file\"), ], className=\"mr-3\", ), dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects in",
"for vuln in cvulns['items']: total += 1 if vuln['source'] == 'NVD': for y",
"is_open=False, ), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"spdxcard\", ), width=4,",
"[ dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output SPDX file\"), ], className=\"mr-3\",",
"== 202: ignoredcount += 1 print(\"{}: marked ignored\".format(vuln_name)) else: print(\"{}: Unable to change",
"status vuln['remediationComment'] = comment # result = hub.execute_put(vuln['_meta']['href'], data=vuln) r = bd.session.put(vuln['_meta']['href'], json=vuln)",
"id=\"fixcvescard\", ), width=4, ), ], ) ] def patch_cves(bd, version, vuln_list, vulns): #",
"num += 1 print(\"Found {} total vulnerabilities\".format(total)) print(\"Found {} CVEs with associated BDSAs",
"vuln in vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in",
"1 if vuln['source'] == 'NVD': for y in vuln['_meta']['links']: if y['rel'] == 'related-vulnerabilities':",
"comment # result = hub.execute_put(vuln['_meta']['href'], data=vuln) r = bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code ==",
"version applicability but not active - no action\") alreadyignoredcount += 1 else: print(vuln_name",
"patch_cves(bd, version, vuln_list, vulns): # vulnerable_components_url = hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\" # custom_headers",
"if vuln_name in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus'] = status vuln['remediationComment'] =",
"dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output SPDX file\"), ], className=\"mr-3\", ),",
"cve_list = [] num = 0 total = 0 for comp in comps:",
"dbc.CardHeader(\"Export SPDX JSON file\", style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody( [ dcc.Interval( id='spdx_interval', disabled=True, interval=1",
"dbc.Form( [ dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output SPDX file\"), ],",
"className=\"mr-3\", ), dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects in Projects)\", \"value\":",
"def check_cves(bd, projverurl, comps, vulns): cve_list = [] num = 0 total =",
"vuln_name in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus'] = status vuln['remediationComment'] = comment",
"in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [ dbc.FormGroup( [ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\",",
"newly marked as ignored\".format(ignoredcount)) return ignoredcount def check_cves(bd, projverurl, comps, vulns): cve_list =",
"\"value\": 1}, ], value=[], switch=True, ) ], className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"),",
"print(\"{}: Unable to change status\".format(vuln_name)) else: print(vuln_name + \": has BDSA which disgrees",
"className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True, ), html.Div('', id='spdx_status'), dbc.Collapse(",
"if y['rel'] == 'related-vulnerabilities': if y['label'] == 'BDSA': # print(\"{} has BDSA which",
"0 print(\"- {} CVEs already inactive\".format(alreadyignoredcount)) print(\"- {} CVEs newly marked as ignored\".format(ignoredcount))",
"hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components = response.json().get('items', []) active_statuses = [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status",
"r = bd.session.put(vuln['_meta']['href'], json=vuln) if r.status_code == 202: ignoredcount += 1 print(\"{}: marked",
"dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export SPDX JSON file\", style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody( [ dcc.Interval(",
"in Projects)\", \"value\": 1}, ], value=[], switch=True, ) ], className=\"mr-3\", ), dbc.Button(\"Export SPDX\",",
"id='spdxtitle'), dbc.CardBody( [ dcc.Interval( id='spdx_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0,",
"# vulns = response.json().get('items', []) cvulns = bd.get_json(x['href'] + \"?limit=3000\") for vuln in",
"# vulnerable_components_url = hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\" # custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response",
"vulnerabilities\".format(total)) print(\"Found {} CVEs with associated BDSAs but which do not agree on",
"print(\"Found {} total vulnerabilities\".format(total)) print(\"Found {} CVEs with associated BDSAs but which do",
"id='fixcves_status'), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"fixcvescard\", ), width=4, ),",
"vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus']",
"\"REMEDIATION_REQUIRED\"] status = \"IGNORED\" comment = \"Ignored as linked BDSA has component version",
"import dash_core_components as dcc import dash_html_components as html from dash_extensions import Download def",
"id=\"spdx_file\", placeholder=\"Enter output SPDX file\"), ], className=\"mr-3\", ), dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\", options=[",
"# vulnerable_bom_components = response.json().get('items', []) active_statuses = [\"NEW\", \"NEEDS_REVIEW\", \"REMEDIATION_REQUIRED\"] status = \"IGNORED\"",
"dbc import dash_core_components as dcc import dash_html_components as html from dash_extensions import Download",
"), dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects in Projects)\", \"value\": 1},",
"fixed\" print(\"Processing vulnerabilities ...\") ignoredcount = 0 alreadyignoredcount = 0 try: for vuln",
"[ dbc.Checklist( id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects in Projects)\", \"value\": 1}, ], value=[],",
"ignored\".format(ignoredcount)) return ignoredcount def check_cves(bd, projverurl, comps, vulns): cve_list = [] num =",
"but not active - no action\") alreadyignoredcount += 1 else: print(vuln_name + \":",
"version - potential false # positive\".format(vuln['name'])) if vuln['name'] not in cve_list: cve_list.append(vuln['name']) num",
"dbc.Row( [ dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export SPDX JSON file\", style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody(",
"alreadyignoredcount += 1 else: print(vuln_name + \": No action\") except Exception as e:",
"in comp['_meta']['links']: if x['rel'] == 'vulnerabilities': # custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response",
"bd.get_json(x['href'] + \"?limit=3000\") for vuln in cvulns['items']: total += 1 if vuln['source'] ==",
"SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True, ), html.Div('', id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download SPDX\",",
"BDSA which disagrees with component version - potential false # positive\".format(vuln['name'])) if vuln['name']",
"print(\"ERROR: Unable to update vulnerabilities via API\\n\" + str(e)) return 0 print(\"- {}",
"dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output SPDX file\"), ], className=\"mr-3\", ), dbc.FormGroup( [ dbc.Checklist( id=\"spdx_recursive\",",
"as ignored\".format(ignoredcount)) return ignoredcount def check_cves(bd, projverurl, comps, vulns): cve_list = [] num",
"color=\"primary\"), ], # inline=True, ), html.Div('', id='spdx_status'), dbc.Collapse( [ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"),",
"= response.json().get('items', []) cvulns = bd.get_json(x['href'] + \"?limit=3000\") for vuln in cvulns['items']: total",
"dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project: - Version: - \"), id='actions_projver'), ), dbc.Row( [ dbc.Col(",
"= bd.get_json(x['href'] + \"?limit=3000\") for vuln in cvulns['items']: total += 1 if vuln['source']",
"dbc.Collapse( [ dbc.Button(\"Download SPDX\", id=\"button_download_spdx\", color=\"primary\"), Download(id=\"download_spdx\"), ], id=\"spdx_collapse\", is_open=False, ), ], ),",
"print(\"{}: marked ignored\".format(vuln_name)) else: print(\"{}: Unable to change status\".format(vuln_name)) else: print(vuln_name + \":",
"dbc.Button(\"Ignore CVEs with Mismatched BDSA Versions\", id=\"buttons_fixcves\", color=\"primary\"), ], # inline=True, ), html.Div('',",
"Download def create_actions_tab(projname, vername): return [ dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project: - Version:",
"with BDSA Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody( [ dcc.Interval( id='fixcves_interval', disabled=True, interval=1 *",
"# response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components = response.json().get('items', []) active_statuses = [\"NEW\",",
"id='spdx_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [",
"[ dcc.Interval( id='fixcves_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ),",
"link', href=projlink)), ], id=\"fixcvescard\", ), width=4, ), ], ) ] def patch_cves(bd, version,",
"= hub.execute_get(x['href'] + \"?limit=9999\", custom_headers=custom_headers) # vulns = response.json().get('items', []) cvulns = bd.get_json(x['href']",
"as linked BDSA has component version as fixed\" print(\"Processing vulnerabilities ...\") ignoredcount =",
"hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\" # custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers)",
"comps: # print(comp) if 'componentVersionName' not in comp: continue print(\"- \" + comp['componentName']",
"+ \"?limit=9999\" # custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) # vulnerable_bom_components",
"ignoredcount += 1 print(\"{}: marked ignored\".format(vuln_name)) else: print(\"{}: Unable to change status\".format(vuln_name)) else:",
"\"Ignored as linked BDSA has component version as fixed\" print(\"Processing vulnerabilities ...\") ignoredcount",
"continue print(\"- \" + comp['componentName'] + '/' + comp['componentVersionName']) for x in comp['_meta']['links']:",
"version as fixed\" print(\"Processing vulnerabilities ...\") ignoredcount = 0 alreadyignoredcount = 0 try:",
"Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody( [ dcc.Interval( id='fixcves_interval', disabled=True, interval=1 * 6000, #",
"print(\"{} has BDSA which disagrees with component version - potential false # positive\".format(vuln['name']))",
"to update vulnerabilities via API\\n\" + str(e)) return 0 print(\"- {} CVEs already",
"y['rel'] == 'related-vulnerabilities': if y['label'] == 'BDSA': # print(\"{} has BDSA which disagrees",
"if vuln['source'] == 'NVD': for y in vuln['_meta']['links']: if y['rel'] == 'related-vulnerabilities': if",
"] def patch_cves(bd, version, vuln_list, vulns): # vulnerable_components_url = hub.get_link(version, \"vulnerable-components\") + \"?limit=9999\"",
"import Download def create_actions_tab(projname, vername): return [ dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project: -",
"vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus'] = status vuln['remediationComment']",
"marked as ignored\".format(ignoredcount)) return ignoredcount def check_cves(bd, projverurl, comps, vulns): cve_list = []",
"0 total = 0 for comp in comps: # print(comp) if 'componentVersionName' not",
"# dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"fixcvescard\", ), width=4, ), ], ) ]",
"vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus'] = status vuln['remediationComment'] = comment # result",
"else: print(vuln_name + \": No action\") except Exception as e: print(\"ERROR: Unable to",
"total += 1 if vuln['source'] == 'NVD': for y in vuln['_meta']['links']: if y['rel']",
"vulns): cve_list = [] num = 0 total = 0 for comp in",
"x['rel'] == 'vulnerabilities': # custom_headers = {'Accept': 'application/vnd.blackducksoftware.vulnerability-4+json'} # response = hub.execute_get(x['href'] +",
"className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output SPDX file\"), ], className=\"mr-3\", ), dbc.FormGroup( [ dbc.Checklist(",
"vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus'] =",
"in vulns: vuln_name = vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses:",
"], className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True, ), html.Div('', id='spdx_status'),",
"vulnerabilities ...\") ignoredcount = 0 alreadyignoredcount = 0 try: for vuln in vulns:",
"id='actions_projver'), ), dbc.Row( [ dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export SPDX JSON file\", style={'classname': 'card-title'},",
"\"vulnerable-components\") + \"?limit=9999\" # custom_headers = {'Accept':'application/vnd.blackducksoftware.bill-of-materials-6+json'} # response = hub.execute_get(vulnerable_components_url, custom_headers=custom_headers) #",
"== 'BDSA': # print(\"{} has BDSA which disagrees with component version - potential",
"html from dash_extensions import Download def create_actions_tab(projname, vername): return [ dbc.Row( dbc.Col(html.H2(\"Actions\")), ),",
"comment = \"Ignored as linked BDSA has component version as fixed\" print(\"Processing vulnerabilities",
"[ dbc.Label(\"Filename\", className=\"mr-2\"), dbc.Input(type=\"text\", id=\"spdx_file\", placeholder=\"Enter output SPDX file\"), ], className=\"mr-3\", ), dbc.FormGroup(",
"comp in comps: # print(comp) if 'componentVersionName' not in comp: continue print(\"- \"",
"status = \"IGNORED\" comment = \"Ignored as linked BDSA has component version as",
"CVEs with BDSA Mismatch\", style={'classname': 'card-title'}, id='fixcvestitle'), dbc.CardBody( [ dcc.Interval( id='fixcves_interval', disabled=True, interval=1",
"dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ], id=\"spdxcard\", ), width=4, ), dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore",
"href=projlink)), ], id=\"fixcvescard\", ), width=4, ), ], ) ] def patch_cves(bd, version, vuln_list,",
"not active - no action\") alreadyignoredcount += 1 else: print(vuln_name + \": No",
"id='fixcves_interval', disabled=True, interval=1 * 6000, # in milliseconds n_intervals=0, max_intervals=400 ), dbc.Form( [",
"1 print(\"{}: marked ignored\".format(vuln_name)) else: print(\"{}: Unable to change status\".format(vuln_name)) else: print(vuln_name +",
"print(\"Processing vulnerabilities ...\") ignoredcount = 0 alreadyignoredcount = 0 try: for vuln in",
"- \"), id='actions_projver'), ), dbc.Row( [ dbc.Col( dbc.Card( [ dbc.CardHeader(\"Export SPDX JSON file\",",
"style={'classname': 'card-title'}, id='spdxtitle'), dbc.CardBody( [ dcc.Interval( id='spdx_interval', disabled=True, interval=1 * 6000, # in",
"# print(\"{} has BDSA which disagrees with component version - potential false #",
"dash_extensions import Download def create_actions_tab(projname, vername): return [ dbc.Row( dbc.Col(html.H2(\"Actions\")), ), dbc.Row( dbc.Col(html.H4(\"Project:",
"= status vuln['remediationComment'] = comment # result = hub.execute_put(vuln['_meta']['href'], data=vuln) r = bd.session.put(vuln['_meta']['href'],",
"status\".format(vuln_name)) else: print(vuln_name + \": has BDSA which disgrees on version applicability but",
"dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash_extensions",
"), width=4, ), dbc.Col( dbc.Card( [ dbc.CardHeader(\"Ignore CVEs with BDSA Mismatch\", style={'classname': 'card-title'},",
"= vuln['vulnerabilityWithRemediation']['vulnerabilityName'] if vuln_name in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus'] = status",
") ], className=\"mr-3\", ), dbc.Button(\"Export SPDX\", id=\"buttons_export_spdx\", color=\"primary\"), ], # inline=True, ), html.Div('',",
"vulnerabilities via API\\n\" + str(e)) return 0 print(\"- {} CVEs already inactive\".format(alreadyignoredcount)) print(\"-",
"ignored\".format(vuln_name)) else: print(\"{}: Unable to change status\".format(vuln_name)) else: print(vuln_name + \": has BDSA",
"+ \"?limit=3000\") for vuln in cvulns['items']: total += 1 if vuln['source'] == 'NVD':",
"# inline=True, ), html.Div('', id='fixcves_status'), ], ), # dbc.CardFooter(dbc.CardLink('Project Version link', href=projlink)), ],",
"active_statuses: vuln['remediationStatus'] = status vuln['remediationComment'] = comment # result = hub.execute_put(vuln['_meta']['href'], data=vuln) r",
"CVEs already inactive\".format(alreadyignoredcount)) print(\"- {} CVEs newly marked as ignored\".format(ignoredcount)) return ignoredcount def",
"if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus'] = status vuln['remediationComment'] = comment # result =",
"has BDSA which disgrees on version applicability but not active - no action\")",
"action\") except Exception as e: print(\"ERROR: Unable to update vulnerabilities via API\\n\" +",
"in vuln_list: if vuln['vulnerabilityWithRemediation']['remediationStatus'] in active_statuses: vuln['remediationStatus'] = status vuln['remediationComment'] = comment #",
"- potential false # positive\".format(vuln['name'])) if vuln['name'] not in cve_list: cve_list.append(vuln['name']) num +=",
"id=\"spdx_recursive\", options=[ {\"label\": \"Recursive (Projects in Projects)\", \"value\": 1}, ], value=[], switch=True, )"
] |
[
"np import unittest import os import tempfile import sys class TestConversion(unittest.TestCase): def test_imread(self):",
"for fname in expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect tif",
"= np.random.random((32, 32, 32)) filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp = phathom.io.tiff.imread(filename)",
"numpy as np import unittest import os import tempfile import sys class TestConversion(unittest.TestCase):",
"incorrect tif paths') def test_pickle_save_load(self): true_dict = {'chunks': (8, 16, 32), 'shape': (100,",
"and loaded array do not have same data type') class TestUtils(unittest.TestCase): def test_make_dir(self):",
"memory memory = phathom.utils.SharedMemory(100, np.uint32) expected = np.random.RandomState(1234).randint(0, 100, 100) with multiprocessing.Pool(1) as",
"# result = find_primes(5 * 1000 * 1000 * 1000, 5*1000*1000*1000 + 1000)",
"have same data type') class TestUtils(unittest.TestCase): def test_make_dir(self): test_dir = 'tests/make_dir_test/' if os.path.isdir(test_dir):",
"= find_primes(5 * 1000 * 1000 * 1000, 5*1000*1000*1000 + 1000) # self.assertEqual(result[0],",
"file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file2.tif', 'file3.tif'] abs_path = os.path.abspath(file_test_dir) expected_paths =",
"the wrong data type') def test_imsave(self): arr = np.random.random((32, 32, 32)) filename =",
"os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path, fname) for fname in expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir)",
"test_pickle_save_load(self): true_dict = {'chunks': (8, 16, 32), 'shape': (100, 1000, 1000)} tmp_file =",
"finally: phathom.utils.is_linux = old_is_linux if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt() # def test_parallel_map(self): #",
"'uint16', msg='loaded array has the wrong data type') def test_imsave(self): arr = np.random.random((32,",
"'file_tests') expected_files = ['file1.txt', 'file2.tif', 'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect",
"msg='loaded array has the wrong shape') self.assertEqual(data.dtype, 'uint16', msg='loaded array has the wrong",
"1000 * 1000 * 1000, 5*1000*1000*1000 + 1000) # self.assertEqual(result[0], 5000000029) class TestSegmentation(unittest.TestCase):",
"data type') def test_imsave(self): arr = np.random.random((32, 32, 32)) filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\")",
"phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect files') def test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files",
"filenames') self.assertEqual(found_paths, expected_paths, msg='found incorrect tif paths') def test_pickle_save_load(self): true_dict = {'chunks': (8,",
"paths') def test_pickle_save_load(self): true_dict = {'chunks': (8, 16, 32), 'shape': (100, 1000, 1000)}",
"generic form of SharedMemory phathom.utils.is_linux = False try: self.do_memory_tteesstt() finally: phathom.utils.is_linux = old_is_linux",
"the generic form of SharedMemory phathom.utils.is_linux = False try: self.do_memory_tteesstt() finally: phathom.utils.is_linux =",
"not match') os.remove(tmp_file) # cleanup @staticmethod def write_for_memory_tteesstt(expected): global memory with memory.txn() as",
"phathom.utils.SharedMemory(100, np.uint32) expected = np.random.RandomState(1234).randint(0, 100, 100) with multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,))",
"phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128, 128), msg='loaded array has the wrong shape') self.assertEqual(data.dtype, 'uint16',",
"of SharedMemory phathom.utils.is_linux = False try: self.do_memory_tteesstt() finally: phathom.utils.is_linux = old_is_linux if sys.platform.startswith(\"linux\"):",
"1000, 5*1000*1000*1000 + 1000) # self.assertEqual(result[0], 5000000029) class TestSegmentation(unittest.TestCase): pass if __name__==\"__main__\": unittest.main()",
"1000, 1000)} tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved",
"100) with multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn() as t: np.testing.assert_equal(t[:], expected)",
"# Test the generic form of SharedMemory phathom.utils.is_linux = False try: self.do_memory_tteesstt() finally:",
"phathom import phathom.io import phathom.utils from phathom.test_helpers import * import multiprocessing import numpy",
"if os.path.isdir(test_dir): # cleanup os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files =",
"values are not equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved and loaded array do not have",
"true_dict = {'chunks': (8, 16, 32), 'shape': (100, 1000, 1000)} tmp_file = 'tests/tmp.pkl'",
"os.path.isdir(test_dir): # cleanup os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file1.txt',",
"found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect tif filenames') self.assertEqual(found_paths, expected_paths, msg='found",
"with memory.txn() as t: np.testing.assert_equal(t[:], expected) def test_shared_memory(self): old_is_linux = phathom.utils.is_linux if sys.platform.startswith(\"linux\"):",
"expected) def test_shared_memory(self): old_is_linux = phathom.utils.is_linux if sys.platform.startswith(\"linux\"): # Test the generic form",
"file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file1.txt', 'file2.tif', 'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files,",
"import phathom.utils from phathom.test_helpers import * import multiprocessing import numpy as np import",
"np.testing.assert_equal(t[:], expected) def test_shared_memory(self): old_is_linux = phathom.utils.is_linux if sys.platform.startswith(\"linux\"): # Test the generic",
"os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file1.txt', 'file2.tif', 'file3.tif'] found_files",
"memory.txn() as t: t[:] = expected @staticmethod def do_memory_tteesstt(): global memory memory =",
"as np import unittest import os import tempfile import sys class TestConversion(unittest.TestCase): def",
"incorrect files') def test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file2.tif', 'file3.tif'] abs_path",
"1000)} tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved and",
"test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file1.txt', 'file2.tif', 'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir)",
"self.assertEqual(read_dict, true_dict, msg='saved and read dict do not match') os.remove(tmp_file) # cleanup @staticmethod",
"expected = np.random.RandomState(1234).randint(0, 100, 100) with multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn()",
"try: self.do_memory_tteesstt() finally: phathom.utils.is_linux = old_is_linux if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt() # def",
"* 1000, 5*1000*1000*1000 + 1000) # self.assertEqual(result[0], 5000000029) class TestSegmentation(unittest.TestCase): pass if __name__==\"__main__\":",
"expected_files, msg='found incorrect tif filenames') self.assertEqual(found_paths, expected_paths, msg='found incorrect tif paths') def test_pickle_save_load(self):",
"tmp.dtype, msg='saved and loaded array do not have same data type') class TestUtils(unittest.TestCase):",
"= phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect files') def test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests')",
"False try: self.do_memory_tteesstt() finally: phathom.utils.is_linux = old_is_linux if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt() #",
"['file2.tif', 'file3.tif'] abs_path = os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path, fname) for fname in expected_files]",
"make_dir') if os.path.isdir(test_dir): # cleanup os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files",
"100, 100) with multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn() as t: np.testing.assert_equal(t[:],",
"do not match') os.remove(tmp_file) # cleanup @staticmethod def write_for_memory_tteesstt(expected): global memory with memory.txn()",
"'example.tif') data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128, 128), msg='loaded array has the wrong",
"np.random.RandomState(1234).randint(0, 100, 100) with multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn() as t:",
"= os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path, fname) for fname in expected_files] found_paths, found_files =",
"do_memory_tteesstt(): global memory memory = phathom.utils.SharedMemory(100, np.uint32) expected = np.random.RandomState(1234).randint(0, 100, 100) with",
"do not have same data type') class TestUtils(unittest.TestCase): def test_make_dir(self): test_dir = 'tests/make_dir_test/'",
"type') def test_imsave(self): arr = np.random.random((32, 32, 32)) filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename,",
"'shape': (100, 1000, 1000)} tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict,",
"(64, 128, 128), msg='loaded array has the wrong shape') self.assertEqual(data.dtype, 'uint16', msg='loaded array",
"= ['file2.tif', 'file3.tif'] abs_path = os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path, fname) for fname in",
"expected @staticmethod def do_memory_tteesstt(): global memory memory = phathom.utils.SharedMemory(100, np.uint32) expected = np.random.RandomState(1234).randint(0,",
"loaded array do not have same data type') class TestUtils(unittest.TestCase): def test_make_dir(self): test_dir",
"memory = phathom.utils.SharedMemory(100, np.uint32) expected = np.random.RandomState(1234).randint(0, 100, 100) with multiprocessing.Pool(1) as pool:",
"after running make_dir') if os.path.isdir(test_dir): # cleanup os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__),",
"def test_shared_memory(self): old_is_linux = phathom.utils.is_linux if sys.platform.startswith(\"linux\"): # Test the generic form of",
"array has the wrong shape') self.assertEqual(data.dtype, 'uint16', msg='loaded array has the wrong data",
"(expected,)) with memory.txn() as t: np.testing.assert_equal(t[:], expected) def test_shared_memory(self): old_is_linux = phathom.utils.is_linux if",
"match') os.remove(tmp_file) # cleanup @staticmethod def write_for_memory_tteesstt(expected): global memory with memory.txn() as t:",
"= False try: self.do_memory_tteesstt() finally: phathom.utils.is_linux = old_is_linux if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt()",
"wrong data type') def test_imsave(self): arr = np.random.random((32, 32, 32)) filename = os.path.join(tempfile.gettempdir(),",
"multiprocessing import numpy as np import unittest import os import tempfile import sys",
"def test_imsave(self): arr = np.random.random((32, 32, 32)) filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr)",
"phathom.utils.is_linux if sys.platform.startswith(\"linux\"): # Test the generic form of SharedMemory phathom.utils.is_linux = False",
"os.remove(tmp_file) # cleanup @staticmethod def write_for_memory_tteesstt(expected): global memory with memory.txn() as t: t[:]",
"32)) filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp),",
"1000 * 1000, 5*1000*1000*1000 + 1000) # self.assertEqual(result[0], 5000000029) class TestSegmentation(unittest.TestCase): pass if",
"class TestUtils(unittest.TestCase): def test_make_dir(self): test_dir = 'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir",
"tif paths') def test_pickle_save_load(self): true_dict = {'chunks': (8, 16, 32), 'shape': (100, 1000,",
"def test_imread(self): filename = os.path.join(os.path.split(__file__)[0], 'example.tif') data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128, 128),",
"fname) for fname in expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect",
"phathom.io import phathom.utils from phathom.test_helpers import * import multiprocessing import numpy as np",
"true_dict) read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved and read dict do not match')",
"and read dict do not match') os.remove(tmp_file) # cleanup @staticmethod def write_for_memory_tteesstt(expected): global",
"test_linux_shared_memory(self): self.do_memory_tteesstt() # def test_parallel_map(self): # result = find_primes(5 * 1000 * 1000",
"tif filenames') self.assertEqual(found_paths, expected_paths, msg='found incorrect tif paths') def test_pickle_save_load(self): true_dict = {'chunks':",
"cleanup os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file1.txt', 'file2.tif', 'file3.tif']",
"self.do_memory_tteesstt() # def test_parallel_map(self): # result = find_primes(5 * 1000 * 1000 *",
"# def test_parallel_map(self): # result = find_primes(5 * 1000 * 1000 * 1000,",
"not equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved and loaded array do not have same data",
"= phathom.utils.SharedMemory(100, np.uint32) expected = np.random.RandomState(1234).randint(0, 100, 100) with multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt,",
"result = find_primes(5 * 1000 * 1000 * 1000, 5*1000*1000*1000 + 1000) #",
"loaded array values are not equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved and loaded array do",
"= os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file1.txt', 'file2.tif', 'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files,",
"SharedMemory phathom.utils.is_linux = False try: self.do_memory_tteesstt() finally: phathom.utils.is_linux = old_is_linux if sys.platform.startswith(\"linux\"): def",
"filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp), msg='saved",
"def test_pickle_save_load(self): true_dict = {'chunks': (8, 16, 32), 'shape': (100, 1000, 1000)} tmp_file",
"phathom.utils from phathom.test_helpers import * import multiprocessing import numpy as np import unittest",
"self.assertEqual(data.dtype, 'uint16', msg='loaded array has the wrong data type') def test_imsave(self): arr =",
"* 1000 * 1000 * 1000, 5*1000*1000*1000 + 1000) # self.assertEqual(result[0], 5000000029) class",
"= np.random.RandomState(1234).randint(0, 100, 100) with multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn() as",
"wrong shape') self.assertEqual(data.dtype, 'uint16', msg='loaded array has the wrong data type') def test_imsave(self):",
"= [os.path.join(abs_path, fname) for fname in expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files,",
"fname in expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect tif filenames')",
"as t: np.testing.assert_equal(t[:], expected) def test_shared_memory(self): old_is_linux = phathom.utils.is_linux if sys.platform.startswith(\"linux\"): # Test",
"128), msg='loaded array has the wrong shape') self.assertEqual(data.dtype, 'uint16', msg='loaded array has the",
"and loaded array values are not equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved and loaded array",
"found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect tif filenames') self.assertEqual(found_paths, expected_paths, msg='found incorrect",
"with memory.txn() as t: t[:] = expected @staticmethod def do_memory_tteesstt(): global memory memory",
"test_shared_memory(self): old_is_linux = phathom.utils.is_linux if sys.platform.startswith(\"linux\"): # Test the generic form of SharedMemory",
"not exist after running make_dir') if os.path.isdir(test_dir): # cleanup os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir",
"= old_is_linux if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt() # def test_parallel_map(self): # result =",
"(100, 1000, 1000)} tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict,",
"the wrong shape') self.assertEqual(data.dtype, 'uint16', msg='loaded array has the wrong data type') def",
"* 1000 * 1000, 5*1000*1000*1000 + 1000) # self.assertEqual(result[0], 5000000029) class TestSegmentation(unittest.TestCase): pass",
"os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not exist after running make_dir') if os.path.isdir(test_dir): #",
"<reponame>chunglabmit/phathom<filename>tests/tests.py import phathom import phathom.io import phathom.utils from phathom.test_helpers import * import multiprocessing",
"'file3.tif'] abs_path = os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path, fname) for fname in expected_files] found_paths,",
"['file1.txt', 'file2.tif', 'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect files') def test_tifs_in_dir(self):",
"import numpy as np import unittest import os import tempfile import sys class",
"def test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file1.txt', 'file2.tif', 'file3.tif'] found_files =",
"phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved and read dict do not match') os.remove(tmp_file) # cleanup",
"\"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp), msg='saved and loaded array",
"unittest import os import tempfile import sys class TestConversion(unittest.TestCase): def test_imread(self): filename =",
"'file2.tif', 'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect files') def test_tifs_in_dir(self): file_test_dir",
"pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn() as t: np.testing.assert_equal(t[:], expected) def test_shared_memory(self): old_is_linux = phathom.utils.is_linux",
"{'chunks': (8, 16, 32), 'shape': (100, 1000, 1000)} tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict)",
"msg='loaded array has the wrong data type') def test_imsave(self): arr = np.random.random((32, 32,",
"shape') self.assertEqual(data.dtype, 'uint16', msg='loaded array has the wrong data type') def test_imsave(self): arr",
"read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved and read dict do not match') os.remove(tmp_file)",
"def test_parallel_map(self): # result = find_primes(5 * 1000 * 1000 * 1000, 5*1000*1000*1000",
"def do_memory_tteesstt(): global memory memory = phathom.utils.SharedMemory(100, np.uint32) expected = np.random.RandomState(1234).randint(0, 100, 100)",
"import tempfile import sys class TestConversion(unittest.TestCase): def test_imread(self): filename = os.path.join(os.path.split(__file__)[0], 'example.tif') data",
"'file_tests') expected_files = ['file2.tif', 'file3.tif'] abs_path = os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path, fname) for",
"phathom.utils.pickle_save(tmp_file, true_dict) read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved and read dict do not",
"true_dict, msg='saved and read dict do not match') os.remove(tmp_file) # cleanup @staticmethod def",
"find_primes(5 * 1000 * 1000 * 1000, 5*1000*1000*1000 + 1000) # self.assertEqual(result[0], 5000000029)",
"@staticmethod def write_for_memory_tteesstt(expected): global memory with memory.txn() as t: t[:] = expected @staticmethod",
"expected_files = ['file1.txt', 'file2.tif', 'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect files')",
"msg='found incorrect files') def test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file2.tif', 'file3.tif']",
"@staticmethod def do_memory_tteesstt(): global memory memory = phathom.utils.SharedMemory(100, np.uint32) expected = np.random.RandomState(1234).randint(0, 100,",
"self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not exist after running make_dir') if os.path.isdir(test_dir): # cleanup os.rmdir(test_dir)",
"import os import tempfile import sys class TestConversion(unittest.TestCase): def test_imread(self): filename = os.path.join(os.path.split(__file__)[0],",
"test_imread(self): filename = os.path.join(os.path.split(__file__)[0], 'example.tif') data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128, 128), msg='loaded",
"= {'chunks': (8, 16, 32), 'shape': (100, 1000, 1000)} tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file,",
"msg='test_dir does not exist after running make_dir') if os.path.isdir(test_dir): # cleanup os.rmdir(test_dir) def",
"form of SharedMemory phathom.utils.is_linux = False try: self.do_memory_tteesstt() finally: phathom.utils.is_linux = old_is_linux if",
"dict do not match') os.remove(tmp_file) # cleanup @staticmethod def write_for_memory_tteesstt(expected): global memory with",
"if sys.platform.startswith(\"linux\"): # Test the generic form of SharedMemory phathom.utils.is_linux = False try:",
"write_for_memory_tteesstt(expected): global memory with memory.txn() as t: t[:] = expected @staticmethod def do_memory_tteesstt():",
"array has the wrong data type') def test_imsave(self): arr = np.random.random((32, 32, 32))",
"tmp), msg='saved and loaded array values are not equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved and",
"equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved and loaded array do not have same data type')",
"as t: t[:] = expected @staticmethod def do_memory_tteesstt(): global memory memory = phathom.utils.SharedMemory(100,",
"t: t[:] = expected @staticmethod def do_memory_tteesstt(): global memory memory = phathom.utils.SharedMemory(100, np.uint32)",
"sys.platform.startswith(\"linux\"): # Test the generic form of SharedMemory phathom.utils.is_linux = False try: self.do_memory_tteesstt()",
"= os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp), msg='saved and",
"import multiprocessing import numpy as np import unittest import os import tempfile import",
"array do not have same data type') class TestUtils(unittest.TestCase): def test_make_dir(self): test_dir =",
"def test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file2.tif', 'file3.tif'] abs_path = os.path.abspath(file_test_dir)",
"msg='saved and loaded array do not have same data type') class TestUtils(unittest.TestCase): def",
"test_make_dir(self): test_dir = 'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not exist",
"self.assertTrue(np.all(arr == tmp), msg='saved and loaded array values are not equal') self.assertEqual(arr.dtype, tmp.dtype,",
"has the wrong data type') def test_imsave(self): arr = np.random.random((32, 32, 32)) filename",
"are not equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved and loaded array do not have same",
"running make_dir') if os.path.isdir(test_dir): # cleanup os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests')",
"phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp), msg='saved and loaded array values are not equal') self.assertEqual(arr.dtype,",
"files') def test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file2.tif', 'file3.tif'] abs_path =",
"os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file2.tif', 'file3.tif'] abs_path = os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path, fname)",
"phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect tif filenames') self.assertEqual(found_paths, expected_paths, msg='found incorrect tif paths')",
"= expected @staticmethod def do_memory_tteesstt(): global memory memory = phathom.utils.SharedMemory(100, np.uint32) expected =",
"if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt() # def test_parallel_map(self): # result = find_primes(5 *",
"# cleanup os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file1.txt', 'file2.tif',",
"sys class TestConversion(unittest.TestCase): def test_imread(self): filename = os.path.join(os.path.split(__file__)[0], 'example.tif') data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape,",
"msg='saved and read dict do not match') os.remove(tmp_file) # cleanup @staticmethod def write_for_memory_tteesstt(expected):",
"has the wrong shape') self.assertEqual(data.dtype, 'uint16', msg='loaded array has the wrong data type')",
"exist after running make_dir') if os.path.isdir(test_dir): # cleanup os.rmdir(test_dir) def test_files_in_dir(self): file_test_dir =",
"found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect files') def test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__),",
"self.assertEqual(found_files, expected_files, msg='found incorrect files') def test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files =",
"32, 32)) filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr ==",
"test_dir = 'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not exist after",
"phathom.test_helpers import * import multiprocessing import numpy as np import unittest import os",
"arr = np.random.random((32, 32, 32)) filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp =",
"(8, 16, 32), 'shape': (100, 1000, 1000)} tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict",
"t[:] = expected @staticmethod def do_memory_tteesstt(): global memory memory = phathom.utils.SharedMemory(100, np.uint32) expected",
"test_parallel_map(self): # result = find_primes(5 * 1000 * 1000 * 1000, 5*1000*1000*1000 +",
"os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file1.txt', 'file2.tif', 'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found",
"os.path.join(os.path.split(__file__)[0], 'example.tif') data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128, 128), msg='loaded array has the",
"= 'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not exist after running",
"'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not exist after running make_dir')",
"arr) tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp), msg='saved and loaded array values are",
"cleanup @staticmethod def write_for_memory_tteesstt(expected): global memory with memory.txn() as t: t[:] = expected",
"= phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved and read dict do not match') os.remove(tmp_file) #",
"global memory with memory.txn() as t: t[:] = expected @staticmethod def do_memory_tteesstt(): global",
"msg='saved and loaded array values are not equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved and loaded",
"import phathom.io import phathom.utils from phathom.test_helpers import * import multiprocessing import numpy as",
"same data type') class TestUtils(unittest.TestCase): def test_make_dir(self): test_dir = 'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir)",
"sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt() # def test_parallel_map(self): # result = find_primes(5 * 1000",
"abs_path = os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path, fname) for fname in expected_files] found_paths, found_files",
"t: np.testing.assert_equal(t[:], expected) def test_shared_memory(self): old_is_linux = phathom.utils.is_linux if sys.platform.startswith(\"linux\"): # Test the",
"old_is_linux if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt() # def test_parallel_map(self): # result = find_primes(5",
"tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp), msg='saved and loaded array values are not",
"TestConversion(unittest.TestCase): def test_imread(self): filename = os.path.join(os.path.split(__file__)[0], 'example.tif') data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128,",
"TestUtils(unittest.TestCase): def test_make_dir(self): test_dir = 'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does",
"phathom.io.tiff.imsave(filename, arr) tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp), msg='saved and loaded array values",
"'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect files') def test_tifs_in_dir(self): file_test_dir =",
"Test the generic form of SharedMemory phathom.utils.is_linux = False try: self.do_memory_tteesstt() finally: phathom.utils.is_linux",
"os import tempfile import sys class TestConversion(unittest.TestCase): def test_imread(self): filename = os.path.join(os.path.split(__file__)[0], 'example.tif')",
"does not exist after running make_dir') if os.path.isdir(test_dir): # cleanup os.rmdir(test_dir) def test_files_in_dir(self):",
"tempfile import sys class TestConversion(unittest.TestCase): def test_imread(self): filename = os.path.join(os.path.split(__file__)[0], 'example.tif') data =",
"self.assertEqual(found_files, expected_files, msg='found incorrect tif filenames') self.assertEqual(found_paths, expected_paths, msg='found incorrect tif paths') def",
"self.assertEqual(found_paths, expected_paths, msg='found incorrect tif paths') def test_pickle_save_load(self): true_dict = {'chunks': (8, 16,",
"tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved and read",
"= ['file1.txt', 'file2.tif', 'file3.tif'] found_files = phathom.utils.files_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect files') def",
"def write_for_memory_tteesstt(expected): global memory with memory.txn() as t: t[:] = expected @staticmethod def",
"= os.path.join(os.path.split(__file__)[0], 'example.tif') data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128, 128), msg='loaded array has",
"read dict do not match') os.remove(tmp_file) # cleanup @staticmethod def write_for_memory_tteesstt(expected): global memory",
"filename = os.path.join(os.path.split(__file__)[0], 'example.tif') data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128, 128), msg='loaded array",
"if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not exist after running make_dir') if",
"data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128, 128), msg='loaded array has the wrong shape')",
"msg='found incorrect tif paths') def test_pickle_save_load(self): true_dict = {'chunks': (8, 16, 32), 'shape':",
"def test_linux_shared_memory(self): self.do_memory_tteesstt() # def test_parallel_map(self): # result = find_primes(5 * 1000 *",
"class TestConversion(unittest.TestCase): def test_imread(self): filename = os.path.join(os.path.split(__file__)[0], 'example.tif') data = phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64,",
"16, 32), 'shape': (100, 1000, 1000)} tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict =",
"global memory memory = phathom.utils.SharedMemory(100, np.uint32) expected = np.random.RandomState(1234).randint(0, 100, 100) with multiprocessing.Pool(1)",
"old_is_linux = phathom.utils.is_linux if sys.platform.startswith(\"linux\"): # Test the generic form of SharedMemory phathom.utils.is_linux",
"= 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved and read dict",
"[os.path.join(abs_path, fname) for fname in expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found",
"os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp), msg='saved and loaded",
"* import multiprocessing import numpy as np import unittest import os import tempfile",
"not have same data type') class TestUtils(unittest.TestCase): def test_make_dir(self): test_dir = 'tests/make_dir_test/' if",
"import phathom import phathom.io import phathom.utils from phathom.test_helpers import * import multiprocessing import",
"np.uint32) expected = np.random.RandomState(1234).randint(0, 100, 100) with multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with",
"expected_paths = [os.path.join(abs_path, fname) for fname in expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files,",
"with multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn() as t: np.testing.assert_equal(t[:], expected) def",
"= phathom.utils.is_linux if sys.platform.startswith(\"linux\"): # Test the generic form of SharedMemory phathom.utils.is_linux =",
"memory with memory.txn() as t: t[:] = expected @staticmethod def do_memory_tteesstt(): global memory",
"import unittest import os import tempfile import sys class TestConversion(unittest.TestCase): def test_imread(self): filename",
"128, 128), msg='loaded array has the wrong shape') self.assertEqual(data.dtype, 'uint16', msg='loaded array has",
"type') class TestUtils(unittest.TestCase): def test_make_dir(self): test_dir = 'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir),",
"self.do_memory_tteesstt() finally: phathom.utils.is_linux = old_is_linux if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt() # def test_parallel_map(self):",
"as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn() as t: np.testing.assert_equal(t[:], expected) def test_shared_memory(self): old_is_linux",
"= os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file2.tif', 'file3.tif'] abs_path = os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path,",
"np.random.random((32, 32, 32)) filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp = phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr",
"phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not exist after running make_dir') if os.path.isdir(test_dir): # cleanup",
"phathom.utils.is_linux = False try: self.do_memory_tteesstt() finally: phathom.utils.is_linux = old_is_linux if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self):",
"self.assertEqual(arr.dtype, tmp.dtype, msg='saved and loaded array do not have same data type') class",
"from phathom.test_helpers import * import multiprocessing import numpy as np import unittest import",
"phathom.utils.is_linux = old_is_linux if sys.platform.startswith(\"linux\"): def test_linux_shared_memory(self): self.do_memory_tteesstt() # def test_parallel_map(self): # result",
"32), 'shape': (100, 1000, 1000)} tmp_file = 'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict = phathom.utils.pickle_load(tmp_file)",
"expected_files, msg='found incorrect files') def test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file2.tif',",
"data type') class TestUtils(unittest.TestCase): def test_make_dir(self): test_dir = 'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir)",
"array values are not equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved and loaded array do not",
"def test_make_dir(self): test_dir = 'tests/make_dir_test/' if os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not",
"incorrect tif filenames') self.assertEqual(found_paths, expected_paths, msg='found incorrect tif paths') def test_pickle_save_load(self): true_dict =",
"= phathom.io.tiff.imread(filename) self.assertTrue(np.all(arr == tmp), msg='saved and loaded array values are not equal')",
"test_imsave(self): arr = np.random.random((32, 32, 32)) filename = os.path.join(tempfile.gettempdir(), \"imsave_test.tif\") phathom.io.tiff.imsave(filename, arr) tmp",
"= phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect tif filenames') self.assertEqual(found_paths, expected_paths, msg='found incorrect tif",
"== tmp), msg='saved and loaded array values are not equal') self.assertEqual(arr.dtype, tmp.dtype, msg='saved",
"# cleanup @staticmethod def write_for_memory_tteesstt(expected): global memory with memory.txn() as t: t[:] =",
"expected_files = ['file2.tif', 'file3.tif'] abs_path = os.path.abspath(file_test_dir) expected_paths = [os.path.join(abs_path, fname) for fname",
"test_tifs_in_dir(self): file_test_dir = os.path.join(os.path.dirname(__file__), 'file_tests') expected_files = ['file2.tif', 'file3.tif'] abs_path = os.path.abspath(file_test_dir) expected_paths",
"import * import multiprocessing import numpy as np import unittest import os import",
"expected_paths, msg='found incorrect tif paths') def test_pickle_save_load(self): true_dict = {'chunks': (8, 16, 32),",
"multiprocessing.Pool(1) as pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn() as t: np.testing.assert_equal(t[:], expected) def test_shared_memory(self):",
"pool: pool.apply(TestUtils.write_for_memory_tteesstt, (expected,)) with memory.txn() as t: np.testing.assert_equal(t[:], expected) def test_shared_memory(self): old_is_linux =",
"os.path.isdir(test_dir): os.rmdir(test_dir) phathom.utils.make_dir(test_dir) self.assertTrue(os.path.isdir(test_dir), msg='test_dir does not exist after running make_dir') if os.path.isdir(test_dir):",
"in expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect tif filenames') self.assertEqual(found_paths,",
"= phathom.io.tiff.imread(filename) self.assertEqual(data.shape, (64, 128, 128), msg='loaded array has the wrong shape') self.assertEqual(data.dtype,",
"self.assertEqual(data.shape, (64, 128, 128), msg='loaded array has the wrong shape') self.assertEqual(data.dtype, 'uint16', msg='loaded",
"expected_files] found_paths, found_files = phathom.utils.tifs_in_dir(file_test_dir) self.assertEqual(found_files, expected_files, msg='found incorrect tif filenames') self.assertEqual(found_paths, expected_paths,",
"'tests/tmp.pkl' phathom.utils.pickle_save(tmp_file, true_dict) read_dict = phathom.utils.pickle_load(tmp_file) self.assertEqual(read_dict, true_dict, msg='saved and read dict do",
"memory.txn() as t: np.testing.assert_equal(t[:], expected) def test_shared_memory(self): old_is_linux = phathom.utils.is_linux if sys.platform.startswith(\"linux\"): #",
"msg='found incorrect tif filenames') self.assertEqual(found_paths, expected_paths, msg='found incorrect tif paths') def test_pickle_save_load(self): true_dict",
"import sys class TestConversion(unittest.TestCase): def test_imread(self): filename = os.path.join(os.path.split(__file__)[0], 'example.tif') data = phathom.io.tiff.imread(filename)"
] |
[
"a match. ''' teamMatchId = db.Column(db.Integer, primary_key=True) #tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False)",
"easier autoLow = db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes = db.Column(db.String(255))",
"db.ForeignKey('Match.matchNo'), nullable=False) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specfic data here #Autonomous",
"autoNotes = db.Column(db.String(255)) #Teleop teleLow = db.Column(db.Integer) teleHigh = db.Column(db.Integer) telePickedUp = db.Column(db.Integer)",
"information to not clutter. ''' teamNumber = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) teamName =",
"game-specfic data here #Autonomous autoTaxi = db.Column(db.Integer) #this is an integer to make",
"( Flask , render_template , redirect , request , jsonify , url_for )",
"f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url) res_json = res.json() info = tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"],",
"''' teamMatchId = db.Column(db.Integer, primary_key=True) #tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo =",
"unique=True) teamName = db.Column(db.String(50), nullable=False) teamCity = db.Column(db.String(50)) teamState = db.Column(db.String(50)) class Match(db.Model):",
"primary_key=True, nullable=False, unique=True) red_1 = db.Column(db.Integer, nullable=False) red_2 = db.Column(db.Integer, nullable=False) red_3 =",
"this with a def getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url) res_json =",
"game-specific data here #TODO: replace this with a def getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\"",
"<filename>app.py<gh_stars>0 from flask import ( Flask , render_template , redirect , request ,",
"= f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url) res_json = res.json() info = tuple( [ res_json[\"results\"][0][\"nickname\"],",
"res.json() info = tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] ) return info @app.route(\"/\")",
"app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app) class Team(db.Model):",
"db.Column(db.String(255)) #Teleop teleLow = db.Column(db.Integer) teleHigh = db.Column(db.Integer) telePickedUp = db.Column(db.Integer) didDefense =",
"index(): ''' Flask method for returning homepage. ''' return render_template(\"index.html\") @app.route(\"/scoutMatch/<int:matchNo><int:teamNo>\") def scoutMatch():",
"''' teamNumber = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) teamName = db.Column(db.String(50), nullable=False) teamCity =",
"constants from requests.exceptions import HTTPError basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] =",
"= Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app) class Team(db.Model): '''",
"db.Column(db.Integer, primary_key=True) #tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False)",
"db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specfic data here #Autonomous autoTaxi = db.Column(db.Integer) #this",
"= db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes = db.Column(db.String(255)) #Teleop teleLow = db.Column(db.Integer) teleHigh",
"nullable=False) #TODO: Insert game-specfic data here #Autonomous autoTaxi = db.Column(db.Integer) #this is an",
"handling in Tableau easier autoLow = db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp = db.Column(db.Integer)",
"= db.Column(db.Integer) teleHigh = db.Column(db.Integer) telePickedUp = db.Column(db.Integer) didDefense = db.Column(db.Boolean) teleDefense =",
"import SQLAlchemy import os, requests from models import constants from requests.exceptions import HTTPError",
"db.Column(db.String(50)) teamState = db.Column(db.String(50)) class Match(db.Model): ''' Database model for a Match table.",
"= db.Column(db.String(50)) teamState = db.Column(db.String(50)) class Match(db.Model): ''' Database model for a Match",
"redirect , request , jsonify , url_for ) from flask_sqlalchemy import SQLAlchemy import",
"db.Column(db.Integer) teleNotes = db.Column(db.String(255)) #Endgame attemptedClimb = db.Column(db.Boolean) levelClimbed = db.Column(db.Integer) endgameNotes =",
"db.Column(db.Integer, nullable=False) blue_3 = db.Column(db.Integer, nullable=False) class TeamMatch(db.Model): ''' Database model for recording",
"db.Column(db.Boolean) fouls = db.Column(db.Integer) generalNotes = db.Column(db.String(255)) class TeamPitScout(db.Model): ''' Database model for",
"'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app) class Team(db.Model): ''' Database model for a",
"autoTaxi = db.Column(db.Integer) #this is an integer to make data handling in Tableau",
"teleNotes = db.Column(db.String(255)) #Endgame attemptedClimb = db.Column(db.Boolean) levelClimbed = db.Column(db.Integer) endgameNotes = db.Column(db.String(255))",
"#TODO: Insert game-specfic data here #Autonomous autoTaxi = db.Column(db.Integer) #this is an integer",
"class Match(db.Model): ''' Database model for a Match table. Only includes match number",
"includes rudimentary team information to not clutter. ''' teamNumber = db.Column(db.Integer, primary_key=True, nullable=False,",
"to not clutter. ''' teamNumber = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) teamName = db.Column(db.String(50),",
"includes match number and team members of an alliance. ''' matchNo = db.Column(db.Integer,",
"db.Column(db.String(255)) #Endgame attemptedClimb = db.Column(db.Boolean) levelClimbed = db.Column(db.Integer) endgameNotes = db.Column(db.String(255)) #generic game",
", url_for ) from flask_sqlalchemy import SQLAlchemy import os, requests from models import",
"import HTTPError basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False",
"res = requests.get(url) res_json = res.json() info = tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"],",
"models import constants from requests.exceptions import HTTPError basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__)",
"= db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes = db.Column(db.String(255)) #Teleop teleLow",
"requests from models import constants from requests.exceptions import HTTPError basedir = os.path.abspath(os.path.dirname(__file__)) app",
"teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specific data here #TODO: replace this",
"for a Match table. Only includes match number and team members of an",
"jsonify , url_for ) from flask_sqlalchemy import SQLAlchemy import os, requests from models",
"fouls = db.Column(db.Integer) generalNotes = db.Column(db.String(255)) class TeamPitScout(db.Model): ''' Database model for pit",
"db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes = db.Column(db.String(255)) #Teleop teleLow = db.Column(db.Integer) teleHigh =",
"match number and team members of an alliance. ''' matchNo = db.Column(db.Integer, primary_key=True,",
"db.Column(db.Boolean) levelClimbed = db.Column(db.Integer) endgameNotes = db.Column(db.String(255)) #generic game data brokenBot = db.Column(db.Boolean)",
"os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app) class",
"flask import ( Flask , render_template , redirect , request , jsonify ,",
"clutter. ''' teamNumber = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) teamName = db.Column(db.String(50), nullable=False) teamCity",
"team's performance in a match. ''' teamMatchId = db.Column(db.Integer, primary_key=True) #tuid matchNo =",
"#Endgame attemptedClimb = db.Column(db.Boolean) levelClimbed = db.Column(db.Integer) endgameNotes = db.Column(db.String(255)) #generic game data",
"telePickedUp = db.Column(db.Integer) didDefense = db.Column(db.Boolean) teleDefense = db.Column(db.Integer) teleNotes = db.Column(db.String(255)) #Endgame",
"data here #TODO: replace this with a def getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res",
"information for a team. ''' TeamPitScoutId = db.Column(db.Integer, primary_key=True) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'),",
", redirect , request , jsonify , url_for ) from flask_sqlalchemy import SQLAlchemy",
"= db.Column(db.Integer, nullable=False) blue_3 = db.Column(db.Integer, nullable=False) class TeamMatch(db.Model): ''' Database model for",
"db.Column(db.Integer, nullable=False) blue_2 = db.Column(db.Integer, nullable=False) blue_3 = db.Column(db.Integer, nullable=False) class TeamMatch(db.Model): '''",
"= db.Column(db.String(255)) #Endgame attemptedClimb = db.Column(db.Boolean) levelClimbed = db.Column(db.Integer) endgameNotes = db.Column(db.String(255)) #generic",
"for recording a team's performance in a match. ''' teamMatchId = db.Column(db.Integer, primary_key=True)",
"teleLow = db.Column(db.Integer) teleHigh = db.Column(db.Integer) telePickedUp = db.Column(db.Integer) didDefense = db.Column(db.Boolean) teleDefense",
"= db.Column(db.Integer, primary_key=True, nullable=False, unique=True) teamName = db.Column(db.String(50), nullable=False) teamCity = db.Column(db.String(50)) teamState",
"= db.Column(db.String(50), nullable=False) teamCity = db.Column(db.String(50)) teamState = db.Column(db.String(50)) class Match(db.Model): ''' Database",
"= db.Column(db.Integer, primary_key=True) #tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'),",
"Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app) class Team(db.Model): ''' Database",
"import constants from requests.exceptions import HTTPError basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI']",
"data brokenBot = db.Column(db.Boolean) noShow = db.Column(db.Boolean) fouls = db.Column(db.Integer) generalNotes = db.Column(db.String(255))",
"import os, requests from models import constants from requests.exceptions import HTTPError basedir =",
"SQLAlchemy(app) class Team(db.Model): ''' Database model for a Team table. Only includes rudimentary",
"Database model for a Team table. Only includes rudimentary team information to not",
"= res.json() info = tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] ) return info",
"= db.Column(db.Integer, nullable=False) blue_1 = db.Column(db.Integer, nullable=False) blue_2 = db.Column(db.Integer, nullable=False) blue_3 =",
"nullable=False) blue_3 = db.Column(db.Integer, nullable=False) class TeamMatch(db.Model): ''' Database model for recording a",
"team. ''' TeamPitScoutId = db.Column(db.Integer, primary_key=True) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert",
"res_json[\"results\"][0][\"state_prov\"], ] ) return info @app.route(\"/\") def index(): ''' Flask method for returning",
") from flask_sqlalchemy import SQLAlchemy import os, requests from models import constants from",
"primary_key=True) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specific data here #TODO: replace",
"= db.Column(db.Integer, primary_key=True) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specific data here",
"teamName = db.Column(db.String(50), nullable=False) teamCity = db.Column(db.String(50)) teamState = db.Column(db.String(50)) class Match(db.Model): '''",
"nullable=False) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specfic data here #Autonomous autoTaxi",
"matchNo = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) red_1 = db.Column(db.Integer, nullable=False) red_2 = db.Column(db.Integer,",
"with a def getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url) res_json = res.json()",
"res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] ) return info @app.route(\"/\") def index(): ''' Flask method for",
"nullable=False) teamCity = db.Column(db.String(50)) teamState = db.Column(db.String(50)) class Match(db.Model): ''' Database model for",
"= db.Column(db.Integer, primary_key=True, nullable=False, unique=True) red_1 = db.Column(db.Integer, nullable=False) red_2 = db.Column(db.Integer, nullable=False)",
"TeamPitScoutId = db.Column(db.Integer, primary_key=True) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specific data",
"nullable=False) #TODO: Insert game-specific data here #TODO: replace this with a def getTeamInfo(teamNo):",
"nullable=False) red_2 = db.Column(db.Integer, nullable=False) red_3 = db.Column(db.Integer, nullable=False) blue_1 = db.Column(db.Integer, nullable=False)",
"= db.Column(db.String(255)) #Teleop teleLow = db.Column(db.Integer) teleHigh = db.Column(db.Integer) telePickedUp = db.Column(db.Integer) didDefense",
"attemptedClimb = db.Column(db.Boolean) levelClimbed = db.Column(db.Integer) endgameNotes = db.Column(db.String(255)) #generic game data brokenBot",
"= db.Column(db.Integer) teleNotes = db.Column(db.String(255)) #Endgame attemptedClimb = db.Column(db.Boolean) levelClimbed = db.Column(db.Integer) endgameNotes",
"for pit scouting information for a team. ''' TeamPitScoutId = db.Column(db.Integer, primary_key=True) teamNo",
"for a team. ''' TeamPitScoutId = db.Column(db.Integer, primary_key=True) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False)",
"= db.Column(db.Integer) didDefense = db.Column(db.Boolean) teleDefense = db.Column(db.Integer) teleNotes = db.Column(db.String(255)) #Endgame attemptedClimb",
"render_template , redirect , request , jsonify , url_for ) from flask_sqlalchemy import",
"Flask , render_template , redirect , request , jsonify , url_for ) from",
"Database model for a Match table. Only includes match number and team members",
"''' Database model for recording a team's performance in a match. ''' teamMatchId",
"make data handling in Tableau easier autoLow = db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp",
"endgameNotes = db.Column(db.String(255)) #generic game data brokenBot = db.Column(db.Boolean) noShow = db.Column(db.Boolean) fouls",
"alliance. ''' matchNo = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) red_1 = db.Column(db.Integer, nullable=False) red_2",
"db.Column(db.Integer, nullable=False) red_2 = db.Column(db.Integer, nullable=False) red_3 = db.Column(db.Integer, nullable=False) blue_1 = db.Column(db.Integer,",
"teamMatchId = db.Column(db.Integer, primary_key=True) #tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo = db.Column(db.Integer,",
"primary_key=True) #tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO:",
"db.Column(db.Boolean) noShow = db.Column(db.Boolean) fouls = db.Column(db.Integer) generalNotes = db.Column(db.String(255)) class TeamPitScout(db.Model): '''",
"res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] ) return info @app.route(\"/\") def index(): ''' Flask method",
"db = SQLAlchemy(app) class Team(db.Model): ''' Database model for a Team table. Only",
"TeamMatch(db.Model): ''' Database model for recording a team's performance in a match. '''",
"db.Column(db.String(255)) #generic game data brokenBot = db.Column(db.Boolean) noShow = db.Column(db.Boolean) fouls = db.Column(db.Integer)",
"= db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specific data here #TODO: replace this with",
"matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specfic",
"teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specfic data here #Autonomous autoTaxi =",
"class Team(db.Model): ''' Database model for a Team table. Only includes rudimentary team",
"red_3 = db.Column(db.Integer, nullable=False) blue_1 = db.Column(db.Integer, nullable=False) blue_2 = db.Column(db.Integer, nullable=False) blue_3",
"db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specfic data here #Autonomous autoTaxi = db.Column(db.Integer) #this is",
"Only includes match number and team members of an alliance. ''' matchNo =",
"''' Database model for a Match table. Only includes match number and team",
"app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app) class Team(db.Model): ''' Database model for a Team table.",
"#Autonomous autoTaxi = db.Column(db.Integer) #this is an integer to make data handling in",
"in Tableau easier autoLow = db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes",
"db.Column(db.String(255)) class TeamPitScout(db.Model): ''' Database model for pit scouting information for a team.",
"pit scouting information for a team. ''' TeamPitScoutId = db.Column(db.Integer, primary_key=True) teamNo =",
"requests.get(url) res_json = res.json() info = tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] )",
"= db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specfic data",
"performance in a match. ''' teamMatchId = db.Column(db.Integer, primary_key=True) #tuid matchNo = db.Column(db.Integer,",
"HTTPError basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db",
"an alliance. ''' matchNo = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) red_1 = db.Column(db.Integer, nullable=False)",
"a def getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url) res_json = res.json() info",
"request , jsonify , url_for ) from flask_sqlalchemy import SQLAlchemy import os, requests",
"url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url) res_json = res.json() info = tuple( [",
"model for a Team table. Only includes rudimentary team information to not clutter.",
"teamState = db.Column(db.String(50)) class Match(db.Model): ''' Database model for a Match table. Only",
"data here #Autonomous autoTaxi = db.Column(db.Integer) #this is an integer to make data",
"app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app) class Team(db.Model): ''' Database model",
"= db.Column(db.String(255)) class TeamPitScout(db.Model): ''' Database model for pit scouting information for a",
"@app.route(\"/\") def index(): ''' Flask method for returning homepage. ''' return render_template(\"index.html\") @app.route(\"/scoutMatch/<int:matchNo><int:teamNo>\")",
"def getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url) res_json = res.json() info =",
"= db.Column(db.String(50)) class Match(db.Model): ''' Database model for a Match table. Only includes",
"db.Column(db.Integer) endgameNotes = db.Column(db.String(255)) #generic game data brokenBot = db.Column(db.Boolean) noShow = db.Column(db.Boolean)",
"basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db =",
"Only includes rudimentary team information to not clutter. ''' teamNumber = db.Column(db.Integer, primary_key=True,",
"= db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specfic data here #Autonomous autoTaxi = db.Column(db.Integer)",
"blue_1 = db.Column(db.Integer, nullable=False) blue_2 = db.Column(db.Integer, nullable=False) blue_3 = db.Column(db.Integer, nullable=False) class",
"match. ''' teamMatchId = db.Column(db.Integer, primary_key=True) #tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo",
"autoPickedUp = db.Column(db.Integer) autoNotes = db.Column(db.String(255)) #Teleop teleLow = db.Column(db.Integer) teleHigh = db.Column(db.Integer)",
"from flask_sqlalchemy import SQLAlchemy import os, requests from models import constants from requests.exceptions",
"here #TODO: replace this with a def getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res =",
"levelClimbed = db.Column(db.Integer) endgameNotes = db.Column(db.String(255)) #generic game data brokenBot = db.Column(db.Boolean) noShow",
"Flask method for returning homepage. ''' return render_template(\"index.html\") @app.route(\"/scoutMatch/<int:matchNo><int:teamNo>\") def scoutMatch(): return render_template(\"matchScout.html\")",
"= db.Column(db.Integer) autoNotes = db.Column(db.String(255)) #Teleop teleLow = db.Column(db.Integer) teleHigh = db.Column(db.Integer) telePickedUp",
"#generic game data brokenBot = db.Column(db.Boolean) noShow = db.Column(db.Boolean) fouls = db.Column(db.Integer) generalNotes",
"= requests.get(url) res_json = res.json() info = tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ]",
"from requests.exceptions import HTTPError basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir,",
"replace this with a def getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url) res_json",
"= db.Column(db.String(255)) #generic game data brokenBot = db.Column(db.Boolean) noShow = db.Column(db.Boolean) fouls =",
"is an integer to make data handling in Tableau easier autoLow = db.Column(db.Integer)",
"SQLAlchemy import os, requests from models import constants from requests.exceptions import HTTPError basedir",
"db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specfic data here",
"import ( Flask , render_template , redirect , request , jsonify , url_for",
"db.Column(db.Integer) autoNotes = db.Column(db.String(255)) #Teleop teleLow = db.Column(db.Integer) teleHigh = db.Column(db.Integer) telePickedUp =",
"blue_3 = db.Column(db.Integer, nullable=False) class TeamMatch(db.Model): ''' Database model for recording a team's",
") return info @app.route(\"/\") def index(): ''' Flask method for returning homepage. '''",
", render_template , redirect , request , jsonify , url_for ) from flask_sqlalchemy",
"Database model for recording a team's performance in a match. ''' teamMatchId =",
"= db.Column(db.Integer) endgameNotes = db.Column(db.String(255)) #generic game data brokenBot = db.Column(db.Boolean) noShow =",
"TeamPitScout(db.Model): ''' Database model for pit scouting information for a team. ''' TeamPitScoutId",
"red_2 = db.Column(db.Integer, nullable=False) red_3 = db.Column(db.Integer, nullable=False) blue_1 = db.Column(db.Integer, nullable=False) blue_2",
"#this is an integer to make data handling in Tableau easier autoLow =",
"url_for ) from flask_sqlalchemy import SQLAlchemy import os, requests from models import constants",
"os, requests from models import constants from requests.exceptions import HTTPError basedir = os.path.abspath(os.path.dirname(__file__))",
"red_1 = db.Column(db.Integer, nullable=False) red_2 = db.Column(db.Integer, nullable=False) red_3 = db.Column(db.Integer, nullable=False) blue_1",
"db.Column(db.Integer) didDefense = db.Column(db.Boolean) teleDefense = db.Column(db.Integer) teleNotes = db.Column(db.String(255)) #Endgame attemptedClimb =",
"integer to make data handling in Tableau easier autoLow = db.Column(db.Integer) autoHigh =",
"tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] ) return info @app.route(\"/\") def index(): '''",
"Team(db.Model): ''' Database model for a Team table. Only includes rudimentary team information",
"in a match. ''' teamMatchId = db.Column(db.Integer, primary_key=True) #tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'),",
"members of an alliance. ''' matchNo = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) red_1 =",
"db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specific data here #TODO: replace this with a",
"nullable=False) red_3 = db.Column(db.Integer, nullable=False) blue_1 = db.Column(db.Integer, nullable=False) blue_2 = db.Column(db.Integer, nullable=False)",
"db.Column(db.Integer, primary_key=True, nullable=False, unique=True) red_1 = db.Column(db.Integer, nullable=False) red_2 = db.Column(db.Integer, nullable=False) red_3",
"requests.exceptions import HTTPError basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db')",
"data handling in Tableau easier autoLow = db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp =",
"db.Column(db.Integer, nullable=False) red_3 = db.Column(db.Integer, nullable=False) blue_1 = db.Column(db.Integer, nullable=False) blue_2 = db.Column(db.Integer,",
"teamNumber = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) teamName = db.Column(db.String(50), nullable=False) teamCity = db.Column(db.String(50))",
"game data brokenBot = db.Column(db.Boolean) noShow = db.Column(db.Boolean) fouls = db.Column(db.Integer) generalNotes =",
"= db.Column(db.Boolean) teleDefense = db.Column(db.Integer) teleNotes = db.Column(db.String(255)) #Endgame attemptedClimb = db.Column(db.Boolean) levelClimbed",
"res_json = res.json() info = tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] ) return",
"def index(): ''' Flask method for returning homepage. ''' return render_template(\"index.html\") @app.route(\"/scoutMatch/<int:matchNo><int:teamNo>\") def",
"= db.Column(db.Integer, nullable=False) blue_2 = db.Column(db.Integer, nullable=False) blue_3 = db.Column(db.Integer, nullable=False) class TeamMatch(db.Model):",
"''' matchNo = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) red_1 = db.Column(db.Integer, nullable=False) red_2 =",
"= db.Column(db.Integer, nullable=False) red_2 = db.Column(db.Integer, nullable=False) red_3 = db.Column(db.Integer, nullable=False) blue_1 =",
"a team. ''' TeamPitScoutId = db.Column(db.Integer, primary_key=True) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO:",
"db.Column(db.Integer, nullable=False) blue_1 = db.Column(db.Integer, nullable=False) blue_2 = db.Column(db.Integer, nullable=False) blue_3 = db.Column(db.Integer,",
"Insert game-specfic data here #Autonomous autoTaxi = db.Column(db.Integer) #this is an integer to",
"brokenBot = db.Column(db.Boolean) noShow = db.Column(db.Boolean) fouls = db.Column(db.Integer) generalNotes = db.Column(db.String(255)) class",
"info @app.route(\"/\") def index(): ''' Flask method for returning homepage. ''' return render_template(\"index.html\")",
"db.Column(db.Integer) telePickedUp = db.Column(db.Integer) didDefense = db.Column(db.Boolean) teleDefense = db.Column(db.Integer) teleNotes = db.Column(db.String(255))",
"= SQLAlchemy(app) class Team(db.Model): ''' Database model for a Team table. Only includes",
"db.Column(db.String(50), nullable=False) teamCity = db.Column(db.String(50)) teamState = db.Column(db.String(50)) class Match(db.Model): ''' Database model",
"unique=True) red_1 = db.Column(db.Integer, nullable=False) red_2 = db.Column(db.Integer, nullable=False) red_3 = db.Column(db.Integer, nullable=False)",
"model for pit scouting information for a team. ''' TeamPitScoutId = db.Column(db.Integer, primary_key=True)",
"getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url) res_json = res.json() info = tuple(",
"db.Column(db.Integer) #this is an integer to make data handling in Tableau easier autoLow",
"nullable=False, unique=True) red_1 = db.Column(db.Integer, nullable=False) red_2 = db.Column(db.Integer, nullable=False) red_3 = db.Column(db.Integer,",
"nullable=False) blue_1 = db.Column(db.Integer, nullable=False) blue_2 = db.Column(db.Integer, nullable=False) blue_3 = db.Column(db.Integer, nullable=False)",
"for a Team table. Only includes rudimentary team information to not clutter. '''",
"of an alliance. ''' matchNo = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) red_1 = db.Column(db.Integer,",
"class TeamPitScout(db.Model): ''' Database model for pit scouting information for a team. '''",
"return info @app.route(\"/\") def index(): ''' Flask method for returning homepage. ''' return",
"from models import constants from requests.exceptions import HTTPError basedir = os.path.abspath(os.path.dirname(__file__)) app =",
"flask_sqlalchemy import SQLAlchemy import os, requests from models import constants from requests.exceptions import",
"table. Only includes rudimentary team information to not clutter. ''' teamNumber = db.Column(db.Integer,",
"Match table. Only includes match number and team members of an alliance. '''",
", request , jsonify , url_for ) from flask_sqlalchemy import SQLAlchemy import os,",
"Database model for pit scouting information for a team. ''' TeamPitScoutId = db.Column(db.Integer,",
"Team table. Only includes rudimentary team information to not clutter. ''' teamNumber =",
"team information to not clutter. ''' teamNumber = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) teamName",
"#tuid matchNo = db.Column(db.Integer, db.ForeignKey('Match.matchNo'), nullable=False) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert",
"autoLow = db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes = db.Column(db.String(255)) #Teleop",
"#TODO: replace this with a def getTeamInfo(teamNo): url = f\"{constants.tba_base}{teamNo}.json?key={constants.tba_key}\" res = requests.get(url)",
"info = tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] ) return info @app.route(\"/\") def",
"table. Only includes match number and team members of an alliance. ''' matchNo",
"noShow = db.Column(db.Boolean) fouls = db.Column(db.Integer) generalNotes = db.Column(db.String(255)) class TeamPitScout(db.Model): ''' Database",
"blue_2 = db.Column(db.Integer, nullable=False) blue_3 = db.Column(db.Integer, nullable=False) class TeamMatch(db.Model): ''' Database model",
"nullable=False, unique=True) teamName = db.Column(db.String(50), nullable=False) teamCity = db.Column(db.String(50)) teamState = db.Column(db.String(50)) class",
"to make data handling in Tableau easier autoLow = db.Column(db.Integer) autoHigh = db.Column(db.Integer)",
"db.Column(db.Integer, primary_key=True, nullable=False, unique=True) teamName = db.Column(db.String(50), nullable=False) teamCity = db.Column(db.String(50)) teamState =",
"here #Autonomous autoTaxi = db.Column(db.Integer) #this is an integer to make data handling",
"teleDefense = db.Column(db.Integer) teleNotes = db.Column(db.String(255)) #Endgame attemptedClimb = db.Column(db.Boolean) levelClimbed = db.Column(db.Integer)",
"rudimentary team information to not clutter. ''' teamNumber = db.Column(db.Integer, primary_key=True, nullable=False, unique=True)",
"db.Column(db.Integer, primary_key=True) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specific data here #TODO:",
", jsonify , url_for ) from flask_sqlalchemy import SQLAlchemy import os, requests from",
"= 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app) class Team(db.Model): ''' Database model for",
"'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app) class Team(db.Model): ''' Database model for a Team",
"''' Flask method for returning homepage. ''' return render_template(\"index.html\") @app.route(\"/scoutMatch/<int:matchNo><int:teamNo>\") def scoutMatch(): return",
"class TeamMatch(db.Model): ''' Database model for recording a team's performance in a match.",
"a Match table. Only includes match number and team members of an alliance.",
"teamCity = db.Column(db.String(50)) teamState = db.Column(db.String(50)) class Match(db.Model): ''' Database model for a",
"teleHigh = db.Column(db.Integer) telePickedUp = db.Column(db.Integer) didDefense = db.Column(db.Boolean) teleDefense = db.Column(db.Integer) teleNotes",
"= tuple( [ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] ) return info @app.route(\"/\") def index():",
"= db.Column(db.Boolean) fouls = db.Column(db.Integer) generalNotes = db.Column(db.String(255)) class TeamPitScout(db.Model): ''' Database model",
"scouting information for a team. ''' TeamPitScoutId = db.Column(db.Integer, primary_key=True) teamNo = db.Column(db.Integer,",
"not clutter. ''' teamNumber = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) teamName = db.Column(db.String(50), nullable=False)",
"= db.Column(db.Integer) #this is an integer to make data handling in Tableau easier",
"primary_key=True, nullable=False, unique=True) teamName = db.Column(db.String(50), nullable=False) teamCity = db.Column(db.String(50)) teamState = db.Column(db.String(50))",
"#TODO: Insert game-specific data here #TODO: replace this with a def getTeamInfo(teamNo): url",
"''' Database model for a Team table. Only includes rudimentary team information to",
"model for a Match table. Only includes match number and team members of",
"an integer to make data handling in Tableau easier autoLow = db.Column(db.Integer) autoHigh",
"''' Database model for pit scouting information for a team. ''' TeamPitScoutId =",
"Insert game-specific data here #TODO: replace this with a def getTeamInfo(teamNo): url =",
"db.Column(db.Integer) generalNotes = db.Column(db.String(255)) class TeamPitScout(db.Model): ''' Database model for pit scouting information",
"from flask import ( Flask , render_template , redirect , request , jsonify",
"= db.Column(db.Boolean) noShow = db.Column(db.Boolean) fouls = db.Column(db.Integer) generalNotes = db.Column(db.String(255)) class TeamPitScout(db.Model):",
"db.Column(db.Integer) teleHigh = db.Column(db.Integer) telePickedUp = db.Column(db.Integer) didDefense = db.Column(db.Boolean) teleDefense = db.Column(db.Integer)",
"db.Column(db.String(50)) class Match(db.Model): ''' Database model for a Match table. Only includes match",
"= db.Column(db.Integer, nullable=False) red_3 = db.Column(db.Integer, nullable=False) blue_1 = db.Column(db.Integer, nullable=False) blue_2 =",
"and team members of an alliance. ''' matchNo = db.Column(db.Integer, primary_key=True, nullable=False, unique=True)",
"= db.Column(db.Integer) telePickedUp = db.Column(db.Integer) didDefense = db.Column(db.Boolean) teleDefense = db.Column(db.Integer) teleNotes =",
"nullable=False) class TeamMatch(db.Model): ''' Database model for recording a team's performance in a",
"= db.Column(db.Boolean) levelClimbed = db.Column(db.Integer) endgameNotes = db.Column(db.String(255)) #generic game data brokenBot =",
"db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specific data here #TODO: replace this with a def",
"db.Column(db.Integer, nullable=False) class TeamMatch(db.Model): ''' Database model for recording a team's performance in",
"''' TeamPitScoutId = db.Column(db.Integer, primary_key=True) teamNo = db.Column(db.Integer, db.ForeignKey('Team.teamNumber'), nullable=False) #TODO: Insert game-specific",
"team members of an alliance. ''' matchNo = db.Column(db.Integer, primary_key=True, nullable=False, unique=True) red_1",
"autoHigh = db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes = db.Column(db.String(255)) #Teleop teleLow = db.Column(db.Integer)",
"didDefense = db.Column(db.Boolean) teleDefense = db.Column(db.Integer) teleNotes = db.Column(db.String(255)) #Endgame attemptedClimb = db.Column(db.Boolean)",
"= os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, 'data/ScoutingData.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlchemy(app)",
"db.Column(db.Boolean) teleDefense = db.Column(db.Integer) teleNotes = db.Column(db.String(255)) #Endgame attemptedClimb = db.Column(db.Boolean) levelClimbed =",
"= db.Column(db.Integer) generalNotes = db.Column(db.String(255)) class TeamPitScout(db.Model): ''' Database model for pit scouting",
"Match(db.Model): ''' Database model for a Match table. Only includes match number and",
"nullable=False) blue_2 = db.Column(db.Integer, nullable=False) blue_3 = db.Column(db.Integer, nullable=False) class TeamMatch(db.Model): ''' Database",
"= db.Column(db.Integer, nullable=False) class TeamMatch(db.Model): ''' Database model for recording a team's performance",
"model for recording a team's performance in a match. ''' teamMatchId = db.Column(db.Integer,",
"db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes = db.Column(db.String(255)) #Teleop teleLow =",
"generalNotes = db.Column(db.String(255)) class TeamPitScout(db.Model): ''' Database model for pit scouting information for",
"] ) return info @app.route(\"/\") def index(): ''' Flask method for returning homepage.",
"number and team members of an alliance. ''' matchNo = db.Column(db.Integer, primary_key=True, nullable=False,",
"[ res_json[\"results\"][0][\"nickname\"], res_json[\"results\"][0][\"city\"], res_json[\"results\"][0][\"state_prov\"], ] ) return info @app.route(\"/\") def index(): ''' Flask",
"#Teleop teleLow = db.Column(db.Integer) teleHigh = db.Column(db.Integer) telePickedUp = db.Column(db.Integer) didDefense = db.Column(db.Boolean)",
"Tableau easier autoLow = db.Column(db.Integer) autoHigh = db.Column(db.Integer) autoPickedUp = db.Column(db.Integer) autoNotes =",
"a team's performance in a match. ''' teamMatchId = db.Column(db.Integer, primary_key=True) #tuid matchNo",
"recording a team's performance in a match. ''' teamMatchId = db.Column(db.Integer, primary_key=True) #tuid",
"a Team table. Only includes rudimentary team information to not clutter. ''' teamNumber"
] |
[
"TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10) ts = set_table_service() if get_table_service() == False: ts.create_table(table_name)",
"= csv.DictReader(csvFile) rows = [row for row in reader] for row in rows:",
"'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10) ts",
"return ts.exists(table_name,10) ts = set_table_service() if get_table_service() == False: ts.create_table(table_name) csvFile = open(file_name,",
"set_table_service(): return TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10) ts = set_table_service() if get_table_service() ==",
"= [row for row in reader] for row in rows: index = rows.index(row)",
"= '' accoun_key = '' table_name = 'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service():",
"def set_table_service(): return TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10) ts = set_table_service() if get_table_service()",
"from azure.cosmosdb.table.models import Entity import csv account_name = '' accoun_key = '' table_name",
"('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile) rows = [row for row in reader] for row",
"= 'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10)",
"azure.cosmosdb.table.tableservice import TableService from azure.cosmosdb.table.models import Entity import csv account_name = '' accoun_key",
"'' table_name = 'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return TableService(account_name,accoun_key) def get_table_service():",
"Entity import csv account_name = '' accoun_key = '' table_name = 'projectx' file_name",
"def get_table_service(): return ts.exists(table_name,10) ts = set_table_service() if get_table_service() == False: ts.create_table(table_name) csvFile",
"get_table_service(): return ts.exists(table_name,10) ts = set_table_service() if get_table_service() == False: ts.create_table(table_name) csvFile =",
"ts = set_table_service() if get_table_service() == False: ts.create_table(table_name) csvFile = open(file_name, 'r') field_names",
"open(file_name, 'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile) rows = [row for row",
"return TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10) ts = set_table_service() if get_table_service() == False:",
"ts.exists(table_name,10) ts = set_table_service() if get_table_service() == False: ts.create_table(table_name) csvFile = open(file_name, 'r')",
"import csv account_name = '' accoun_key = '' table_name = 'projectx' file_name =",
"= set_table_service() if get_table_service() == False: ts.create_table(table_name) csvFile = open(file_name, 'r') field_names =",
"account_name = '' accoun_key = '' table_name = 'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def",
"accoun_key = '' table_name = 'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return TableService(account_name,accoun_key)",
"azure.cosmosdb.table.models import Entity import csv account_name = '' accoun_key = '' table_name =",
"= '' table_name = 'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return TableService(account_name,accoun_key) def",
"ts.create_table(table_name) csvFile = open(file_name, 'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile) rows =",
"'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile) rows = [row for row in",
"TableService from azure.cosmosdb.table.models import Entity import csv account_name = '' accoun_key = ''",
"file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10) ts =",
"= ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile) rows = [row for row in reader] for",
"table_name = 'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return TableService(account_name,accoun_key) def get_table_service(): return",
"<gh_stars>0 from azure.cosmosdb.table.tableservice import TableService from azure.cosmosdb.table.models import Entity import csv account_name =",
"csv account_name = '' accoun_key = '' table_name = 'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv'",
"= 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10) ts = set_table_service()",
"import TableService from azure.cosmosdb.table.models import Entity import csv account_name = '' accoun_key =",
"csv.DictReader(csvFile) rows = [row for row in reader] for row in rows: index",
"field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile) rows = [row for row in reader]",
"[row for row in reader] for row in rows: index = rows.index(row) ts.insert_or_replace_entity(table_name,row)",
"'' accoun_key = '' table_name = 'projectx' file_name = 'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return",
"from azure.cosmosdb.table.tableservice import TableService from azure.cosmosdb.table.models import Entity import csv account_name = ''",
"'C:\\\\Users\\\\admin\\\\Downloads\\\\meta.csv' def set_table_service(): return TableService(account_name,accoun_key) def get_table_service(): return ts.exists(table_name,10) ts = set_table_service() if",
"False: ts.create_table(table_name) csvFile = open(file_name, 'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile) rows",
"rows = [row for row in reader] for row in rows: index =",
"import Entity import csv account_name = '' accoun_key = '' table_name = 'projectx'",
"= open(file_name, 'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile) rows = [row for",
"set_table_service() if get_table_service() == False: ts.create_table(table_name) csvFile = open(file_name, 'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority')",
"reader = csv.DictReader(csvFile) rows = [row for row in reader] for row in",
"csvFile = open(file_name, 'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile) rows = [row",
"if get_table_service() == False: ts.create_table(table_name) csvFile = open(file_name, 'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader",
"get_table_service() == False: ts.create_table(table_name) csvFile = open(file_name, 'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader =",
"== False: ts.create_table(table_name) csvFile = open(file_name, 'r') field_names = ('PartitionKey','RowKey','TimeStamp','UpdatedOn','ID','Priority') reader = csv.DictReader(csvFile)"
] |
[
"from tests.base import RDMATestCase from pyverbs.mr import MR import pyverbs.enums as e class",
"create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self): self.mr",
"client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn) return client, server def",
"traffic, xrc_traffic from tests.base import RDMATestCase from pyverbs.mr import MR import pyverbs.enums as",
"MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size,",
"class RoXRC(XRCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase):",
"test_ro_ud_traffic(self): client, server = self.create_players('ud') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_xrc_traffic(self): client,",
"+ self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size,",
"server.qpn) server.pre_run(client.psn, client.qpn) return client, server def test_ro_rc_traffic(self): client, server = self.create_players('rc') traffic(client,",
"'xrc': RoXRC} def create_players(self, qp_type): client = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server = self.qp_dict[qp_type](self.dev_name,",
"else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn) return client, server def test_ro_rc_traffic(self): client, server =",
"def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def setUp(self):",
"= MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self): self.mr = MR(self.pd,",
"e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE |",
"client, server = self.create_players('rc') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_ud_traffic(self): client, server",
"pyverbs.mr import MR import pyverbs.enums as e class RoUD(UDResources): def create_mr(self): self.mr =",
"from tests.utils import traffic, xrc_traffic from tests.base import RDMATestCase from pyverbs.mr import MR",
"RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase, self).setUp() self.iters = 100 self.qp_dict = {'rc': RoRC, 'ud':",
"traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_xrc_traffic(self): client, server = self.create_players('xrc') xrc_traffic(client, server)",
"server = self.create_players('ud') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_xrc_traffic(self): client, server =",
"self.ib_port, self.gid_index) if qp_type == 'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn, server.qpn)",
"self.ib_port, self.gid_index) server = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if qp_type == 'xrc': client.pre_run(server.psns, server.qps_num)",
"= self.create_players('ud') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_xrc_traffic(self): client, server = self.create_players('xrc')",
"RCResources, UDResources, XRCResources from tests.utils import traffic, xrc_traffic from tests.base import RDMATestCase from",
"import MR import pyverbs.enums as e class RoUD(UDResources): def create_mr(self): self.mr = MR(self.pd,",
"self.mr = MR(self.pd, self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def create_mr(self):",
"= MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase, self).setUp() self.iters",
"self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if qp_type == 'xrc': client.pre_run(server.psns,",
"= self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if qp_type == 'xrc':",
"server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn) return client, server def test_ro_rc_traffic(self): client,",
"def test_ro_ud_traffic(self): client, server = self.create_players('ud') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_xrc_traffic(self):",
"create_mr(self): self.mr = MR(self.pd, self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def",
"class RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase, self).setUp() self.iters = 100 self.qp_dict = {'rc': RoRC,",
"self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase, self).setUp()",
"test_ro_rc_traffic(self): client, server = self.create_players('rc') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_ud_traffic(self): client,",
"| e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING)",
"client.qpn) return client, server def test_ro_rc_traffic(self): client, server = self.create_players('rc') traffic(client, server, self.iters,",
"client.qps_num) else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn) return client, server def test_ro_rc_traffic(self): client, server",
"self.create_players('rc') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_ud_traffic(self): client, server = self.create_players('ud') traffic(client,",
"tests.base import RCResources, UDResources, XRCResources from tests.utils import traffic, xrc_traffic from tests.base import",
"self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE",
"{'rc': RoRC, 'ud': RoUD, 'xrc': RoXRC} def create_players(self, qp_type): client = self.qp_dict[qp_type](self.dev_name, self.ib_port,",
"self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if qp_type == 'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn,",
"from tests.base import RCResources, UDResources, XRCResources from tests.utils import traffic, xrc_traffic from tests.base",
"class RoUD(UDResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING)",
"self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE",
"self.gid_index) server = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if qp_type == 'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns,",
"MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase, self).setUp() self.iters =",
"self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self): self.mr =",
"def test_ro_rc_traffic(self): client, server = self.create_players('rc') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_ud_traffic(self):",
"client, server = self.create_players('ud') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_xrc_traffic(self): client, server",
"RoXRC} def create_players(self, qp_type): client = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server = self.qp_dict[qp_type](self.dev_name, self.ib_port,",
"self.gid_index, self.ib_port) def test_ro_ud_traffic(self): client, server = self.create_players('ud') traffic(client, server, self.iters, self.gid_index, self.ib_port)",
"import RDMATestCase from pyverbs.mr import MR import pyverbs.enums as e class RoUD(UDResources): def",
"UDResources, XRCResources from tests.utils import traffic, xrc_traffic from tests.base import RDMATestCase from pyverbs.mr",
"as e class RoUD(UDResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE",
"pyverbs.enums as e class RoUD(UDResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size + self.GRH_SIZE,",
"server, self.iters, self.gid_index, self.ib_port) def test_ro_ud_traffic(self): client, server = self.create_players('ud') traffic(client, server, self.iters,",
"'ud': RoUD, 'xrc': RoXRC} def create_players(self, qp_type): client = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server",
"create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase,",
"tests.base import RDMATestCase from pyverbs.mr import MR import pyverbs.enums as e class RoUD(UDResources):",
"RDMATestCase from pyverbs.mr import MR import pyverbs.enums as e class RoUD(UDResources): def create_mr(self):",
"e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase, self).setUp() self.iters = 100 self.qp_dict",
"100 self.qp_dict = {'rc': RoRC, 'ud': RoUD, 'xrc': RoXRC} def create_players(self, qp_type): client",
"import RCResources, UDResources, XRCResources from tests.utils import traffic, xrc_traffic from tests.base import RDMATestCase",
"server = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if qp_type == 'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num)",
"e class RoUD(UDResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE |",
"client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn) return client, server def test_ro_rc_traffic(self): client, server = self.create_players('rc')",
"= self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if qp_type == 'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num) else:",
"self).setUp() self.iters = 100 self.qp_dict = {'rc': RoRC, 'ud': RoUD, 'xrc': RoXRC} def",
"server = self.create_players('rc') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_ud_traffic(self): client, server =",
"import pyverbs.enums as e class RoUD(UDResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size +",
"def setUp(self): super(RoTestCase, self).setUp() self.iters = 100 self.qp_dict = {'rc': RoRC, 'ud': RoUD,",
"| e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase, self).setUp() self.iters = 100 self.qp_dict =",
"qp_type == 'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn) return",
"RoUD, 'xrc': RoXRC} def create_players(self, qp_type): client = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server =",
"if qp_type == 'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn)",
"== 'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn) return client,",
"RoUD(UDResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class",
"e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class",
"<filename>mlnx-ofed-4.9-driver/rdma-core-50mlnx1/tests/test_relaxed_ordering.py from tests.base import RCResources, UDResources, XRCResources from tests.utils import traffic, xrc_traffic from",
"self.qp_dict = {'rc': RoRC, 'ud': RoUD, 'xrc': RoXRC} def create_players(self, qp_type): client =",
"self.gid_index) if qp_type == 'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn,",
"class RoRC(RCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources):",
"self.ib_port) def test_ro_ud_traffic(self): client, server = self.create_players('ud') traffic(client, server, self.iters, self.gid_index, self.ib_port) def",
"def create_players(self, qp_type): client = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index)",
"def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def create_mr(self):",
"setUp(self): super(RoTestCase, self).setUp() self.iters = 100 self.qp_dict = {'rc': RoRC, 'ud': RoUD, 'xrc':",
"| e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING)",
"tests.utils import traffic, xrc_traffic from tests.base import RDMATestCase from pyverbs.mr import MR import",
"e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE |",
"self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase, self).setUp() self.iters = 100",
"client = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if qp_type ==",
"MR(self.pd, self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def create_mr(self): self.mr =",
"import traffic, xrc_traffic from tests.base import RDMATestCase from pyverbs.mr import MR import pyverbs.enums",
"MR import pyverbs.enums as e class RoUD(UDResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size",
"self.create_players('ud') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_xrc_traffic(self): client, server = self.create_players('xrc') xrc_traffic(client,",
"from pyverbs.mr import MR import pyverbs.enums as e class RoUD(UDResources): def create_mr(self): self.mr",
"client, server def test_ro_rc_traffic(self): client, server = self.create_players('rc') traffic(client, server, self.iters, self.gid_index, self.ib_port)",
"e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class",
"XRCResources from tests.utils import traffic, xrc_traffic from tests.base import RDMATestCase from pyverbs.mr import",
"qp_type): client = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if qp_type",
"traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_ud_traffic(self): client, server = self.create_players('ud') traffic(client, server,",
"server.pre_run(client.psn, client.qpn) return client, server def test_ro_rc_traffic(self): client, server = self.create_players('rc') traffic(client, server,",
"= MR(self.pd, self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def create_mr(self): self.mr",
"create_players(self, qp_type): client = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) server = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index) if",
"server.qps_num) server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn) return client, server def test_ro_rc_traffic(self):",
"server def test_ro_rc_traffic(self): client, server = self.create_players('rc') traffic(client, server, self.iters, self.gid_index, self.ib_port) def",
"self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources): def create_mr(self): self.mr = MR(self.pd,",
"super(RoTestCase, self).setUp() self.iters = 100 self.qp_dict = {'rc': RoRC, 'ud': RoUD, 'xrc': RoXRC}",
"self.iters, self.gid_index, self.ib_port) def test_ro_ud_traffic(self): client, server = self.create_players('ud') traffic(client, server, self.iters, self.gid_index,",
"RoXRC(XRCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def",
"= self.create_players('rc') traffic(client, server, self.iters, self.gid_index, self.ib_port) def test_ro_ud_traffic(self): client, server = self.create_players('ud')",
"= {'rc': RoRC, 'ud': RoUD, 'xrc': RoXRC} def create_players(self, qp_type): client = self.qp_dict[qp_type](self.dev_name,",
"return client, server def test_ro_rc_traffic(self): client, server = self.create_players('rc') traffic(client, server, self.iters, self.gid_index,",
"= 100 self.qp_dict = {'rc': RoRC, 'ud': RoUD, 'xrc': RoXRC} def create_players(self, qp_type):",
"e.IBV_ACCESS_RELAXED_ORDERING) class RoTestCase(RDMATestCase): def setUp(self): super(RoTestCase, self).setUp() self.iters = 100 self.qp_dict = {'rc':",
"RoRC(RCResources): def create_mr(self): self.mr = MR(self.pd, self.msg_size, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoXRC(XRCResources): def",
"RoRC, 'ud': RoUD, 'xrc': RoXRC} def create_players(self, qp_type): client = self.qp_dict[qp_type](self.dev_name, self.ib_port, self.gid_index)",
"def create_mr(self): self.mr = MR(self.pd, self.msg_size + self.GRH_SIZE, e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_RELAXED_ORDERING) class RoRC(RCResources):",
"'xrc': client.pre_run(server.psns, server.qps_num) server.pre_run(client.psns, client.qps_num) else: client.pre_run(server.psn, server.qpn) server.pre_run(client.psn, client.qpn) return client, server",
"xrc_traffic from tests.base import RDMATestCase from pyverbs.mr import MR import pyverbs.enums as e",
"self.iters = 100 self.qp_dict = {'rc': RoRC, 'ud': RoUD, 'xrc': RoXRC} def create_players(self,"
] |
[
"document import preprocess import argparse import pdb def get_summary(input_text): pr = preprocess.Preprocess() original_text",
"pr = preprocess.Preprocess() original_text = input_text preprocessed_text = pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences",
"preprocess.Preprocess() original_text = input_text preprocessed_text = pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text)",
"import argparse import pdb def get_summary(input_text): pr = preprocess.Preprocess() original_text = input_text preprocessed_text",
"vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input']) pr = preprocess.Preprocess() input_text = pr.get_article_content(input_path)",
"\"output\" ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to input text document\") #ap.add_argument(\"-o\", \"--output\",",
"Summarized Document\") args = vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input']) pr =",
"#pdb.set_trace() with open(output_path,'w' ,encoding = \"utf-8\") as f: f.write(summary) if __name__ == \"__main__\":",
"document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to output Summarized Document\") args = vars(ap.parse_args()) input_path =",
"input_text preprocessed_text = pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text)",
"pickle, re import document import preprocess import argparse import pdb def get_summary(input_text): pr",
"Document\") args = vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input']) pr = preprocess.Preprocess()",
"= vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input']) pr = preprocess.Preprocess() input_text =",
"= pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc = document.Doc( original_text =",
"doc.summarize() return summary def run(): input_dir = \"input\" output_dir = \"output\" ap =",
"text document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to output Summarized Document\") args = vars(ap.parse_args()) input_path",
"= sentences, paragraphs = paragraphs ,para_sent_list = para_sent_list ,tokenized_word_sentences = tokenized_word_sentences) summary =",
"os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input']) pr = preprocess.Preprocess() input_text = pr.get_article_content(input_path) summary = get_summary(input_text)",
"preprocessed_text = pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list",
"<filename>run_files.py<gh_stars>0 import os, pickle, re import document import preprocess import argparse import pdb",
"get_summary(input_text) #pdb.set_trace() with open(output_path,'w' ,encoding = \"utf-8\") as f: f.write(summary) if __name__ ==",
"output_path = os.path.join(output_dir,args['input']) pr = preprocess.Preprocess() input_text = pr.get_article_content(input_path) summary = get_summary(input_text) #pdb.set_trace()",
"def run(): input_dir = \"input\" output_dir = \"output\" ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\",",
"os.path.join(output_dir,args['input']) pr = preprocess.Preprocess() input_text = pr.get_article_content(input_path) summary = get_summary(input_text) #pdb.set_trace() with open(output_path,'w'",
"= tokenized_word_sentences) summary = doc.summarize() return summary def run(): input_dir = \"input\" output_dir",
"preprocess import argparse import pdb def get_summary(input_text): pr = preprocess.Preprocess() original_text = input_text",
"pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc = document.Doc( original_text = original_text",
"preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences = sentences, paragraphs = paragraphs ,para_sent_list = para_sent_list ,tokenized_word_sentences",
"paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc = document.Doc( original_text",
"original_text , original_sentences = original_sentences , preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences = sentences, paragraphs",
"= doc.summarize() return summary def run(): input_dir = \"input\" output_dir = \"output\" ap",
"input text document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to output Summarized Document\") args = vars(ap.parse_args())",
"input_text = pr.get_article_content(input_path) summary = get_summary(input_text) #pdb.set_trace() with open(output_path,'w' ,encoding = \"utf-8\") as",
"= preprocess.Preprocess() original_text = input_text preprocessed_text = pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences =",
"#ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to output Summarized Document\") args = vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input'])",
"pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs)",
"= \"input\" output_dir = \"output\" ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to input",
"\"--output\", required=True,help=\"path to output Summarized Document\") args = vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input']) output_path",
"= paragraphs ,para_sent_list = para_sent_list ,tokenized_word_sentences = tokenized_word_sentences) summary = doc.summarize() return summary",
"with open(output_path,'w' ,encoding = \"utf-8\") as f: f.write(summary) if __name__ == \"__main__\": run()",
"summary def run(): input_dir = \"input\" output_dir = \"output\" ap = argparse.ArgumentParser() ap.add_argument(\"-i\",",
"summary = get_summary(input_text) #pdb.set_trace() with open(output_path,'w' ,encoding = \"utf-8\") as f: f.write(summary) if",
"to input text document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to output Summarized Document\") args =",
"def get_summary(input_text): pr = preprocess.Preprocess() original_text = input_text preprocessed_text = pr.get_clean_article(input_text) sentences =",
"re import document import preprocess import argparse import pdb def get_summary(input_text): pr =",
"= pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list =",
"tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc = document.Doc( original_text = original_text , original_sentences = original_sentences",
"= os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input']) pr = preprocess.Preprocess() input_text = pr.get_article_content(input_path) summary =",
"para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc = document.Doc( original_text = original_text ,",
"get_summary(input_text): pr = preprocess.Preprocess() original_text = input_text preprocessed_text = pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text)",
"tokenized_word_sentences) summary = doc.summarize() return summary def run(): input_dir = \"input\" output_dir =",
"= get_summary(input_text) #pdb.set_trace() with open(output_path,'w' ,encoding = \"utf-8\") as f: f.write(summary) if __name__",
"pr = preprocess.Preprocess() input_text = pr.get_article_content(input_path) summary = get_summary(input_text) #pdb.set_trace() with open(output_path,'w' ,encoding",
"required=True,help=\"path to output Summarized Document\") args = vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input']) output_path =",
"summary = doc.summarize() return summary def run(): input_dir = \"input\" output_dir = \"output\"",
"= os.path.join(output_dir,args['input']) pr = preprocess.Preprocess() input_text = pr.get_article_content(input_path) summary = get_summary(input_text) #pdb.set_trace() with",
"import document import preprocess import argparse import pdb def get_summary(input_text): pr = preprocess.Preprocess()",
"pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc = document.Doc(",
"os, pickle, re import document import preprocess import argparse import pdb def get_summary(input_text):",
"pdb def get_summary(input_text): pr = preprocess.Preprocess() original_text = input_text preprocessed_text = pr.get_clean_article(input_text) sentences",
"sentences = pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences",
"ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to input text document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to output Summarized",
", original_sentences = original_sentences , preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences = sentences, paragraphs =",
"= \"output\" ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to input text document\") #ap.add_argument(\"-o\",",
"= pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences =",
"\"--input\", required=True,help=\"path to input text document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to output Summarized Document\")",
",para_sent_list = para_sent_list ,tokenized_word_sentences = tokenized_word_sentences) summary = doc.summarize() return summary def run():",
"original_text = original_text , original_sentences = original_sentences , preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences =",
"run(): input_dir = \"input\" output_dir = \"output\" ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path",
"original_sentences = original_sentences , preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences = sentences, paragraphs = paragraphs",
"pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences)",
"to output Summarized Document\") args = vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input'])",
"paragraphs ,para_sent_list = para_sent_list ,tokenized_word_sentences = tokenized_word_sentences) summary = doc.summarize() return summary def",
"argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to input text document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to output",
"ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to input text document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path",
"= preprocessed_text.replace('ppp',\"\"), sentences = sentences, paragraphs = paragraphs ,para_sent_list = para_sent_list ,tokenized_word_sentences =",
"return summary def run(): input_dir = \"input\" output_dir = \"output\" ap = argparse.ArgumentParser()",
"\"input\" output_dir = \"output\" ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to input text",
"= preprocess.Preprocess() input_text = pr.get_article_content(input_path) summary = get_summary(input_text) #pdb.set_trace() with open(output_path,'w' ,encoding =",
"= pr.get_tokenized_word_sentences(sentences) doc = document.Doc( original_text = original_text , original_sentences = original_sentences ,",
"pr.get_article_content(input_path) summary = get_summary(input_text) #pdb.set_trace() with open(output_path,'w' ,encoding = \"utf-8\") as f: f.write(summary)",
"required=True,help=\"path to input text document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to output Summarized Document\") args",
"= argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to input text document\") #ap.add_argument(\"-o\", \"--output\", required=True,help=\"path to",
"output_dir = \"output\" ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to input text document\")",
"import preprocess import argparse import pdb def get_summary(input_text): pr = preprocess.Preprocess() original_text =",
"paragraphs = paragraphs ,para_sent_list = para_sent_list ,tokenized_word_sentences = tokenized_word_sentences) summary = doc.summarize() return",
"sentences, paragraphs = paragraphs ,para_sent_list = para_sent_list ,tokenized_word_sentences = tokenized_word_sentences) summary = doc.summarize()",
"= pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc = document.Doc( original_text = original_text , original_sentences",
"argparse import pdb def get_summary(input_text): pr = preprocess.Preprocess() original_text = input_text preprocessed_text =",
"original_text = input_text preprocessed_text = pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text) paragraphs",
"pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc = document.Doc( original_text = original_text , original_sentences =",
",tokenized_word_sentences = tokenized_word_sentences) summary = doc.summarize() return summary def run(): input_dir = \"input\"",
"= original_sentences , preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences = sentences, paragraphs = paragraphs ,para_sent_list",
"= document.Doc( original_text = original_text , original_sentences = original_sentences , preprocessed_text = preprocessed_text.replace('ppp',\"\"),",
"= pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc =",
"preprocessed_text.replace('ppp',\"\"), sentences = sentences, paragraphs = paragraphs ,para_sent_list = para_sent_list ,tokenized_word_sentences = tokenized_word_sentences)",
"= input_text preprocessed_text = pr.get_clean_article(input_text) sentences = pr.get_article_sentences(preprocessed_text) original_sentences = pr.get_article_sentences(input_text) paragraphs =",
"document.Doc( original_text = original_text , original_sentences = original_sentences , preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences",
"original_sentences = pr.get_article_sentences(input_text) paragraphs = pr.get_cleaned_article_paragraphes(preprocessed_text) para_sent_list = pr.get_para_sentences(paragraphs) tokenized_word_sentences = pr.get_tokenized_word_sentences(sentences) doc",
"pr.get_tokenized_word_sentences(sentences) doc = document.Doc( original_text = original_text , original_sentences = original_sentences , preprocessed_text",
"para_sent_list ,tokenized_word_sentences = tokenized_word_sentences) summary = doc.summarize() return summary def run(): input_dir =",
"import os, pickle, re import document import preprocess import argparse import pdb def",
"doc = document.Doc( original_text = original_text , original_sentences = original_sentences , preprocessed_text =",
"= pr.get_article_content(input_path) summary = get_summary(input_text) #pdb.set_trace() with open(output_path,'w' ,encoding = \"utf-8\") as f:",
"args = vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input']) pr = preprocess.Preprocess() input_text",
"= original_text , original_sentences = original_sentences , preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences = sentences,",
"input_dir = \"input\" output_dir = \"output\" ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--input\", required=True,help=\"path to",
"output Summarized Document\") args = vars(ap.parse_args()) input_path = os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input']) pr",
", preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences = sentences, paragraphs = paragraphs ,para_sent_list = para_sent_list",
"import pdb def get_summary(input_text): pr = preprocess.Preprocess() original_text = input_text preprocessed_text = pr.get_clean_article(input_text)",
"input_path = os.path.join(input_dir,args['input']) output_path = os.path.join(output_dir,args['input']) pr = preprocess.Preprocess() input_text = pr.get_article_content(input_path) summary",
"sentences = sentences, paragraphs = paragraphs ,para_sent_list = para_sent_list ,tokenized_word_sentences = tokenized_word_sentences) summary",
"preprocess.Preprocess() input_text = pr.get_article_content(input_path) summary = get_summary(input_text) #pdb.set_trace() with open(output_path,'w' ,encoding = \"utf-8\")",
"= para_sent_list ,tokenized_word_sentences = tokenized_word_sentences) summary = doc.summarize() return summary def run(): input_dir",
"original_sentences , preprocessed_text = preprocessed_text.replace('ppp',\"\"), sentences = sentences, paragraphs = paragraphs ,para_sent_list ="
] |
[
"Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved. # Please refer",
"= logging.Formatter(LOG_FORMAT) handlers = [] # Configure the stderr handler configured on CRITICAL",
"\\t%(message)s\" ) def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the sqreen root logger. Set",
"set for configured level \"\"\" logger = logging.getLogger(root) # Don't propagate messages to",
"level \"\"\" logger = logging.getLogger(root) # Don't propagate messages to upper loggers logger.propagate",
"module helpers \"\"\" import logging ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\"",
"on stderr for errors and one file handler if log_location is set for",
"Configure the stderr handler configured on CRITICAL level stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler)",
"don't propagate messages logs to the python root logger. Configure two handlers, one",
"IOError): msg = \"Couldn't use %s as sqreen log location, fallback to stderr.\"",
"logging ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\" )",
"on CRITICAL level stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location is not None:",
"except (OSError, IOError): msg = \"Couldn't use %s as sqreen log location, fallback",
"propagate messages logs to the python root logger. Configure two handlers, one stream",
"False formatter = logging.Formatter(LOG_FORMAT) handlers = [] # Configure the stderr handler configured",
"logger.addHandler(handler) try: logger.setLevel(log_level) except ValueError: logger.error(\"Unknown log_level %r, don't alter log level\", log_level)",
"try: filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError, IOError): msg = \"Couldn't use",
"= \"Couldn't use %s as sqreen log location, fallback to stderr.\" logger.exception(msg, log_location)",
"propagate messages to upper loggers logger.propagate = False formatter = logging.Formatter(LOG_FORMAT) handlers =",
"\"\"\" import logging ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s",
"# Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved. # Please",
"one file handler if log_location is set for configured level \"\"\" logger =",
"to upper loggers logger.propagate = False formatter = logging.Formatter(LOG_FORMAT) handlers = [] #",
"Sqreen. All rights reserved. # Please refer to our terms for more information:",
"logging.getLogger(root) # Don't propagate messages to upper loggers logger.propagate = False formatter =",
"not None: try: filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError, IOError): msg =",
"2018, 2019 Sqreen. All rights reserved. # Please refer to our terms for",
"if log_location is set for configured level \"\"\" logger = logging.getLogger(root) # Don't",
"helpers \"\"\" import logging ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \"",
"# https://www.sqreen.io/terms.html # \"\"\" Logging module helpers \"\"\" import logging ROOT_LOGGER_NAME = \"sqreen\"",
"Don't propagate messages to upper loggers logger.propagate = False formatter = logging.Formatter(LOG_FORMAT) handlers",
"configured on CRITICAL level stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location is not",
"# Configure the stderr handler configured on CRITICAL level stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter)",
"stderr for errors and one file handler if log_location is set for configured",
"%(name)s:%(lineno)s \\t%(message)s\" ) def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the sqreen root logger.",
"\"\"\" Configure the sqreen root logger. Set following settings: - log_level Ensure that",
"terms for more information: # # https://www.sqreen.io/terms.html # \"\"\" Logging module helpers \"\"\"",
"- log_level Ensure that the sqreen root logger don't propagate messages logs to",
"= \"sqreen\" LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\" ) def configure_root_logger(log_level,",
"Logging module helpers \"\"\" import logging ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s",
") def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the sqreen root logger. Set following",
"root=ROOT_LOGGER_NAME): \"\"\" Configure the sqreen root logger. Set following settings: - log_level Ensure",
"utf-8 -*- # Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved.",
"log_location is set for configured level \"\"\" logger = logging.getLogger(root) # Don't propagate",
"the stderr handler configured on CRITICAL level stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if",
"root logger don't propagate messages logs to the python root logger. Configure two",
"root logger. Set following settings: - log_level Ensure that the sqreen root logger",
"%s as sqreen log location, fallback to stderr.\" logger.exception(msg, log_location) if logger.handlers: logger.handlers",
"stderr.\" logger.exception(msg, log_location) if logger.handlers: logger.handlers = [] for handler in handlers: logger.addHandler(handler)",
"Configure two handlers, one stream handler on stderr for errors and one file",
"stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location is not None: try: filehandler =",
"to stderr.\" logger.exception(msg, log_location) if logger.handlers: logger.handlers = [] for handler in handlers:",
"\"sqreen\" LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\" ) def configure_root_logger(log_level, log_location=None,",
"= [] # Configure the stderr handler configured on CRITICAL level stderr_handler =",
"log_level Ensure that the sqreen root logger don't propagate messages logs to the",
"one stream handler on stderr for errors and one file handler if log_location",
"log_location) if logger.handlers: logger.handlers = [] for handler in handlers: logger.addHandler(handler) try: logger.setLevel(log_level)",
"2019 Sqreen. All rights reserved. # Please refer to our terms for more",
"messages to upper loggers logger.propagate = False formatter = logging.Formatter(LOG_FORMAT) handlers = []",
"-*- # Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved. #",
"Configure the sqreen root logger. Set following settings: - log_level Ensure that the",
"the sqreen root logger. Set following settings: - log_level Ensure that the sqreen",
"refer to our terms for more information: # # https://www.sqreen.io/terms.html # \"\"\" Logging",
"# # https://www.sqreen.io/terms.html # \"\"\" Logging module helpers \"\"\" import logging ROOT_LOGGER_NAME =",
"python root logger. Configure two handlers, one stream handler on stderr for errors",
"\"\"\" Logging module helpers \"\"\" import logging ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT = (",
"formatter = logging.Formatter(LOG_FORMAT) handlers = [] # Configure the stderr handler configured on",
"our terms for more information: # # https://www.sqreen.io/terms.html # \"\"\" Logging module helpers",
"[] for handler in handlers: logger.addHandler(handler) try: logger.setLevel(log_level) except ValueError: logger.error(\"Unknown log_level %r,",
"\"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\" ) def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the",
"level stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location is not None: try: filehandler",
"= False formatter = logging.Formatter(LOG_FORMAT) handlers = [] # Configure the stderr handler",
"coding: utf-8 -*- # Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights",
"# \"\"\" Logging module helpers \"\"\" import logging ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT =",
"= ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\" ) def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\"",
"# -*- coding: utf-8 -*- # Copyright (c) 2016, 2017, 2018, 2019 Sqreen.",
"None: try: filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError, IOError): msg = \"Couldn't",
"<gh_stars>0 # -*- coding: utf-8 -*- # Copyright (c) 2016, 2017, 2018, 2019",
"2017, 2018, 2019 Sqreen. All rights reserved. # Please refer to our terms",
"logger.handlers: logger.handlers = [] for handler in handlers: logger.addHandler(handler) try: logger.setLevel(log_level) except ValueError:",
"reserved. # Please refer to our terms for more information: # # https://www.sqreen.io/terms.html",
"logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError, IOError): msg = \"Couldn't use %s as sqreen",
"two handlers, one stream handler on stderr for errors and one file handler",
"Ensure that the sqreen root logger don't propagate messages logs to the python",
"\"\"\" logger = logging.getLogger(root) # Don't propagate messages to upper loggers logger.propagate =",
"handlers, one stream handler on stderr for errors and one file handler if",
"logger. Configure two handlers, one stream handler on stderr for errors and one",
"handler in handlers: logger.addHandler(handler) try: logger.setLevel(log_level) except ValueError: logger.error(\"Unknown log_level %r, don't alter",
"https://www.sqreen.io/terms.html # \"\"\" Logging module helpers \"\"\" import logging ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT",
"-*- coding: utf-8 -*- # Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All",
"that the sqreen root logger don't propagate messages logs to the python root",
"handlers.append(filehandler) except (OSError, IOError): msg = \"Couldn't use %s as sqreen log location,",
"sqreen log location, fallback to stderr.\" logger.exception(msg, log_location) if logger.handlers: logger.handlers = []",
"handlers = [] # Configure the stderr handler configured on CRITICAL level stderr_handler",
"#%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\" ) def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the sqreen",
"handler configured on CRITICAL level stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location is",
"fallback to stderr.\" logger.exception(msg, log_location) if logger.handlers: logger.handlers = [] for handler in",
"for configured level \"\"\" logger = logging.getLogger(root) # Don't propagate messages to upper",
"logger.setLevel(log_level) except ValueError: logger.error(\"Unknown log_level %r, don't alter log level\", log_level) return logger",
"to the python root logger. Configure two handlers, one stream handler on stderr",
"LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\" ) def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME):",
"\"Couldn't use %s as sqreen log location, fallback to stderr.\" logger.exception(msg, log_location) if",
"settings: - log_level Ensure that the sqreen root logger don't propagate messages logs",
"loggers logger.propagate = False formatter = logging.Formatter(LOG_FORMAT) handlers = [] # Configure the",
"All rights reserved. # Please refer to our terms for more information: #",
"# Don't propagate messages to upper loggers logger.propagate = False formatter = logging.Formatter(LOG_FORMAT)",
"log location, fallback to stderr.\" logger.exception(msg, log_location) if logger.handlers: logger.handlers = [] for",
"2016, 2017, 2018, 2019 Sqreen. All rights reserved. # Please refer to our",
"log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the sqreen root logger. Set following settings: - log_level",
"= logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location is not None: try: filehandler = logging.FileHandler(log_location)",
"if logger.handlers: logger.handlers = [] for handler in handlers: logger.addHandler(handler) try: logger.setLevel(log_level) except",
"def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the sqreen root logger. Set following settings:",
"sqreen root logger don't propagate messages logs to the python root logger. Configure",
"logs to the python root logger. Configure two handlers, one stream handler on",
"logger = logging.getLogger(root) # Don't propagate messages to upper loggers logger.propagate = False",
"messages logs to the python root logger. Configure two handlers, one stream handler",
"configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the sqreen root logger. Set following settings: -",
"the python root logger. Configure two handlers, one stream handler on stderr for",
"sqreen root logger. Set following settings: - log_level Ensure that the sqreen root",
"handlers.append(stderr_handler) if log_location is not None: try: filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except",
"information: # # https://www.sqreen.io/terms.html # \"\"\" Logging module helpers \"\"\" import logging ROOT_LOGGER_NAME",
"file handler if log_location is set for configured level \"\"\" logger = logging.getLogger(root)",
"CRITICAL level stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location is not None: try:",
"rights reserved. # Please refer to our terms for more information: # #",
"stderr handler configured on CRITICAL level stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location",
"for errors and one file handler if log_location is set for configured level",
"root logger. Configure two handlers, one stream handler on stderr for errors and",
"upper loggers logger.propagate = False formatter = logging.Formatter(LOG_FORMAT) handlers = [] # Configure",
"location, fallback to stderr.\" logger.exception(msg, log_location) if logger.handlers: logger.handlers = [] for handler",
"try: logger.setLevel(log_level) except ValueError: logger.error(\"Unknown log_level %r, don't alter log level\", log_level) return",
"filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError, IOError): msg = \"Couldn't use %s as sqreen log",
"handler on stderr for errors and one file handler if log_location is set",
"use %s as sqreen log location, fallback to stderr.\" logger.exception(msg, log_location) if logger.handlers:",
"logger.exception(msg, log_location) if logger.handlers: logger.handlers = [] for handler in handlers: logger.addHandler(handler) try:",
"for handler in handlers: logger.addHandler(handler) try: logger.setLevel(log_level) except ValueError: logger.error(\"Unknown log_level %r, don't",
"import logging ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\"",
"logging.StreamHandler() stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location is not None: try: filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter)",
"is not None: try: filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError, IOError): msg",
"Set following settings: - log_level Ensure that the sqreen root logger don't propagate",
"logging.Formatter(LOG_FORMAT) handlers = [] # Configure the stderr handler configured on CRITICAL level",
"ROOT_LOGGER_NAME = \"sqreen\" LOG_FORMAT = ( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\" ) def",
"log_location is not None: try: filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError, IOError):",
"msg = \"Couldn't use %s as sqreen log location, fallback to stderr.\" logger.exception(msg,",
"(c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved. # Please refer to",
"handler if log_location is set for configured level \"\"\" logger = logging.getLogger(root) #",
"more information: # # https://www.sqreen.io/terms.html # \"\"\" Logging module helpers \"\"\" import logging",
"the sqreen root logger don't propagate messages logs to the python root logger.",
"[] # Configure the stderr handler configured on CRITICAL level stderr_handler = logging.StreamHandler()",
"is set for configured level \"\"\" logger = logging.getLogger(root) # Don't propagate messages",
"logger. Set following settings: - log_level Ensure that the sqreen root logger don't",
"errors and one file handler if log_location is set for configured level \"\"\"",
"stderr_handler.setFormatter(formatter) handlers.append(stderr_handler) if log_location is not None: try: filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler)",
"(OSError, IOError): msg = \"Couldn't use %s as sqreen log location, fallback to",
"configured level \"\"\" logger = logging.getLogger(root) # Don't propagate messages to upper loggers",
"for more information: # # https://www.sqreen.io/terms.html # \"\"\" Logging module helpers \"\"\" import",
"handlers: logger.addHandler(handler) try: logger.setLevel(log_level) except ValueError: logger.error(\"Unknown log_level %r, don't alter log level\",",
"in handlers: logger.addHandler(handler) try: logger.setLevel(log_level) except ValueError: logger.error(\"Unknown log_level %r, don't alter log",
"\" %(name)s:%(lineno)s \\t%(message)s\" ) def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure the sqreen root",
"as sqreen log location, fallback to stderr.\" logger.exception(msg, log_location) if logger.handlers: logger.handlers =",
"and one file handler if log_location is set for configured level \"\"\" logger",
"logger.propagate = False formatter = logging.Formatter(LOG_FORMAT) handlers = [] # Configure the stderr",
"logger don't propagate messages logs to the python root logger. Configure two handlers,",
"( \"[%(levelname)s][%(asctime)s #%(process)d.%(threadName)s]\" \" %(name)s:%(lineno)s \\t%(message)s\" ) def configure_root_logger(log_level, log_location=None, root=ROOT_LOGGER_NAME): \"\"\" Configure",
"= logging.getLogger(root) # Don't propagate messages to upper loggers logger.propagate = False formatter",
"Please refer to our terms for more information: # # https://www.sqreen.io/terms.html # \"\"\"",
"to our terms for more information: # # https://www.sqreen.io/terms.html # \"\"\" Logging module",
"following settings: - log_level Ensure that the sqreen root logger don't propagate messages",
"if log_location is not None: try: filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError,",
"= logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError, IOError): msg = \"Couldn't use %s as",
"# Please refer to our terms for more information: # # https://www.sqreen.io/terms.html #",
"= [] for handler in handlers: logger.addHandler(handler) try: logger.setLevel(log_level) except ValueError: logger.error(\"Unknown log_level",
"stream handler on stderr for errors and one file handler if log_location is",
"logger.handlers = [] for handler in handlers: logger.addHandler(handler) try: logger.setLevel(log_level) except ValueError: logger.error(\"Unknown",
"filehandler = logging.FileHandler(log_location) filehandler.setFormatter(formatter) handlers.append(filehandler) except (OSError, IOError): msg = \"Couldn't use %s"
] |
[
"<reponame>kevinkissi/basic-tech-tips-webapp from django.contrib import admin from django.apps import apps questions = apps.get_app_config('questions') for",
"from django.contrib import admin from django.apps import apps questions = apps.get_app_config('questions') for model_name,",
"from django.apps import apps questions = apps.get_app_config('questions') for model_name, model in questions.models.items(): admin.site.register(model)",
"admin from django.apps import apps questions = apps.get_app_config('questions') for model_name, model in questions.models.items():",
"import admin from django.apps import apps questions = apps.get_app_config('questions') for model_name, model in",
"django.contrib import admin from django.apps import apps questions = apps.get_app_config('questions') for model_name, model"
] |
[] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"KIND, either express or implied. # See the License for the specific language",
"language governing permissions and # limitations under the License. from __future__ import print_function",
"Unless required by applicable law or agreed to in writing, software # distributed",
"# # Copyright 2017 <NAME> # # Licensed under the Apache License, Version",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"License. # You may obtain a copy of the License at # #",
"def load_verbocean(verbocean_filename): relations = dict() with gzip.open(verbocean_filename, 'rt', 'utf-8') as fin: for line",
"verbocean.items(): for v2, rels in d.items(): verbocean[v1][v2] = list(rels) with open(args.outfile, 'w') as",
"permissions and # limitations under the License. from __future__ import print_function import argparse",
"parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args = parser.parse_args() def load_verbocean(verbocean_filename): relations = dict() with gzip.open(verbocean_filename, 'rt',",
"argparse from collections import defaultdict import gzip import json parser = argparse.ArgumentParser() parser.add_argument(\"infile\")",
"as fin: for line in fin: if not line.startswith('#'): verb1, rel, verb2 =",
"relations = dict() with gzip.open(verbocean_filename, 'rt', 'utf-8') as fin: for line in fin:",
"argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args = parser.parse_args() def load_verbocean(verbocean_filename): relations = dict() with gzip.open(verbocean_filename,",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"in relations: relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean = load_verbocean(args.infile) for v1,",
"coding: utf-8 -*- # # Copyright 2017 <NAME> # # Licensed under the",
"compliance with the License. # You may obtain a copy of the License",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"this file except in compliance with the License. # You may obtain a",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"defaultdict import gzip import json parser = argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args = parser.parse_args()",
"<filename>en/verbocean_to_json.py #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2017 <NAME> #",
"not in relations: relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean = load_verbocean(args.infile) for",
"<NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"ANY KIND, either express or implied. # See the License for the specific",
"-*- coding: utf-8 -*- # # Copyright 2017 <NAME> # # Licensed under",
"in compliance with the License. # You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"in fin: if not line.startswith('#'): verb1, rel, verb2 = line.split()[0:3] if verb1 not",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"use this file except in compliance with the License. # You may obtain",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"in verbocean.items(): for v2, rels in d.items(): verbocean[v1][v2] = list(rels) with open(args.outfile, 'w')",
"line in fin: if not line.startswith('#'): verb1, rel, verb2 = line.split()[0:3] if verb1",
"not use this file except in compliance with the License. # You may",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"# Copyright 2017 <NAME> # # Licensed under the Apache License, Version 2.0",
"load_verbocean(args.infile) for v1, d in verbocean.items(): for v2, rels in d.items(): verbocean[v1][v2] =",
"verb2 = line.split()[0:3] if verb1 not in relations: relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"limitations under the License. from __future__ import print_function import argparse from collections import",
"specific language governing permissions and # limitations under the License. from __future__ import",
"= parser.parse_args() def load_verbocean(verbocean_filename): relations = dict() with gzip.open(verbocean_filename, 'rt', 'utf-8') as fin:",
"dict() with gzip.open(verbocean_filename, 'rt', 'utf-8') as fin: for line in fin: if not",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"parser.add_argument(\"outfile\") args = parser.parse_args() def load_verbocean(verbocean_filename): relations = dict() with gzip.open(verbocean_filename, 'rt', 'utf-8')",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"if verb1 not in relations: relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean =",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"from collections import defaultdict import gzip import json parser = argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\")",
"OF ANY KIND, either express or implied. # See the License for the",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"from __future__ import print_function import argparse from collections import defaultdict import gzip import",
"relations: relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean = load_verbocean(args.infile) for v1, d",
"# you may not use this file except in compliance with the License.",
"utf-8 -*- # # Copyright 2017 <NAME> # # Licensed under the Apache",
"agreed to in writing, software # distributed under the License is distributed on",
"Copyright 2017 <NAME> # # Licensed under the Apache License, Version 2.0 (the",
"'utf-8') as fin: for line in fin: if not line.startswith('#'): verb1, rel, verb2",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"in d.items(): verbocean[v1][v2] = list(rels) with open(args.outfile, 'w') as fout: json.dump(verbocean, fout, indent=2)",
"gzip import json parser = argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args = parser.parse_args() def load_verbocean(verbocean_filename):",
"(the \"License\"); # you may not use this file except in compliance with",
"gzip.open(verbocean_filename, 'rt', 'utf-8') as fin: for line in fin: if not line.startswith('#'): verb1,",
"import print_function import argparse from collections import defaultdict import gzip import json parser",
"relations verbocean = load_verbocean(args.infile) for v1, d in verbocean.items(): for v2, rels in",
"# # Unless required by applicable law or agreed to in writing, software",
"if not line.startswith('#'): verb1, rel, verb2 = line.split()[0:3] if verb1 not in relations:",
"express or implied. # See the License for the specific language governing permissions",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"for the specific language governing permissions and # limitations under the License. from",
"except in compliance with the License. # You may obtain a copy of",
"= load_verbocean(args.infile) for v1, d in verbocean.items(): for v2, rels in d.items(): verbocean[v1][v2]",
"by applicable law or agreed to in writing, software # distributed under the",
"__future__ import print_function import argparse from collections import defaultdict import gzip import json",
"return relations verbocean = load_verbocean(args.infile) for v1, d in verbocean.items(): for v2, rels",
"= defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean = load_verbocean(args.infile) for v1, d in verbocean.items():",
"v1, d in verbocean.items(): for v2, rels in d.items(): verbocean[v1][v2] = list(rels) with",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"the License. from __future__ import print_function import argparse from collections import defaultdict import",
"args = parser.parse_args() def load_verbocean(verbocean_filename): relations = dict() with gzip.open(verbocean_filename, 'rt', 'utf-8') as",
"either express or implied. # See the License for the specific language governing",
"import json parser = argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args = parser.parse_args() def load_verbocean(verbocean_filename): relations",
"'rt', 'utf-8') as fin: for line in fin: if not line.startswith('#'): verb1, rel,",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"verb1, rel, verb2 = line.split()[0:3] if verb1 not in relations: relations[verb1] = defaultdict(set)",
"verbocean = load_verbocean(args.infile) for v1, d in verbocean.items(): for v2, rels in d.items():",
"for v1, d in verbocean.items(): for v2, rels in d.items(): verbocean[v1][v2] = list(rels)",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2017 <NAME> # #",
"under the License. from __future__ import print_function import argparse from collections import defaultdict",
"relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean = load_verbocean(args.infile) for v1, d in verbocean.items(): for v2,",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"License. from __future__ import print_function import argparse from collections import defaultdict import gzip",
"file except in compliance with the License. # You may obtain a copy",
"the specific language governing permissions and # limitations under the License. from __future__",
"and # limitations under the License. from __future__ import print_function import argparse from",
"json parser = argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args = parser.parse_args() def load_verbocean(verbocean_filename): relations =",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"License for the specific language governing permissions and # limitations under the License.",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean = load_verbocean(args.infile) for v1, d in verbocean.items(): for",
"the License. # You may obtain a copy of the License at #",
"import argparse from collections import defaultdict import gzip import json parser = argparse.ArgumentParser()",
"rel, verb2 = line.split()[0:3] if verb1 not in relations: relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]'))",
"to in writing, software # distributed under the License is distributed on an",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"for line in fin: if not line.startswith('#'): verb1, rel, verb2 = line.split()[0:3] if",
"for v2, rels in d.items(): verbocean[v1][v2] = list(rels) with open(args.outfile, 'w') as fout:",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"implied. # See the License for the specific language governing permissions and #",
"line.startswith('#'): verb1, rel, verb2 = line.split()[0:3] if verb1 not in relations: relations[verb1] =",
"relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean = load_verbocean(args.infile) for v1, d in",
"\"License\"); # you may not use this file except in compliance with the",
"2017 <NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"import defaultdict import gzip import json parser = argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args =",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"required by applicable law or agreed to in writing, software # distributed under",
"import gzip import json parser = argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args = parser.parse_args() def",
"line.split()[0:3] if verb1 not in relations: relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean",
"applicable law or agreed to in writing, software # distributed under the License",
"parser.parse_args() def load_verbocean(verbocean_filename): relations = dict() with gzip.open(verbocean_filename, 'rt', 'utf-8') as fin: for",
"-*- # # Copyright 2017 <NAME> # # Licensed under the Apache License,",
"with gzip.open(verbocean_filename, 'rt', 'utf-8') as fin: for line in fin: if not line.startswith('#'):",
"= line.split()[0:3] if verb1 not in relations: relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations",
"= argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args = parser.parse_args() def load_verbocean(verbocean_filename): relations = dict() with",
"or agreed to in writing, software # distributed under the License is distributed",
"verb1 not in relations: relations[verb1] = defaultdict(set) relations[verb1][verb2].add(rel.strip('[]')) return relations verbocean = load_verbocean(args.infile)",
"# limitations under the License. from __future__ import print_function import argparse from collections",
"fin: for line in fin: if not line.startswith('#'): verb1, rel, verb2 = line.split()[0:3]",
"or implied. # See the License for the specific language governing permissions and",
"not line.startswith('#'): verb1, rel, verb2 = line.split()[0:3] if verb1 not in relations: relations[verb1]",
"print_function import argparse from collections import defaultdict import gzip import json parser =",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"parser = argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args = parser.parse_args() def load_verbocean(verbocean_filename): relations = dict()",
"fin: if not line.startswith('#'): verb1, rel, verb2 = line.split()[0:3] if verb1 not in",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"v2, rels in d.items(): verbocean[v1][v2] = list(rels) with open(args.outfile, 'w') as fout: json.dump(verbocean,",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"d in verbocean.items(): for v2, rels in d.items(): verbocean[v1][v2] = list(rels) with open(args.outfile,",
"with the License. # You may obtain a copy of the License at",
"collections import defaultdict import gzip import json parser = argparse.ArgumentParser() parser.add_argument(\"infile\") parser.add_argument(\"outfile\") args",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"# -*- coding: utf-8 -*- # # Copyright 2017 <NAME> # # Licensed",
"in writing, software # distributed under the License is distributed on an \"AS",
"governing permissions and # limitations under the License. from __future__ import print_function import",
"load_verbocean(verbocean_filename): relations = dict() with gzip.open(verbocean_filename, 'rt', 'utf-8') as fin: for line in",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"rels in d.items(): verbocean[v1][v2] = list(rels) with open(args.outfile, 'w') as fout: json.dump(verbocean, fout,",
"= dict() with gzip.open(verbocean_filename, 'rt', 'utf-8') as fin: for line in fin: if"
] |
[
"import Runnable class showMultiPlayerBoard(Runnable): def __init__(self,vue, sec): Runnable.__init__(self,vue) self.sec = sec def run(self):",
"view.runnable.Runnable import Runnable class showMultiPlayerBoard(Runnable): def __init__(self,vue, sec): Runnable.__init__(self,vue) self.sec = sec def",
"Runnable class showMultiPlayerBoard(Runnable): def __init__(self,vue, sec): Runnable.__init__(self,vue) self.sec = sec def run(self): self.vue.showMultiPlayerBoard(self.sec)",
"from view.runnable.Runnable import Runnable class showMultiPlayerBoard(Runnable): def __init__(self,vue, sec): Runnable.__init__(self,vue) self.sec = sec"
] |
[
"'v2' def __init__(self, api_key, api_secret, base_api_uri=None, api_version=None, debug=False): if not api_key: raise ValueError('Missing",
"market = market, timeframe = timeframe ) if page is not None: params[\"page\"]",
"= 0.0 page = 0 n_entries = 100 while True: book_page = self.get_book(market,",
"temp = amount_required amount_required = amount_obtained amount_obtained = temp instant = dict(obtained=amount_obtained, required=amount_required)",
"Optional Arguments: page: Page number to query. Default is 0 limit: Number of",
"get_transactions(self, currency, page = None, limit = None): \"\"\"return all the transactions of",
"is 0 limit: Number of orders returned in each page. Default is 20.",
"if tracking_code is not None: params[\"tracking_code\"] = tracking_code if voucher is not None:",
"warnings_data and new_api_object(None, warnings_data, APIObject), } if isinstance(data, dict): obj = new_api_object(self, data,",
"= self._get(self.API_VERSION,\"prices\", params = params) return self._make_api_object(response, APIObject) # Authenticated endpoints #------------------------------------------------------------------- #",
"None, limit = None): \"\"\"return all the transactions of a currency of the",
"get all the user transactions. Optional Arguments: page: Page number to query. Default",
".compat import urlencode from .error import build_api_error from .model import APIObject from .model",
"Socket from .util import check_uri_security from .util import encode_params class Client(object): BASE_API_URI =",
"tracking code of the deposit. voucher: a file. \"\"\" params = dict( amount",
"of a dict. Does not requiere to be authenticated. Optional Arguments: market: A",
"present moment. Required Arguments: market: A market pair as a string. Is the",
"APIObject) def get_auth_socket(self): \"\"\"returns the userid and the socket ids to permit a",
"a \"data\" key. if data is None: raise build_api_error(response, blob) # Warn the",
"api_key, api_secret, self.API_VERSION) # a container for the socket if needed. self.socket =",
"amount_required += rest rest = 0 break else: amount_obtained += amount * price",
"address of the wallet to transfer money. amount: The amount of money to",
"params['page'] = page if limit is not None and isinstance(limit, int): params['limit'] =",
"'create', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_order_status(self, id): \"\"\"returns the present status",
"dict): kwargs['data'] = data response = getattr(self.session, method)(uri, **kwargs) return self._handle_response(response) def _handle_response(self,",
"0 n_entries = 100 while True: book_page = self.get_book(market, book_side, page=page, limit=n_entries) for",
"\"\"\" uri = self._create_api_uri(*relative_path_parts, **kwargs) data = kwargs.get(\"data\", None) if data and isinstance(data,",
"amount=amount, market=market, price=price, side=side, type=type, ) response = self._post(self.API_VERSION, 'orders', 'create', data=params) return",
"_build_session(self, auth_class, *args, **kwargs): \"\"\"Internal helper for creating a requests `session` with the",
"getattr(self.session, method)(uri, **kwargs) return self._handle_response(response) def _handle_response(self, response): \"\"\"Internal helper for handling API",
"return self._request('post', *args, **kwargs) def _make_api_object(self, response, model_type=None): blob = response.json() data =",
"import unicode_literals import json import requests import time import warnings from .auth import",
"'sell': temp = amount_required amount_required = amount_obtained amount_obtained = temp instant = dict(obtained=amount_obtained,",
"kwargs = { 'response': response, 'pagination': pagination and new_api_object(None, pagination, APIObject), 'warnings': warnings_data",
"from the CryptoMarket server. Raises the appropriate exceptions when necessary; otherwise, returns the",
"take the money. e.g. 'ETH' memo (optional): memo of the wallet to transfer",
"in order or 'side' not in order or 'amount' not in order): return",
"new_api_object(None, pagination, APIObject), 'warnings': warnings_data and new_api_object(None, warnings_data, APIObject), } if isinstance(data, dict):",
"import HMACAuth from .compat import imap from .compat import quote from .compat import",
"volume and price, and the low and high of the market. Stored in",
"a dict. Required Arguments: market: A market pair as a string. Is the",
"int): params['limit'] = limit response = self._get(self.API_VERSION, 'book', params=params) return self._make_api_object(response, APIObject) def",
"= dict( market=market ) if start is not None: params['start'] = start if",
"= timeframe ) if page is not None: params[\"page\"] = page if limit",
"of the user. Name, email, rate and bank accounts. \"\"\" response = self._get(self.API_VERSION,\"account\")",
"APIObject) def notify_deposit(self,amount,bank_account, date= None, tracking_code = None, voucher = None): \"\"\"Notifies a",
"blob.get('pagination', None) kwargs = { 'response': response, 'pagination': pagination and new_api_object(None, pagination, APIObject),",
"to get all the user transactions. Optional Arguments: page: Page number to query.",
"\"withdrawal\", data = params) return self._make_api_object(response, APIObject) def transfer(self,address, amount, currency, memo =",
"not None: params[\"limit\"] = limit response = self._get(self.API_VERSION,\"prices\", params = params) return self._make_api_object(response,",
"None # Set up a requests session for interacting with the API. self.session",
"for creating a requests `session` with the correct authentication handling.\"\"\" session = requests.session()",
"user. Required Arguments: currency: The currency to get all the user transactions. Optional",
"European Union: voucher: a file. Extra Arguments required for Mexico: date: The date",
"[]: message = \"%s (%s)\" % ( warning_blob.get('message', ''), warning_blob.get('url', '')) warnings.warn(message, UserWarning)",
"limit is not None and isinstance(limit, int): params['limit'] = limit response = self._get(self.API_VERSION,",
"= check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION = api_version or self.API_VERSION self.socket = None #",
"(optional): memo of the wallet to transfer money. \"\"\" params = dict( address",
"dict. Shows the actual bid and ask, the volume and price, and the",
"debug=False): \"\"\"returns a socket connection with cryptomkt. \"\"\" if self.socket is None: auth",
"temp instant = dict(obtained=amount_obtained, required=amount_required) return instant #Wallet def get_balance(self): \"\"\"returns the balance",
"entry in book_page['data']: price = float(entry['price']) amount = float(entry['amount']) if rest < amount:",
"in book_page['data']: price = float(entry['price']) amount = float(entry['amount']) if rest < amount: amount_obtained",
"of the wallet to transfer money. amount: The amount of money to transfer",
"id. Required Arguments: id: The identification of the order. \"\"\" params = dict(",
"import encode_params class Client(object): BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION = 'v2' def __init__(self, api_key,",
"the correct authentication handling.\"\"\" session = requests.session() session.auth = auth_class(*args, **kwargs) # session.headers.update({'Content-type':",
"the book from. e.g: 'ETHCLP'. Optional Arguments: page: Page number to query. Default",
"self._post(self.API_VERSION, \"withdrawal\", data = params) return self._make_api_object(response, APIObject) def transfer(self,address, amount, currency, memo",
"= page if limit is not None: params['limit'] = limit response = self._get(self.API_VERSION,",
"self._make_api_object(response, APIObject) def create_multi_orders(self, order_list): for order in order_list: if ('market' not in",
"a different API base. self.BASE_API_URI = check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION = api_version or",
"from .auth import HMACAuth from .compat import imap from .compat import quote from",
"A market pair as a string. Is the specified market to place the",
"page. Default is 20. \"\"\" params = dict( market = market, timeframe =",
"of the wallet to transfer money. \"\"\" params = dict( address = address,",
"from __future__ import division from __future__ import print_function from __future__ import unicode_literals import",
"\"\"\"Internal helper for creating a requests `session` with the correct authentication handling.\"\"\" session",
"response = self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) # orders def get_active_orders(self, market, page=None, limit=None): \"\"\"returns",
"if side == 'buy' else 'buy' amount_required = 0.0 amount_obtained = 0.0 page",
"= params) return self._make_api_object(response, APIObject) def transfer(self,address, amount, currency, memo = None): \"\"\"transfer",
"pair is provided, the market state of all the market pairs are returned.",
"money between wallets. Required Arguments: adderss: The address of the wallet to transfer",
"requests to the CryptoMarket API. Raises an APIError if the response is not",
"method, *relative_path_parts, **kwargs): \"\"\"Internal helper for creating HTTP requests to the CryptoMarket API.",
"the end date. the earlier trades first, and the older last. stored in",
"up a requests session for interacting with the API. self.session = self._build_session(HMACAuth, api_key,",
"user in a given market. Required Arguments: market: A market pair as a",
"member of a dict. Required Arguments: market: A market pair as a string.",
"the \"data\" member of a dict If no start date is given, returns",
"requiere to be authenticated. Optional Arguments: market: A market pair as string, if",
"member of a dict. Does not requiere to be authenticated. Optional Arguments: market:",
"The wallet from which to take the money. e.g. 'ETH' memo (optional): memo",
"page. Default is 20. \"\"\" params = dict( market=market, side=side ) if page",
"= urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return url def _request(self, method, *relative_path_parts, **kwargs): \"\"\"Internal helper",
"self._get(self.API_VERSION, 'trades', params=params) return self._make_api_object(response, APIObject) def get_prices(self, market, timeframe, page = None,",
"All valid responses have a \"data\" key. if data is None: raise build_api_error(response,",
"the specified market to get the book from. e.g: 'ETHCLP'. Optional Arguments: page:",
"book_page['data']: price = float(entry['price']) amount = float(entry['amount']) if rest < amount: amount_obtained +=",
"the estimate of the transaction. side: 'buy' or 'sell' amount: Is the amount",
"of the user. Required Arguments: currency: The currency to get all the user",
"response = self._get(self.API_VERSION, 'ticker', params=params) return self._make_api_object(response, APIObject) def get_book(self, market, side, page=None,",
"None): \"\"\"returns a list of the prices of a market (candles on the",
"amount, bank_account = bank_account ) if date is not None: params[\"date\"] = date",
"to obatin it. If side is buy, returns an estimate of the amount",
"amount * price amount_required += amount rest -= amount if rest == 0",
"wallets. Required Arguments: adderss: The address of the wallet to transfer money. amount:",
"user. \"\"\" response = self._get(self.API_VERSION, 'balance') return self._make_api_object(response, APIObject) def get_transactions(self, currency, page",
"end: The earlier date to get trades from, exclusive. page: Page number to",
"\"\"\" params = dict( market=market ) if start is not None: params['start'] =",
"transfer into the wallet. currency: The wallet from which to take the money.",
"The amount deposited to your wallet. bank_account: The address (id) of the bank",
"price=price, side=side, type=type, ) response = self._post(self.API_VERSION, 'orders', 'create', data=params) return self._make_api_object(response, APIObject)",
"\"\"\"Returns a list of the marketpairs as strings available in Cryptomkt as the",
"book_side, page=page, limit=n_entries) for entry in book_page['data']: price = float(entry['price']) amount = float(entry['amount'])",
"a dict. Shows the actual bid and ask, the volume and price, and",
"of the amount ofOrder crypto obtained and the amount of fiat required to",
"APIObject) def get_trades(self, market, start=None, end=None, page=None, limit=None): \"\"\"returns a list of all",
"withdrawal from fiat wallet to your bank account. Required Arguments: amount: the amount",
"20. \"\"\" params = dict( currency = currency ) if page is not",
"Extra Arguments required for Brazil and the European Union: voucher: a file. Extra",
"APIObject) def get_executed_orders(self, market, page=None, limit=None): \"\"\"returns the list of the executed orders",
"from .compat import urlencode from .error import build_api_error from .model import APIObject from",
"not api_secret: raise ValueError('Missing `api_secret`.') # Allow passing in a different API base.",
"= self._get(self.API_VERSION, \"transactions\", params=params) return self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account, date= None, tracking_code =",
"= dict( market=market, side=side ) if page is not None and isinstance(page, int):",
"return self._make_api_object(response, APIObject) def get_auth_socket(self): \"\"\"returns the userid and the socket ids to",
"market=market ) if start is not None: params['start'] = start if end is",
"= None): \"\"\"returns a list of the prices of a market (candles on",
"api_secret, self.API_VERSION) # a container for the socket if needed. self.socket = None",
"is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'trades', params=params) return self._make_api_object(response,",
"money to transfer into the wallet. currency: The wallet from which to take",
"import APIObject from .model import new_api_object from .socket import Socket from .util import",
"new_api_object from .socket import Socket from .util import check_uri_security from .util import encode_params",
"params=params) return self._make_api_object(response, APIObject) def get_executed_orders(self, market, page=None, limit=None): \"\"\"returns the list of",
"the account information of the user. Name, email, rate and bank accounts. \"\"\"",
"member of a dict Required Arguments: market: A market pair as a string.",
"*relative_path_parts, **kwargs): \"\"\"Internal helper for creating HTTP requests to the CryptoMarket API. Raises",
"each page. Default is 20. \"\"\" params = dict( market=market, side=side ) if",
"currency: The wallet from which to take the money. e.g. 'ETH' memo (optional):",
"of the executed orders of the user on a given market. Required Arguments:",
"the market state of all the market pairs are returned. e.g: 'EHTARS'. \"\"\"",
"timeframe. The earlier prices first and the older last. the list is stored",
"'id' not in order: return None params = dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), )",
"Arguments: page: Page number to query. Default is 0 limit: Number of orders",
"= self._get(self.API_VERSION, 'orders', 'status', params=params) return self._make_api_object(response, APIObject) def cancel_order(self, id): \"\"\"Cancel an",
"None, voucher = None): \"\"\"Notifies a deposit from your bank account to your",
"0.0 amount_obtained = 0.0 page = 0 n_entries = 100 while True: book_page",
"for entry in book_page['data']: price = float(entry['price']) amount = float(entry['amount']) if rest <",
"in format dd/mm/yyyy. tracking_code: The tracking code of the deposit. voucher: a file.",
"for creating fully qualified endpoint URIs.\"\"\" params = kwargs.get(\"params\", None) if params and",
"required for Brazil and the European Union: voucher: a file. Extra Arguments required",
"'bulk', data=params) return self._make_api_object(response, APIObject) def get_order_status(self, id): \"\"\"returns the present status of",
"= None): \"\"\"return all the transactions of a currency of the user. Required",
"None) kwargs = { 'response': response, 'pagination': pagination and new_api_object(None, pagination, APIObject), 'warnings':",
"endpoints #------------------------------------------------------------------- # account def get_account(self): \"\"\"returns the account information of the user.",
"and high of the market. Stored in the \"data\" member of a dict.",
"rest = float(amount) book_side = 'sell' if side == 'buy' else 'buy' amount_required",
"of a dict Required Arguments: market: A market pair as a string. Is",
"amount if rest == 0 or len(book_page['data']) < n_entries: break else: time.sleep(3) page",
"bank account from which you deposited. Extra Arguments required for Brazil and the",
"given a timeframe. The earlier prices first and the older last. the list",
"no market pair is provided, the market state of all the market pairs",
"to obtain it. Required Arguments: market: The market to get the estimate of",
"the amount of crypto to 'buy' or 'sell' \"\"\" rest = float(amount) book_side",
"Required Arguments: adderss: The address of the wallet to transfer money. amount: The",
"the present status of an order, given the order id. Required Arguments: id:",
"limit=n_entries) for entry in book_page['data']: price = float(entry['price']) amount = float(entry['amount']) if rest",
"UserWarning) pagination = blob.get('pagination', None) kwargs = { 'response': response, 'pagination': pagination and",
"params = dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'create', 'bulk',",
"estimate of the amount of fiat obtained and the amount of crypto required",
"in minutes. accepted values are 1, 5, 15, 60, 240, 1440 and 10080.",
"wallet (fiat). Required Arguments: amount: The amount deposited to your wallet. bank_account: The",
"one of the keywords 'market', 'limit', 'stop_limit' \"\"\" params = dict( amount=amount, market=market,",
"or 'sell' the crypto type: one of the keywords 'market', 'limit', 'stop_limit' \"\"\"",
"15, 60, 240, 1440 and 10080. Optional Arguments: page: Page number to query.",
"\"\"\"Returns a general view of the market state as a dict. Shows the",
"= self._get(self.API_VERSION, 'ticker', params=params) return self._make_api_object(response, APIObject) def get_book(self, market, side, page=None, limit=None):",
"response.json() data = blob.get('data', None) # All valid responses have a \"data\" key.",
"API # ----------------------------------------------------------- def get_markets(self): \"\"\"Returns a list of the marketpairs as strings",
"= dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'cancel', 'bulk', data=params)",
"return self._make_api_object(response, APIObject) def get_ticker(self, market=None): \"\"\"Returns a general view of the market",
"trades first, and the older last. stored in the \"data\" member of a",
"session def _create_api_uri(self, *parts, **kwargs): \"\"\"Internal helper for creating fully qualified endpoint URIs.\"\"\"",
"state of all the market pairs are returned. e.g: 'EHTARS'. \"\"\" params =",
"date: The date of the deposit, in format dd/mm/yyyy. tracking_code: The tracking code",
"dict( id=id ) response = self._get(self.API_VERSION, 'orders', 'status', params=params) return self._make_api_object(response, APIObject) def",
"market response = self._get(self.API_VERSION, 'ticker', params=params) return self._make_api_object(response, APIObject) def get_book(self, market, side,",
"necessary; otherwise, returns the response. \"\"\" if not str(response.status_code).startswith('2'): raise build_api_error(response) return response",
"data = params) return self._make_api_object(response, APIObject) def transfer(self,address, amount, currency, memo = None):",
"= float(entry['price']) amount = float(entry['amount']) if rest < amount: amount_obtained += rest *",
"URIs.\"\"\" params = kwargs.get(\"params\", None) if params and isinstance(params, dict): url = urljoin(self.BASE_API_URI,",
"market, start=None, end=None, page=None, limit=None): \"\"\"returns a list of all trades (executed orders)",
"and isinstance(params, dict): url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) + '?%s' % urlencode(params)) else:",
"build_api_error(response, blob) # Warn the user about each warning that was returned. warnings_data",
"else: time.sleep(3) page = page + 1 if book_side == 'sell': temp =",
"socket ids to permit a socket connection with cryptomkt. \"\"\" response = self._get(\"v2\",",
"if data is None: raise build_api_error(response, blob) # Warn the user about each",
"date= None, tracking_code = None, voucher = None): \"\"\"Notifies a deposit from your",
"date, until the end date. the earlier trades first, and the older last.",
"def get_socket(self, debug=False): \"\"\"returns a socket connection with cryptomkt. \"\"\" if self.socket is",
"len(book_page['data']) < n_entries: break else: time.sleep(3) page = page + 1 if book_side",
"'application/json'}) return session def _create_api_uri(self, *parts, **kwargs): \"\"\"Internal helper for creating fully qualified",
"orders returned in each page. Default is 20. \"\"\" params = dict( currency",
"not None: params[\"page\"] = page if limit is not None: params[\"limit\"] = limit",
"user. Name, email, rate and bank accounts. \"\"\" response = self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject)",
"def __init__(self, api_key, api_secret, base_api_uri=None, api_version=None, debug=False): if not api_key: raise ValueError('Missing `api_key`.')",
"helper for creating a requests `session` with the correct authentication handling.\"\"\" session =",
"def get_instant(self,market, side, amount): \"\"\"If side is sell, returns an estimate of the",
"voucher response = self._post(self.API_VERSION, \"deposit\", data = params) return self._make_api_object(response,APIObject) def notify_withdrawal(self, amount,",
"creating HTTP requests to the CryptoMarket API. Raises an APIError if the response",
"a currency of the user. Required Arguments: currency: The currency to get all",
"a dict Required Arguments: market: A market pair as a string. Is the",
"creating a requests `session` with the correct authentication handling.\"\"\" session = requests.session() session.auth",
"notify_withdrawal(self, amount, bank_account): \"\"\"Notifies a withdrawal from fiat wallet to your bank account.",
"import build_api_error from .model import APIObject from .model import new_api_object from .socket import",
"APIObject) def get_prices(self, market, timeframe, page = None, limit = None): \"\"\"returns a",
"price amount_required += amount rest -= amount if rest == 0 or len(book_page['data'])",
"transaction. side: 'buy' or 'sell' amount: Is the amount of crypto to 'buy'",
"all the transactions of a currency of the user. Required Arguments: currency: The",
"format dd/mm/yyyy. tracking_code: The tracking code of the deposit. voucher: a file. \"\"\"",
"APIObject) def get_instant(self,market, side, amount): \"\"\"If side is sell, returns an estimate of",
"start: The older date to get trades from, inclusive. end: The earlier date",
"your bank account to your wallet (fiat). Required Arguments: amount: The amount deposited",
"use by API consumers. \"\"\" uri = self._create_api_uri(*relative_path_parts, **kwargs) data = kwargs.get(\"data\", None)",
"= self._post(self.API_VERSION, \"withdrawal\", data = params) return self._make_api_object(response, APIObject) def transfer(self,address, amount, currency,",
"isinstance(params, dict): url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) + '?%s' % urlencode(params)) else: url",
"response = self._post(self.API_VERSION, \"transfer\", data = params) return self._make_api_object(response, APIObject) def get_auth_socket(self): \"\"\"returns",
"= response.json() data = blob.get('data', None) # All valid responses have a \"data\"",
"params = dict( currency = currency ) if page is not None: params[\"page\"]",
"account. Required Arguments: amount: the amount you need to withdraw to your bank",
"currency, memo = None): \"\"\"transfer money between wallets. Required Arguments: adderss: The address",
"between every candle in minutes. accepted values are 1, 5, 15, 60, 240,",
"side=side ) if page is not None and isinstance(page, int): params['page'] = page",
"of a currency of the user. Required Arguments: currency: The currency to get",
"to the CryptoMarket API. Raises an APIError if the response is not 20X.",
"the amount of crypto required to obatin it. If side is buy, returns",
"page: Page number to query. Default is 0 limit: Number of orders returned",
"params=params) return self._make_api_object(response, APIObject) def create_order(self, market, amount, price, side, type): \"\"\"creates an",
"connection with cryptomkt. \"\"\" response = self._get(\"v2\", \"socket/auth\") return self._make_api_object(response, APIObject) def get_socket(self,",
"and the socket ids to permit a socket connection with cryptomkt. \"\"\" response",
"not in order or 'type' not in order or 'side' not in order",
"if voucher is not None: params[\"voucher\"] = voucher response = self._post(self.API_VERSION, \"deposit\", data",
"Allow passing in a different API base. self.BASE_API_URI = check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION",
"e.g. 'ETH' memo (optional): memo of the wallet to transfer money. \"\"\" params",
"**kwargs): \"\"\"Internal helper for creating fully qualified endpoint URIs.\"\"\" params = kwargs.get(\"params\", None)",
"and 10080. Optional Arguments: page: Page number to query. Default is 0 limit:",
"= amount, bank_account = bank_account ) response = self._post(self.API_VERSION, \"withdrawal\", data = params)",
"user transactions. Optional Arguments: page: Page number to query. Default is 0 limit:",
"5, 15, 60, 240, 1440 and 10080. Optional Arguments: page: Page number to",
"of a dict. \"\"\" response = self._get(self.API_VERSION, 'market') return self._make_api_object(response, APIObject) def get_ticker(self,",
"the response is not 20X. Otherwise, returns the response object. Not intended for",
"the socket ids to permit a socket connection with cryptomkt. \"\"\" response =",
"account def get_account(self): \"\"\"returns the account information of the user. Name, email, rate",
"return self._make_api_object(response, APIObject) # Authenticated endpoints #------------------------------------------------------------------- # account def get_account(self): \"\"\"returns the",
"start=None, end=None, page=None, limit=None): \"\"\"returns a list of all trades (executed orders) of",
"the keywords 'market', 'limit', 'stop_limit' \"\"\" params = dict( amount=amount, market=market, price=price, side=side,",
"a market between the start date, until the end date. the earlier trades",
"'market', 'limit', 'stop_limit' \"\"\" params = dict( amount=amount, market=market, price=price, side=side, type=type, )",
"params) return self._make_api_object(response, APIObject) def transfer(self,address, amount, currency, memo = None): \"\"\"transfer money",
"the list of the executed orders of the user on a given market.",
"for direct use by API consumers. \"\"\" uri = self._create_api_uri(*relative_path_parts, **kwargs) data =",
"order. \"\"\" params = dict( id=id ) response = self._get(self.API_VERSION, 'orders', 'status', params=params)",
"self._request('get', *args, **kwargs) def _post(self, *args, **kwargs): return self._request('post', *args, **kwargs) def _make_api_object(self,",
"of crypto required to obatin it. If side is buy, returns an estimate",
"params[\"page\"] = page if limit is not None: params[\"limit\"] = limit response =",
"= params) return self._make_api_object(response,APIObject) def notify_withdrawal(self, amount, bank_account): \"\"\"Notifies a withdrawal from fiat",
"the book from. e.g: 'ETHCLP'. timeframe: timelapse between every candle in minutes. accepted",
"fiat obtained and the amount of crypto required to obatin it. If side",
"start if end is not None: params['end'] = end if page is not",
"currency of the user. Required Arguments: currency: The currency to get all the",
"quote from .compat import urljoin from .compat import urlencode from .error import build_api_error",
"voucher is not None: params[\"voucher\"] = voucher response = self._post(self.API_VERSION, \"deposit\", data =",
"to place the order in e.g: 'ETHCLP'. price: The price to ask or",
"the volume and price, and the low and high of the market. Stored",
"if limit is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'executed',",
"market: A market pair as a string. Is the specified market to get",
"dict( market = market, timeframe = timeframe ) if page is not None:",
"in the \"data\" member of a dict If no start date is given,",
"returned in each page. Default is 20. \"\"\" params = dict( market=market )",
"'market') return self._make_api_object(response, APIObject) def get_ticker(self, market=None): \"\"\"Returns a general view of the",
"limit response = self._get(self.API_VERSION, 'book', params=params) return self._make_api_object(response, APIObject) def get_trades(self, market, start=None,",
"= new_api_object(self, data, model_type) return obj # Public API # ----------------------------------------------------------- def get_markets(self):",
"if no market pair is provided, the market state of all the market",
"method)(uri, **kwargs) return self._handle_response(response) def _handle_response(self, response): \"\"\"Internal helper for handling API responses",
"urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) + '?%s' % urlencode(params)) else: url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)))",
"API_VERSION = 'v2' def __init__(self, api_key, api_secret, base_api_uri=None, api_version=None, debug=False): if not api_key:",
"import Socket from .util import check_uri_security from .util import encode_params class Client(object): BASE_API_URI",
"wallet to transfer money. \"\"\" params = dict( address = address, amount =",
"pair as a string. Is the specified market to place the order in",
"the order. \"\"\" params = dict( id=id ) response = self._post(self.API_VERSION, 'orders', 'cancel',",
"or 'sell'. Optional Arguments: page: Page number to query. Default is 0 limit:",
"from .error import build_api_error from .model import APIObject from .model import new_api_object from",
"and isinstance(page, int): params['page'] = page if limit is not None and isinstance(limit,",
"address (id) of the bank account from which you deposited. Extra Arguments required",
"or 'amount' not in order): return None params = dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')),",
"self.BASE_API_URI = check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION = api_version or self.API_VERSION self.socket = None",
"not in order: return None params = dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response",
"= self._post(self.API_VERSION, \"transfer\", data = params) return self._make_api_object(response, APIObject) def get_auth_socket(self): \"\"\"returns the",
"list of all trades (executed orders) of a market between the start date,",
"*parts, **kwargs): \"\"\"Internal helper for creating fully qualified endpoint URIs.\"\"\" params = kwargs.get(\"params\",",
"response = self._get(self.API_VERSION, 'market') return self._make_api_object(response, APIObject) def get_ticker(self, market=None): \"\"\"Returns a general",
"params = dict( id=id ) response = self._get(self.API_VERSION, 'orders', 'status', params=params) return self._make_api_object(response,",
"API responses from the CryptoMarket server. Raises the appropriate exceptions when necessary; otherwise,",
"order: return None params = dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION,",
"returns an estimate of the amount ofOrder crypto obtained and the amount of",
"wallet to your bank account. Required Arguments: amount: the amount you need to",
"return self._handle_response(response) def _handle_response(self, response): \"\"\"Internal helper for handling API responses from the",
"'buy' amount_required = 0.0 amount_obtained = 0.0 page = 0 n_entries = 100",
"amount_required += amount rest -= amount if rest == 0 or len(book_page['data']) <",
"params = dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'cancel', 'bulk',",
"orders of a given side in a specified market pair. stored in the",
"list is stored in the data member of a dict Required Arguments: market:",
"which to take the money. e.g. 'ETH' memo (optional): memo of the wallet",
"given, returns trades until the present moment. Required Arguments: market: A market pair",
"of the marketpairs as strings available in Cryptomkt as the \"data\" member of",
"required to obatin it. If side is buy, returns an estimate of the",
"def cancel_order(self, id): \"\"\"Cancel an order given its id. Required Arguments: id: The",
"in order_list: if 'id' not in order: return None params = dict( ids=json.dumps(order_list,",
"market. Required Arguments: market: A market pair as a string. Is the specified",
"in order or 'type' not in order or 'side' not in order or",
"with the correct authentication handling.\"\"\" session = requests.session() session.auth = auth_class(*args, **kwargs) #",
"self._get(self.API_VERSION, 'ticker', params=params) return self._make_api_object(response, APIObject) def get_book(self, market, side, page=None, limit=None): \"\"\"Returns",
"and isinstance(limit, int): params['limit'] = limit response = self._get(self.API_VERSION, 'book', params=params) return self._make_api_object(response,",
"def transfer(self,address, amount, currency, memo = None): \"\"\"transfer money between wallets. Required Arguments:",
"= dict( amount = amount, bank_account = bank_account ) response = self._post(self.API_VERSION, \"withdrawal\",",
"timeframe ) if page is not None: params[\"page\"] = page if limit is",
"or self.BASE_API_URI) self.API_VERSION = api_version or self.API_VERSION self.socket = None # Set up",
"if start is not None: params['start'] = start if end is not None:",
"order_list: if ('market' not in order or 'type' not in order or 'side'",
"= api_version or self.API_VERSION self.socket = None # Set up a requests session",
"= 100 while True: book_page = self.get_book(market, book_side, page=page, limit=n_entries) for entry in",
"dict( amount = amount, bank_account = bank_account ) response = self._post(self.API_VERSION, \"withdrawal\", data",
"a specified market pair. stored in the \"data\" member of a dict. Required",
"wallet from which to take the money. e.g. 'ETH' memo (optional): memo of",
"orders) of a market between the start date, until the end date. the",
"The address(id) of the bank account. \"\"\" params = dict( amount = amount,",
"< n_entries: break else: time.sleep(3) page = page + 1 if book_side ==",
"dict(obtained=amount_obtained, required=amount_required) return instant #Wallet def get_balance(self): \"\"\"returns the balance of the user.",
"**kwargs) return self._handle_response(response) def _handle_response(self, response): \"\"\"Internal helper for handling API responses from",
"earlier prices first and the older last. the list is stored in the",
"since 2020-02-17. If no end date is given, returns trades until the present",
"Is the specified market to place the order in e.g: 'ETHCLP'. price: The",
"get trades from, inclusive. end: The earlier date to get trades from, exclusive.",
"instant = dict(obtained=amount_obtained, required=amount_required) return instant #Wallet def get_balance(self): \"\"\"returns the balance of",
"currency: The currency to get all the user transactions. Optional Arguments: page: Page",
"Arguments: adderss: The address of the wallet to transfer money. amount: The amount",
"response = self._post(self.API_VERSION, 'orders', 'cancel', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_instant(self,market, side,",
"amount = amount, bank_account = bank_account ) if date is not None: params[\"date\"]",
"last. the list is stored in the data member of a dict Required",
"market to place the order in e.g: 'ETHCLP'. price: The price to ask",
"dict( market=market ) if page is not None: params['page'] = page if limit",
"'status', params=params) return self._make_api_object(response, APIObject) def cancel_order(self, id): \"\"\"Cancel an order given its",
"\"\"\"return all the transactions of a currency of the user. Required Arguments: currency:",
"'limit', 'stop_limit' \"\"\" params = dict( amount=amount, market=market, price=price, side=side, type=type, ) response",
"amount of crypto required to obatin it. If side is buy, returns an",
"self.socket = None def _build_session(self, auth_class, *args, **kwargs): \"\"\"Internal helper for creating a",
"Raises an APIError if the response is not 20X. Otherwise, returns the response",
"self._make_api_object(response,APIObject) def notify_withdrawal(self, amount, bank_account): \"\"\"Notifies a withdrawal from fiat wallet to your",
") response = self._post(self.API_VERSION, 'orders', 'cancel', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_instant(self,market,",
"and new_api_object(None, warnings_data, APIObject), } if isinstance(data, dict): obj = new_api_object(self, data, model_type,",
"params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'executed', params=params) return self._make_api_object(response, APIObject) def",
"or 'sell' amount: Is the amount of crypto to 'buy' or 'sell' \"\"\"",
"as a string. Is the specified market to place the order in e.g:",
"if date is not None: params[\"date\"] = date if tracking_code is not None:",
"prices first and the older last. the list is stored in the data",
"with the API. self.session = self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION) # a container for",
"to take the money. e.g. 'ETH' memo (optional): memo of the wallet to",
"end=None, page=None, limit=None): \"\"\"returns a list of all trades (executed orders) of a",
"in the \"data\" member of a dict. Does not requiere to be authenticated.",
"'ETHCLP'. timeframe: timelapse between every candle in minutes. accepted values are 1, 5,",
"date is given, returns trades until the present moment. Required Arguments: market: A",
"self.socket = None # Set up a requests session for interacting with the",
"break else: amount_obtained += amount * price amount_required += amount rest -= amount",
"returns the response. \"\"\" if not str(response.status_code).startswith('2'): raise build_api_error(response) return response def _get(self,",
"a string. Is the specified market to get the book from. e.g: 'ETHCLP'.",
"Is the specified market to get the book from. e.g: 'ETHCLP'. timeframe: timelapse",
"market: The market to get the estimate of the transaction. side: 'buy' or",
"get_auth_socket(self): \"\"\"returns the userid and the socket ids to permit a socket connection",
"requests `session` with the correct authentication handling.\"\"\" session = requests.session() session.auth = auth_class(*args,",
"start date is given, returns trades since 2020-02-17. If no end date is",
"in a given market. Required Arguments: market: A market pair as a string.",
"start is not None: params['start'] = start if end is not None: params['end']",
"wallet. bank_account: The address (id) of the bank account from which you deposited.",
"the amount of fiat required to obtain it. Required Arguments: market: The market",
"'cancel', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_instant(self,market, side, amount): \"\"\"If side is",
"self._get(self.API_VERSION, 'balance') return self._make_api_object(response, APIObject) def get_transactions(self, currency, page = None, limit =",
"**kwargs) def _post(self, *args, **kwargs): return self._request('post', *args, **kwargs) def _make_api_object(self, response, model_type=None):",
"of the order. \"\"\" params = dict( id=id ) response = self._get(self.API_VERSION, 'orders',",
"= market response = self._get(self.API_VERSION, 'ticker', params=params) return self._make_api_object(response, APIObject) def get_book(self, market,",
"'create', data=params) return self._make_api_object(response, APIObject) def create_multi_orders(self, order_list): for order in order_list: if",
"int): params['page'] = page if limit is not None and isinstance(limit, int): params['limit']",
"page if limit is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION, \"transactions\",",
"the order in e.g: 'ETHCLP'. price: The price to ask or bid for",
"limit = None): \"\"\"return all the transactions of a currency of the user.",
"transactions of a currency of the user. Required Arguments: currency: The currency to",
"returned. e.g: 'EHTARS'. \"\"\" params = {} if market: params['market'] = market response",
"page if limit is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION,\"prices\", params",
"warning_blob in warnings_data or []: message = \"%s (%s)\" % ( warning_blob.get('message', ''),",
"\"\"\" params = dict( id=id ) response = self._get(self.API_VERSION, 'orders', 'status', params=params) return",
"blob.get('warnings', None) for warning_blob in warnings_data or []: message = \"%s (%s)\" %",
"create_order(self, market, amount, price, side, type): \"\"\"creates an orders from the specified argument.",
"limit is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'active', params=params)",
"crypto to 'buy' or 'sell' \"\"\" rest = float(amount) book_side = 'sell' if",
") if page is not None: params[\"page\"] = page if limit is not",
"'response': response, 'pagination': pagination and new_api_object(None, pagination, APIObject), 'warnings': warnings_data and new_api_object(None, warnings_data,",
"the wallet. currency: The wallet from which to take the money. e.g. 'ETH'",
"params = dict( amount = amount, bank_account = bank_account ) if date is",
"order in e.g: 'ETHCLP'. price: The price to ask or bid for one",
"\"\"\" rest = float(amount) book_side = 'sell' if side == 'buy' else 'buy'",
"the response object. Not intended for direct use by API consumers. \"\"\" uri",
"data = kwargs.get(\"data\", None) if data and isinstance(data, dict): kwargs['data'] = data response",
"self._make_api_object(response, APIObject) def transfer(self,address, amount, currency, memo = None): \"\"\"transfer money between wallets.",
"or selled. market: A market pair as a string. Is the specified market",
"import print_function from __future__ import unicode_literals import json import requests import time import",
"string, if no market pair is provided, the market state of all the",
"obatin it. If side is buy, returns an estimate of the amount ofOrder",
"ValueError('Missing `api_secret`.') # Allow passing in a different API base. self.BASE_API_URI = check_uri_security(base_api_uri",
"is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'active', params=params) return",
"self._get(self.API_VERSION, 'orders', 'status', params=params) return self._make_api_object(response, APIObject) def cancel_order(self, id): \"\"\"Cancel an order",
"self._make_api_object(response, APIObject) def get_socket(self, debug=False): \"\"\"returns a socket connection with cryptomkt. \"\"\" if",
"= {} if market: params['market'] = market response = self._get(self.API_VERSION, 'ticker', params=params) return",
"obj # Public API # ----------------------------------------------------------- def get_markets(self): \"\"\"Returns a list of the",
"e.g: 'ETHEUR'. side: 'buy' or 'sell'. Optional Arguments: page: Page number to query.",
"to permit a socket connection with cryptomkt. \"\"\" response = self._get(\"v2\", \"socket/auth\") return",
"dict. \"\"\" response = self._get(self.API_VERSION, 'market') return self._make_api_object(response, APIObject) def get_ticker(self, market=None): \"\"\"Returns",
"dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'create', 'bulk', data=params) return",
"which you deposited. Extra Arguments required for Brazil and the European Union: voucher:",
"the appropriate exceptions when necessary; otherwise, returns the response. \"\"\" if not str(response.status_code).startswith('2'):",
"params = dict( market=market ) if page is not None: params['page'] = page",
"Authenticated endpoints #------------------------------------------------------------------- # account def get_account(self): \"\"\"returns the account information of the",
"not str(response.status_code).startswith('2'): raise build_api_error(response) return response def _get(self, *args, **kwargs): return self._request('get', *args,",
"dict. Required Arguments: market: A market pair as a string. Is the specified",
"into the wallet. currency: The wallet from which to take the money. e.g.",
"currency ) if memo is not None: params[\"memo\"] = memo response = self._post(self.API_VERSION,",
"and the amount of crypto required to obatin it. If side is buy,",
"def notify_withdrawal(self, amount, bank_account): \"\"\"Notifies a withdrawal from fiat wallet to your bank",
"response = self._get(self.API_VERSION, 'orders', 'active', params=params) return self._make_api_object(response, APIObject) def get_executed_orders(self, market, page=None,",
"for creating HTTP requests to the CryptoMarket API. Raises an APIError if the",
"self._make_api_object(response, APIObject) def get_executed_orders(self, market, page=None, limit=None): \"\"\"returns the list of the executed",
"from which you deposited. Extra Arguments required for Brazil and the European Union:",
"moment. Required Arguments: market: A market pair as a string. Is the specified",
"date to get trades from, exclusive. page: Page number to query. Default is",
"n_entries = 100 while True: book_page = self.get_book(market, book_side, page=page, limit=n_entries) for entry",
"params['page'] = page if limit is not None: params['limit'] = limit response =",
"isinstance(limit, int): params['limit'] = limit response = self._get(self.API_VERSION, 'book', params=params) return self._make_api_object(response, APIObject)",
"a socket connection with cryptomkt. \"\"\" if self.socket is None: auth = self.get_auth_socket()",
"of the deposit. voucher: a file. \"\"\" params = dict( amount = amount,",
"voucher = None): \"\"\"Notifies a deposit from your bank account to your wallet",
"pagination = blob.get('pagination', None) kwargs = { 'response': response, 'pagination': pagination and new_api_object(None,",
"= self._get(self.API_VERSION, 'orders', 'active', params=params) return self._make_api_object(response, APIObject) def get_executed_orders(self, market, page=None, limit=None):",
"= self._post(self.API_VERSION, 'orders', 'create', data=params) return self._make_api_object(response, APIObject) def create_multi_orders(self, order_list): for order",
"amount: The amount deposited to your wallet. bank_account: The address (id) of the",
"\"\"\" params = dict( market = market, timeframe = timeframe ) if page",
"is not 20X. Otherwise, returns the response object. Not intended for direct use",
"amount_obtained amount_obtained = temp instant = dict(obtained=amount_obtained, required=amount_required) return instant #Wallet def get_balance(self):",
"Arguments: currency: The currency to get all the user transactions. Optional Arguments: page:",
"of money to transfer into the wallet. currency: The wallet from which to",
"timeframe, page = None, limit = None): \"\"\"returns a list of the prices",
"the CryptoMarket API. Raises an APIError if the response is not 20X. Otherwise,",
"or []: message = \"%s (%s)\" % ( warning_blob.get('message', ''), warning_blob.get('url', '')) warnings.warn(message,",
"= 'sell' if side == 'buy' else 'buy' amount_required = 0.0 amount_obtained =",
"return self._make_api_object(response, APIObject) def get_socket(self, debug=False): \"\"\"returns a socket connection with cryptomkt. \"\"\"",
"order): return None params = dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION,",
"trades from, inclusive. end: The earlier date to get trades from, exclusive. page:",
"None): \"\"\"Notifies a deposit from your bank account to your wallet (fiat). Required",
"data is None: raise build_api_error(response, blob) # Warn the user about each warning",
"order_list: if 'id' not in order: return None params = dict( ids=json.dumps(order_list, sort_keys=True,",
"bank_account: The address (id) of the bank account from which you deposited. Extra",
"If no start date is given, returns trades since 2020-02-17. If no end",
"encode_params class Client(object): BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION = 'v2' def __init__(self, api_key, api_secret,",
"# Authenticated endpoints #------------------------------------------------------------------- # account def get_account(self): \"\"\"returns the account information of",
"when necessary; otherwise, returns the response. \"\"\" if not str(response.status_code).startswith('2'): raise build_api_error(response) return",
"== 'sell': temp = amount_required amount_required = amount_obtained amount_obtained = temp instant =",
"no end date is given, returns trades until the present moment. Required Arguments:",
"fully qualified endpoint URIs.\"\"\" params = kwargs.get(\"params\", None) if params and isinstance(params, dict):",
"be authenticated. Optional Arguments: market: A market pair as string, if no market",
"no start date is given, returns trades since 2020-02-17. If no end date",
"amount of crypto to 'buy' or 'sell' \"\"\" rest = float(amount) book_side =",
"to your bank account. Required Arguments: amount: the amount you need to withdraw",
"0 break else: amount_obtained += amount * price amount_required += amount rest -=",
") response = self._post(self.API_VERSION, \"withdrawal\", data = params) return self._make_api_object(response, APIObject) def transfer(self,address,",
"params['start'] = start if end is not None: params['end'] = end if page",
"returns an estimate of the amount of fiat obtained and the amount of",
"direct use by API consumers. \"\"\" uri = self._create_api_uri(*relative_path_parts, **kwargs) data = kwargs.get(\"data\",",
"not 20X. Otherwise, returns the response object. Not intended for direct use by",
"member of a dict If no start date is given, returns trades since",
"currency ) if page is not None: params[\"page\"] = page if limit is",
"__init__(self, api_key, api_secret, base_api_uri=None, api_version=None, debug=False): if not api_key: raise ValueError('Missing `api_key`.') if",
"a requests `session` with the correct authentication handling.\"\"\" session = requests.session() session.auth =",
"the user. Required Arguments: currency: The currency to get all the user transactions.",
"your bank account. bank_account: The address(id) of the bank account. \"\"\" params =",
"not in order or 'amount' not in order): return None params = dict(",
"'ETHCLP'. Optional Arguments: page: Page number to query. Default is 0 limit: Number",
"params[\"limit\"] = limit response = self._get(self.API_VERSION, \"transactions\", params=params) return self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account,",
"'')) warnings.warn(message, UserWarning) pagination = blob.get('pagination', None) kwargs = { 'response': response, 'pagination':",
"a file. Extra Arguments required for Mexico: date: The date of the deposit,",
"None: params[\"tracking_code\"] = tracking_code if voucher is not None: params[\"voucher\"] = voucher response",
"last. stored in the \"data\" member of a dict If no start date",
"blob.get('data', None) # All valid responses have a \"data\" key. if data is",
"self._get(self.API_VERSION,\"prices\", params = params) return self._make_api_object(response, APIObject) # Authenticated endpoints #------------------------------------------------------------------- # account",
"def notify_deposit(self,amount,bank_account, date= None, tracking_code = None, voucher = None): \"\"\"Notifies a deposit",
"return self._make_api_object(response, APIObject) def cancel_order(self, id): \"\"\"Cancel an order given its id. Required",
"to query. Default is 0 limit: Number of orders returned in each page.",
"price: The price to ask or bid for one unit of crypto side:",
"return self._make_api_object(response, APIObject) def get_instant(self,market, side, amount): \"\"\"If side is sell, returns an",
"parts)) + '?%s' % urlencode(params)) else: url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return url",
"obtain it. Required Arguments: market: The market to get the estimate of the",
"code of the deposit. voucher: a file. \"\"\" params = dict( amount =",
"params = params) return self._make_api_object(response, APIObject) # Authenticated endpoints #------------------------------------------------------------------- # account def",
"book_side == 'sell': temp = amount_required amount_required = amount_obtained amount_obtained = temp instant",
"params[\"voucher\"] = voucher response = self._post(self.API_VERSION, \"deposit\", data = params) return self._make_api_object(response,APIObject) def",
"= self._get(\"v2\", \"socket/auth\") return self._make_api_object(response, APIObject) def get_socket(self, debug=False): \"\"\"returns a socket connection",
"order, given the order id. Required Arguments: id: The identification of the order.",
"is given, returns trades since 2020-02-17. If no end date is given, returns",
"dict): url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) + '?%s' % urlencode(params)) else: url =",
"'buy' or 'sell' the crypto type: one of the keywords 'market', 'limit', 'stop_limit'",
"= tracking_code if voucher is not None: params[\"voucher\"] = voucher response = self._post(self.API_VERSION,",
"warnings from .auth import HMACAuth from .compat import imap from .compat import quote",
"\"\"\"returns a list of the active orders of the user in a given",
"def cancel_multi_orders(self, order_list): for order in order_list: if 'id' not in order: return",
"= blob.get('data', None) # All valid responses have a \"data\" key. if data",
"get_book(self, market, side, page=None, limit=None): \"\"\"Returns a list of active orders of a",
"limit=None): \"\"\"returns the list of the executed orders of the user on a",
"if params and isinstance(params, dict): url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) + '?%s' %",
"are returned. e.g: 'EHTARS'. \"\"\" params = {} if market: params['market'] = market",
"of crypto to 'buy' or 'sell' \"\"\" rest = float(amount) book_side = 'sell'",
"= getattr(self.session, method)(uri, **kwargs) return self._handle_response(response) def _handle_response(self, response): \"\"\"Internal helper for handling",
"on a given market. Required Arguments: market: A market pair as a string.",
"The address of the wallet to transfer money. amount: The amount of money",
"= memo response = self._post(self.API_VERSION, \"transfer\", data = params) return self._make_api_object(response, APIObject) def",
"of a market (candles on the market prices graph), given a timeframe. The",
"is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'executed', params=params) return",
"raise build_api_error(response) return response def _get(self, *args, **kwargs): return self._request('get', *args, **kwargs) def",
"of orders returned in each page. Default is 20. \"\"\" params = dict(",
"params[\"tracking_code\"] = tracking_code if voucher is not None: params[\"voucher\"] = voucher response =",
"\"\"\" params = dict( amount = amount, bank_account = bank_account ) response =",
"type=type, ) response = self._post(self.API_VERSION, 'orders', 'create', data=params) return self._make_api_object(response, APIObject) def create_multi_orders(self,",
"market pair is provided, the market state of all the market pairs are",
"market (candles on the market prices graph), given a timeframe. The earlier prices",
"needed. self.socket = None def _build_session(self, auth_class, *args, **kwargs): \"\"\"Internal helper for creating",
"obtained and the amount of fiat required to obtain it. Required Arguments: market:",
"urljoin from .compat import urlencode from .error import build_api_error from .model import APIObject",
"is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION,\"prices\", params = params) return",
"each warning that was returned. warnings_data = blob.get('warnings', None) for warning_blob in warnings_data",
"requests import time import warnings from .auth import HMACAuth from .compat import imap",
"If no end date is given, returns trades until the present moment. Required",
"of crypto to be buyed or selled. market: A market pair as a",
"\"data\" member of a dict. \"\"\" response = self._get(self.API_VERSION, 'market') return self._make_api_object(response, APIObject)",
"object. Not intended for direct use by API consumers. \"\"\" uri = self._create_api_uri(*relative_path_parts,",
"the specified argument. Required Arguments: amount: The amount of crypto to be buyed",
"available in Cryptomkt as the \"data\" member of a dict. \"\"\" response =",
"= page + 1 if book_side == 'sell': temp = amount_required amount_required =",
"'buy' or 'sell'. Optional Arguments: page: Page number to query. Default is 0",
"\"transactions\", params=params) return self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account, date= None, tracking_code = None, voucher",
"'https://api.cryptomkt.com/' API_VERSION = 'v2' def __init__(self, api_key, api_secret, base_api_uri=None, api_version=None, debug=False): if not",
"in order or 'amount' not in order): return None params = dict( orders=json.dumps(order_list,",
"if limit is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'trades', params=params)",
"Otherwise, returns the response object. Not intended for direct use by API consumers.",
"amount: the amount you need to withdraw to your bank account. bank_account: The",
"a list of the active orders of the user in a given market.",
"api_secret, base_api_uri=None, api_version=None, debug=False): if not api_key: raise ValueError('Missing `api_key`.') if not api_secret:",
"tracking_code = None, voucher = None): \"\"\"Notifies a deposit from your bank account",
"and the older last. stored in the \"data\" member of a dict If",
"is 20. \"\"\" params = dict( market=market ) if page is not None:",
"absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals",
"parts))) return url def _request(self, method, *relative_path_parts, **kwargs): \"\"\"Internal helper for creating HTTP",
"not None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'executed', params=params) return self._make_api_object(response,",
"in a different API base. self.BASE_API_URI = check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION = api_version",
"status of an order, given the order id. Required Arguments: id: The identification",
"rest = 0 break else: amount_obtained += amount * price amount_required += amount",
"'sell' amount: Is the amount of crypto to 'buy' or 'sell' \"\"\" rest",
"-= amount if rest == 0 or len(book_page['data']) < n_entries: break else: time.sleep(3)",
"= page if limit is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION,\"prices\",",
"an estimate of the amount ofOrder crypto obtained and the amount of fiat",
"amount of money to transfer into the wallet. currency: The wallet from which",
"('market' not in order or 'type' not in order or 'side' not in",
"actual bid and ask, the volume and price, and the low and high",
"end date is given, returns trades until the present moment. Required Arguments: market:",
"list of the active orders of the user in a given market. Required",
"return self._make_api_object(response, APIObject) def get_book(self, market, side, page=None, limit=None): \"\"\"Returns a list of",
"\"\"\" params = dict( address = address, amount = amount, currency = currency",
"def get_balance(self): \"\"\"returns the balance of the user. \"\"\" response = self._get(self.API_VERSION, 'balance')",
"isinstance(data, dict): obj = new_api_object(self, data, model_type, **kwargs) else: obj = APIObject(self, **kwargs)",
"time.sleep(3) page = page + 1 if book_side == 'sell': temp = amount_required",
"get_trades(self, market, start=None, end=None, page=None, limit=None): \"\"\"returns a list of all trades (executed",
"'orders', 'cancel', data=params) return self._make_api_object(response, APIObject) def cancel_multi_orders(self, order_list): for order in order_list:",
"of active orders of a given side in a specified market pair. stored",
"appropriate exceptions when necessary; otherwise, returns the response. \"\"\" if not str(response.status_code).startswith('2'): raise",
"not requiere to be authenticated. Optional Arguments: market: A market pair as string,",
"Default is 20. \"\"\" params = dict( market = market, timeframe = timeframe",
"'side' not in order or 'amount' not in order): return None params =",
"data=params) return self._make_api_object(response, APIObject) def get_instant(self,market, side, amount): \"\"\"If side is sell, returns",
"all the user transactions. Optional Arguments: page: Page number to query. Default is",
"price to ask or bid for one unit of crypto side: 'buy' or",
"obj = new_api_object(self, data, model_type, **kwargs) else: obj = APIObject(self, **kwargs) obj.data =",
"20. \"\"\" params = dict( market=market ) if page is not None: params['page']",
"limit response = self._get(self.API_VERSION,\"prices\", params = params) return self._make_api_object(response, APIObject) # Authenticated endpoints",
"Extra Arguments required for Mexico: date: The date of the deposit, in format",
"e.g: 'EHTARS'. \"\"\" params = {} if market: params['market'] = market response =",
"self._handle_response(response) def _handle_response(self, response): \"\"\"Internal helper for handling API responses from the CryptoMarket",
"as the \"data\" member of a dict. \"\"\" response = self._get(self.API_VERSION, 'market') return",
"given side in a specified market pair. stored in the \"data\" member of",
"self._post(self.API_VERSION, 'orders', 'create', data=params) return self._make_api_object(response, APIObject) def create_multi_orders(self, order_list): for order in",
"of the user. \"\"\" response = self._get(self.API_VERSION, 'balance') return self._make_api_object(response, APIObject) def get_transactions(self,",
"dict Required Arguments: market: A market pair as a string. Is the specified",
"None: params['page'] = page if limit is not None: params['limit'] = limit response",
"Required Arguments: amount: The amount deposited to your wallet. bank_account: The address (id)",
"and ask, the volume and price, and the low and high of the",
"a requests session for interacting with the API. self.session = self._build_session(HMACAuth, api_key, api_secret,",
"price amount_required += rest rest = 0 break else: amount_obtained += amount *",
"fiat required to obtain it. Required Arguments: market: The market to get the",
"**kwargs): return self._request('get', *args, **kwargs) def _post(self, *args, **kwargs): return self._request('post', *args, **kwargs)",
"type: one of the keywords 'market', 'limit', 'stop_limit' \"\"\" params = dict( amount=amount,",
"n_entries: break else: time.sleep(3) page = page + 1 if book_side == 'sell':",
"self._get(self.API_VERSION, 'book', params=params) return self._make_api_object(response, APIObject) def get_trades(self, market, start=None, end=None, page=None, limit=None):",
"specified market to get the book from. e.g: 'ETHCLP'. Optional Arguments: start: The",
"def create_multi_orders(self, order_list): for order in order_list: if ('market' not in order or",
"Is the specified market to get the book from. e.g: 'ETHCLP'. Optional Arguments:",
"1, 5, 15, 60, 240, 1440 and 10080. Optional Arguments: page: Page number",
"response = self._get(self.API_VERSION, 'orders', 'executed', params=params) return self._make_api_object(response, APIObject) def create_order(self, market, amount,",
"get the estimate of the transaction. side: 'buy' or 'sell' amount: Is the",
"= params) return self._make_api_object(response, APIObject) # Authenticated endpoints #------------------------------------------------------------------- # account def get_account(self):",
"identification of the order. \"\"\" params = dict( id=id ) response = self._get(self.API_VERSION,",
"side, type): \"\"\"creates an orders from the specified argument. Required Arguments: amount: The",
"_create_api_uri(self, *parts, **kwargs): \"\"\"Internal helper for creating fully qualified endpoint URIs.\"\"\" params =",
"def _handle_response(self, response): \"\"\"Internal helper for handling API responses from the CryptoMarket server.",
"deposited. Extra Arguments required for Brazil and the European Union: voucher: a file.",
"the balance of the user. \"\"\" response = self._get(self.API_VERSION, 'balance') return self._make_api_object(response, APIObject)",
"market, amount, price, side, type): \"\"\"creates an orders from the specified argument. Required",
"member of a dict. \"\"\" response = self._get(self.API_VERSION, 'market') return self._make_api_object(response, APIObject) def",
"'ETH' memo (optional): memo of the wallet to transfer money. \"\"\" params =",
"self._post(self.API_VERSION, \"deposit\", data = params) return self._make_api_object(response,APIObject) def notify_withdrawal(self, amount, bank_account): \"\"\"Notifies a",
"# session.headers.update({'Content-type': 'application/json'}) return session def _create_api_uri(self, *parts, **kwargs): \"\"\"Internal helper for creating",
"= self._get(self.API_VERSION, 'orders', 'executed', params=params) return self._make_api_object(response, APIObject) def create_order(self, market, amount, price,",
"\"\"\"Notifies a deposit from your bank account to your wallet (fiat). Required Arguments:",
") if page is not None and isinstance(page, int): params['page'] = page if",
"\"data\" member of a dict If no start date is given, returns trades",
"string. Is the specified market to get the book from. e.g: 'ETHEUR'. side:",
"= limit response = self._get(self.API_VERSION, \"transactions\", params=params) return self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account, date=",
"None) for warning_blob in warnings_data or []: message = \"%s (%s)\" % (",
"every candle in minutes. accepted values are 1, 5, 15, 60, 240, 1440",
"if market: params['market'] = market response = self._get(self.API_VERSION, 'ticker', params=params) return self._make_api_object(response, APIObject)",
"the amount ofOrder crypto obtained and the amount of fiat required to obtain",
"\"%s (%s)\" % ( warning_blob.get('message', ''), warning_blob.get('url', '')) warnings.warn(message, UserWarning) pagination = blob.get('pagination',",
"self._make_api_object(response, APIObject) def get_prices(self, market, timeframe, page = None, limit = None): \"\"\"returns",
"\"\"\"returns a list of all trades (executed orders) of a market between the",
"address = address, amount = amount, currency = currency ) if memo is",
"data = params) return self._make_api_object(response, APIObject) def get_auth_socket(self): \"\"\"returns the userid and the",
"passing in a different API base. self.BASE_API_URI = check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION =",
"id): \"\"\"Cancel an order given its id. Required Arguments: id: The identification of",
"limit=None): \"\"\"Returns a list of active orders of a given side in a",
"data and isinstance(data, dict): kwargs['data'] = data response = getattr(self.session, method)(uri, **kwargs) return",
"params['market'] = market response = self._get(self.API_VERSION, 'ticker', params=params) return self._make_api_object(response, APIObject) def get_book(self,",
"of a given side in a specified market pair. stored in the \"data\"",
"the earlier trades first, and the older last. stored in the \"data\" member",
"= 'https://api.cryptomkt.com/' API_VERSION = 'v2' def __init__(self, api_key, api_secret, base_api_uri=None, api_version=None, debug=False): if",
"response. \"\"\" if not str(response.status_code).startswith('2'): raise build_api_error(response) return response def _get(self, *args, **kwargs):",
"dict( address = address, amount = amount, currency = currency ) if memo",
"to get the book from. e.g: 'ETHCLP'. Optional Arguments: page: Page number to",
"response = self._post(self.API_VERSION, \"deposit\", data = params) return self._make_api_object(response,APIObject) def notify_withdrawal(self, amount, bank_account):",
"\"data\" member of a dict. Required Arguments: market: A market pair as a",
"low and high of the market. Stored in the \"data\" member of a",
"not None: params[\"limit\"] = limit response = self._get(self.API_VERSION, \"transactions\", params=params) return self._make_api_object(response, APIObject)",
"\"\"\"Cancel an order given its id. Required Arguments: id: The identification of the",
"separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'cancel', 'bulk', data=params) return self._make_api_object(response, APIObject) def",
"dict. Does not requiere to be authenticated. Optional Arguments: market: A market pair",
"params) return self._make_api_object(response, APIObject) def get_auth_socket(self): \"\"\"returns the userid and the socket ids",
"*args, **kwargs) def _make_api_object(self, response, model_type=None): blob = response.json() data = blob.get('data', None)",
"url def _request(self, method, *relative_path_parts, **kwargs): \"\"\"Internal helper for creating HTTP requests to",
"returns trades until the present moment. Required Arguments: market: A market pair as",
"'sell'. Optional Arguments: page: Page number to query. Default is 0 limit: Number",
"else: amount_obtained += amount * price amount_required += amount rest -= amount if",
"build_api_error from .model import APIObject from .model import new_api_object from .socket import Socket",
"for interacting with the API. self.session = self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION) # a",
"\"\"\" response = self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) # orders def get_active_orders(self, market, page=None, limit=None):",
") if start is not None: params['start'] = start if end is not",
"between the start date, until the end date. the earlier trades first, and",
"import requests import time import warnings from .auth import HMACAuth from .compat import",
"candle in minutes. accepted values are 1, 5, 15, 60, 240, 1440 and",
"\"deposit\", data = params) return self._make_api_object(response,APIObject) def notify_withdrawal(self, amount, bank_account): \"\"\"Notifies a withdrawal",
"get_socket(self, debug=False): \"\"\"returns a socket connection with cryptomkt. \"\"\" if self.socket is None:",
"address, amount = amount, currency = currency ) if memo is not None:",
"from fiat wallet to your bank account. Required Arguments: amount: the amount you",
"get_account(self): \"\"\"returns the account information of the user. Name, email, rate and bank",
"params=params) return self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account, date= None, tracking_code = None, voucher =",
"from, exclusive. page: Page number to query. Default is 0 limit: Number of",
"\"\"\"creates an orders from the specified argument. Required Arguments: amount: The amount of",
"a given side in a specified market pair. stored in the \"data\" member",
"= 0 n_entries = 100 while True: book_page = self.get_book(market, book_side, page=page, limit=n_entries)",
"= page if limit is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION,",
"None) if params and isinstance(params, dict): url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) + '?%s'",
"page=None, limit=None): \"\"\"returns a list of all trades (executed orders) of a market",
"amount: The amount of money to transfer into the wallet. currency: The wallet",
"warnings_data = blob.get('warnings', None) for warning_blob in warnings_data or []: message = \"%s",
"the userid and the socket ids to permit a socket connection with cryptomkt.",
"if the response is not 20X. Otherwise, returns the response object. Not intended",
"sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'create', 'bulk', data=params) return self._make_api_object(response, APIObject)",
"*args, **kwargs): \"\"\"Internal helper for creating a requests `session` with the correct authentication",
"the book from. e.g: 'ETHCLP'. Optional Arguments: start: The older date to get",
"side in a specified market pair. stored in the \"data\" member of a",
"instant #Wallet def get_balance(self): \"\"\"returns the balance of the user. \"\"\" response =",
"( warning_blob.get('message', ''), warning_blob.get('url', '')) warnings.warn(message, UserWarning) pagination = blob.get('pagination', None) kwargs =",
"order id. Required Arguments: id: The identification of the order. \"\"\" params =",
"self._post(self.API_VERSION, 'orders', 'cancel', data=params) return self._make_api_object(response, APIObject) def cancel_multi_orders(self, order_list): for order in",
"book from. e.g: 'ETHCLP'. Optional Arguments: page: Page number to query. Default is",
"ask, the volume and price, and the low and high of the market.",
"memo of the wallet to transfer money. \"\"\" params = dict( address =",
"the start date, until the end date. the earlier trades first, and the",
"the transactions of a currency of the user. Required Arguments: currency: The currency",
"pagination, APIObject), 'warnings': warnings_data and new_api_object(None, warnings_data, APIObject), } if isinstance(data, dict): obj",
"Required Arguments: currency: The currency to get all the user transactions. Optional Arguments:",
"book from. e.g: 'ETHEUR'. side: 'buy' or 'sell'. Optional Arguments: page: Page number",
"10080. Optional Arguments: page: Page number to query. Default is 0 limit: Number",
"from __future__ import unicode_literals import json import requests import time import warnings from",
"params = dict( market=market ) if start is not None: params['start'] = start",
"'warnings': warnings_data and new_api_object(None, warnings_data, APIObject), } if isinstance(data, dict): obj = new_api_object(self,",
"list of the marketpairs as strings available in Cryptomkt as the \"data\" member",
"None and isinstance(page, int): params['page'] = page if limit is not None and",
"None params = dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'cancel',",
"side: 'buy' or 'sell' amount: Is the amount of crypto to 'buy' or",
"A market pair as string, if no market pair is provided, the market",
"= limit response = self._get(self.API_VERSION, 'trades', params=params) return self._make_api_object(response, APIObject) def get_prices(self, market,",
"api_key: raise ValueError('Missing `api_key`.') if not api_secret: raise ValueError('Missing `api_secret`.') # Allow passing",
"self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account, date= None, tracking_code = None, voucher = None): \"\"\"Notifies",
"order or 'side' not in order or 'amount' not in order): return None",
"self._make_api_object(response, APIObject) def cancel_order(self, id): \"\"\"Cancel an order given its id. Required Arguments:",
"the money. e.g. 'ETH' memo (optional): memo of the wallet to transfer money.",
"if page is not None: params[\"page\"] = page if limit is not None:",
"# Warn the user about each warning that was returned. warnings_data = blob.get('warnings',",
"def get_executed_orders(self, market, page=None, limit=None): \"\"\"returns the list of the executed orders of",
"(%s)\" % ( warning_blob.get('message', ''), warning_blob.get('url', '')) warnings.warn(message, UserWarning) pagination = blob.get('pagination', None)",
"from .compat import urljoin from .compat import urlencode from .error import build_api_error from",
"else: obj = APIObject(self, **kwargs) obj.data = new_api_object(self, data, model_type) return obj #",
"The market to get the estimate of the transaction. side: 'buy' or 'sell'",
"= float(entry['amount']) if rest < amount: amount_obtained += rest * price amount_required +=",
"transactions. Optional Arguments: page: Page number to query. Default is 0 limit: Number",
"warning_blob.get('url', '')) warnings.warn(message, UserWarning) pagination = blob.get('pagination', None) kwargs = { 'response': response,",
"if limit is not None and isinstance(limit, int): params['limit'] = limit response =",
"\"\"\"Internal helper for creating HTTP requests to the CryptoMarket API. Raises an APIError",
"is not None: params[\"tracking_code\"] = tracking_code if voucher is not None: params[\"voucher\"] =",
"`session` with the correct authentication handling.\"\"\" session = requests.session() session.auth = auth_class(*args, **kwargs)",
"estimate of the amount ofOrder crypto obtained and the amount of fiat required",
"response = self._get(self.API_VERSION, 'trades', params=params) return self._make_api_object(response, APIObject) def get_prices(self, market, timeframe, page",
"self._get(self.API_VERSION, 'orders', 'active', params=params) return self._make_api_object(response, APIObject) def get_executed_orders(self, market, page=None, limit=None): \"\"\"returns",
"CryptoMarket server. Raises the appropriate exceptions when necessary; otherwise, returns the response. \"\"\"",
"one unit of crypto side: 'buy' or 'sell' the crypto type: one of",
"the prices of a market (candles on the market prices graph), given a",
"from your bank account to your wallet (fiat). Required Arguments: amount: The amount",
"timeframe: timelapse between every candle in minutes. accepted values are 1, 5, 15,",
"is not None: params['start'] = start if end is not None: params['end'] =",
"of fiat obtained and the amount of crypto required to obatin it. If",
"and isinstance(data, dict): kwargs['data'] = data response = getattr(self.session, method)(uri, **kwargs) return self._handle_response(response)",
"return session def _create_api_uri(self, *parts, **kwargs): \"\"\"Internal helper for creating fully qualified endpoint",
"get_prices(self, market, timeframe, page = None, limit = None): \"\"\"returns a list of",
"limit response = self._get(self.API_VERSION, \"transactions\", params=params) return self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account, date= None,",
"to withdraw to your bank account. bank_account: The address(id) of the bank account.",
"market=market, side=side ) if page is not None and isinstance(page, int): params['page'] =",
"params) return self._make_api_object(response, APIObject) # Authenticated endpoints #------------------------------------------------------------------- # account def get_account(self): \"\"\"returns",
"to your wallet. bank_account: The address (id) of the bank account from which",
"get_order_status(self, id): \"\"\"returns the present status of an order, given the order id.",
"from the specified argument. Required Arguments: amount: The amount of crypto to be",
"market pairs are returned. e.g: 'EHTARS'. \"\"\" params = {} if market: params['market']",
"of the deposit, in format dd/mm/yyyy. tracking_code: The tracking code of the deposit.",
"2020-02-17. If no end date is given, returns trades until the present moment.",
"import urljoin from .compat import urlencode from .error import build_api_error from .model import",
"params['end'] = end if page is not None: params['page'] = page if limit",
") response = self._get(self.API_VERSION, 'orders', 'status', params=params) return self._make_api_object(response, APIObject) def cancel_order(self, id):",
"amount_obtained += amount * price amount_required += amount rest -= amount if rest",
"# account def get_account(self): \"\"\"returns the account information of the user. Name, email,",
"helper for creating fully qualified endpoint URIs.\"\"\" params = kwargs.get(\"params\", None) if params",
"market, timeframe = timeframe ) if page is not None: params[\"page\"] = page",
"server. Raises the appropriate exceptions when necessary; otherwise, returns the response. \"\"\" if",
"= amount, currency = currency ) if memo is not None: params[\"memo\"] =",
"= temp instant = dict(obtained=amount_obtained, required=amount_required) return instant #Wallet def get_balance(self): \"\"\"returns the",
"limit is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'executed', params=params)",
"amount): \"\"\"If side is sell, returns an estimate of the amount of fiat",
"for Mexico: date: The date of the deposit, in format dd/mm/yyyy. tracking_code: The",
"of crypto side: 'buy' or 'sell' the crypto type: one of the keywords",
"\"\"\"If side is sell, returns an estimate of the amount of fiat obtained",
"obtained and the amount of crypto required to obatin it. If side is",
"rest rest = 0 break else: amount_obtained += amount * price amount_required +=",
"def get_account(self): \"\"\"returns the account information of the user. Name, email, rate and",
"self._make_api_object(response, APIObject) def get_auth_socket(self): \"\"\"returns the userid and the socket ids to permit",
"from which to take the money. e.g. 'ETH' memo (optional): memo of the",
"is not None and isinstance(page, int): params['page'] = page if limit is not",
"are 1, 5, 15, 60, 240, 1440 and 10080. Optional Arguments: page: Page",
"market, side, page=None, limit=None): \"\"\"Returns a list of active orders of a given",
"response = self._get(self.API_VERSION,\"prices\", params = params) return self._make_api_object(response, APIObject) # Authenticated endpoints #-------------------------------------------------------------------",
"**kwargs) data = kwargs.get(\"data\", None) if data and isinstance(data, dict): kwargs['data'] = data",
"return None params = dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders',",
"= urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) + '?%s' % urlencode(params)) else: url = urljoin(self.BASE_API_URI, '/'.join(imap(quote,",
"The date of the deposit, in format dd/mm/yyyy. tracking_code: The tracking code of",
"self._make_api_object(response, APIObject) def get_ticker(self, market=None): \"\"\"Returns a general view of the market state",
"data response = getattr(self.session, method)(uri, **kwargs) return self._handle_response(response) def _handle_response(self, response): \"\"\"Internal helper",
"response): \"\"\"Internal helper for handling API responses from the CryptoMarket server. Raises the",
"self.BASE_API_URI) self.API_VERSION = api_version or self.API_VERSION self.socket = None # Set up a",
"0.0 page = 0 n_entries = 100 while True: book_page = self.get_book(market, book_side,",
"Required Arguments: market: A market pair as a string. Is the specified market",
"limit=None): \"\"\"returns a list of all trades (executed orders) of a market between",
"If side is buy, returns an estimate of the amount ofOrder crypto obtained",
"authenticated. Optional Arguments: market: A market pair as string, if no market pair",
"\"data\" key. if data is None: raise build_api_error(response, blob) # Warn the user",
"from .model import APIObject from .model import new_api_object from .socket import Socket from",
"'sell' \"\"\" rest = float(amount) book_side = 'sell' if side == 'buy' else",
"list of the prices of a market (candles on the market prices graph),",
"\"data\" member of a dict. Does not requiere to be authenticated. Optional Arguments:",
".model import APIObject from .model import new_api_object from .socket import Socket from .util",
"= dict(obtained=amount_obtained, required=amount_required) return instant #Wallet def get_balance(self): \"\"\"returns the balance of the",
"= self._post(self.API_VERSION, 'orders', 'cancel', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_instant(self,market, side, amount):",
"def get_order_status(self, id): \"\"\"returns the present status of an order, given the order",
"kwargs.get(\"params\", None) if params and isinstance(params, dict): url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) +",
"self._request('post', *args, **kwargs) def _make_api_object(self, response, model_type=None): blob = response.json() data = blob.get('data',",
"valid responses have a \"data\" key. if data is None: raise build_api_error(response, blob)",
"limit=None): \"\"\"returns a list of the active orders of the user in a",
"warning_blob.get('message', ''), warning_blob.get('url', '')) warnings.warn(message, UserWarning) pagination = blob.get('pagination', None) kwargs = {",
"get_executed_orders(self, market, page=None, limit=None): \"\"\"returns the list of the executed orders of the",
"buyed or selled. market: A market pair as a string. Is the specified",
"pairs are returned. e.g: 'EHTARS'. \"\"\" params = {} if market: params['market'] =",
"The currency to get all the user transactions. Optional Arguments: page: Page number",
"def _get(self, *args, **kwargs): return self._request('get', *args, **kwargs) def _post(self, *args, **kwargs): return",
"APIError if the response is not 20X. Otherwise, returns the response object. Not",
"trades since 2020-02-17. If no end date is given, returns trades until the",
"get the book from. e.g: 'ETHEUR'. side: 'buy' or 'sell'. Optional Arguments: page:",
"as string, if no market pair is provided, the market state of all",
"= bank_account ) response = self._post(self.API_VERSION, \"withdrawal\", data = params) return self._make_api_object(response, APIObject)",
"def _post(self, *args, **kwargs): return self._request('post', *args, **kwargs) def _make_api_object(self, response, model_type=None): blob",
"limit response = self._get(self.API_VERSION, 'orders', 'executed', params=params) return self._make_api_object(response, APIObject) def create_order(self, market,",
"view of the market state as a dict. Shows the actual bid and",
"account to your wallet (fiat). Required Arguments: amount: The amount deposited to your",
"params[\"date\"] = date if tracking_code is not None: params[\"tracking_code\"] = tracking_code if voucher",
"if not api_secret: raise ValueError('Missing `api_secret`.') # Allow passing in a different API",
"self._make_api_object(response, APIObject) def get_order_status(self, id): \"\"\"returns the present status of an order, given",
"the market pairs are returned. e.g: 'EHTARS'. \"\"\" params = {} if market:",
"not None and isinstance(page, int): params['page'] = page if limit is not None",
"ValueError('Missing `api_key`.') if not api_secret: raise ValueError('Missing `api_secret`.') # Allow passing in a",
"the \"data\" member of a dict. Does not requiere to be authenticated. Optional",
"from .util import encode_params class Client(object): BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION = 'v2' def",
"in e.g: 'ETHCLP'. price: The price to ask or bid for one unit",
"crypto side: 'buy' or 'sell' the crypto type: one of the keywords 'market',",
"else 'buy' amount_required = 0.0 amount_obtained = 0.0 page = 0 n_entries =",
"information of the user. Name, email, rate and bank accounts. \"\"\" response =",
"of the market. Stored in the \"data\" member of a dict. Does not",
"earlier trades first, and the older last. stored in the \"data\" member of",
"to get the estimate of the transaction. side: 'buy' or 'sell' amount: Is",
"amount_required = 0.0 amount_obtained = 0.0 page = 0 n_entries = 100 while",
"\"\"\"returns the balance of the user. \"\"\" response = self._get(self.API_VERSION, 'balance') return self._make_api_object(response,",
"obj = APIObject(self, **kwargs) obj.data = new_api_object(self, data, model_type) return obj # Public",
"APIObject) def get_book(self, market, side, page=None, limit=None): \"\"\"Returns a list of active orders",
"get the book from. e.g: 'ETHCLP'. Optional Arguments: start: The older date to",
"the specified market to get the book from. e.g: 'ETHCLP'. timeframe: timelapse between",
"amount: The amount of crypto to be buyed or selled. market: A market",
"= self._get(self.API_VERSION, 'book', params=params) return self._make_api_object(response, APIObject) def get_trades(self, market, start=None, end=None, page=None,",
"self.get_book(market, book_side, page=page, limit=n_entries) for entry in book_page['data']: price = float(entry['price']) amount =",
"an estimate of the amount of fiat obtained and the amount of crypto",
"the order. \"\"\" params = dict( id=id ) response = self._get(self.API_VERSION, 'orders', 'status',",
"return self._request('get', *args, **kwargs) def _post(self, *args, **kwargs): return self._request('post', *args, **kwargs) def",
"handling.\"\"\" session = requests.session() session.auth = auth_class(*args, **kwargs) # session.headers.update({'Content-type': 'application/json'}) return session",
"if limit is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION,\"prices\", params =",
"import division from __future__ import print_function from __future__ import unicode_literals import json import",
"----------------------------------------------------------- def get_markets(self): \"\"\"Returns a list of the marketpairs as strings available in",
"from .socket import Socket from .util import check_uri_security from .util import encode_params class",
"the user. Name, email, rate and bank accounts. \"\"\" response = self._get(self.API_VERSION,\"account\") return",
"a given market. Required Arguments: market: A market pair as a string. Is",
"amount, currency = currency ) if memo is not None: params[\"memo\"] = memo",
"(executed orders) of a market between the start date, until the end date.",
"requests session for interacting with the API. self.session = self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION)",
"book from. e.g: 'ETHCLP'. timeframe: timelapse between every candle in minutes. accepted values",
"'type' not in order or 'side' not in order or 'amount' not in",
"is 20. \"\"\" params = dict( market=market, side=side ) if page is not",
"specified market to get the book from. e.g: 'ETHEUR'. side: 'buy' or 'sell'.",
"= self._get(self.API_VERSION, 'trades', params=params) return self._make_api_object(response, APIObject) def get_prices(self, market, timeframe, page =",
".compat import urljoin from .compat import urlencode from .error import build_api_error from .model",
"order_list): for order in order_list: if 'id' not in order: return None params",
"return self._make_api_object(response, APIObject) def get_transactions(self, currency, page = None, limit = None): \"\"\"return",
"withdraw to your bank account. bank_account: The address(id) of the bank account. \"\"\"",
"base. self.BASE_API_URI = check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION = api_version or self.API_VERSION self.socket =",
"Client(object): BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION = 'v2' def __init__(self, api_key, api_secret, base_api_uri=None, api_version=None,",
"about each warning that was returned. warnings_data = blob.get('warnings', None) for warning_blob in",
"timelapse between every candle in minutes. accepted values are 1, 5, 15, 60,",
"bank account. Required Arguments: amount: the amount you need to withdraw to your",
"The identification of the order. \"\"\" params = dict( id=id ) response =",
"return self._make_api_object(response, APIObject) def cancel_multi_orders(self, order_list): for order in order_list: if 'id' not",
"helper for handling API responses from the CryptoMarket server. Raises the appropriate exceptions",
"its id. Required Arguments: id: The identification of the order. \"\"\" params =",
"as a dict. Shows the actual bid and ask, the volume and price,",
"and the amount of fiat required to obtain it. Required Arguments: market: The",
"the response. \"\"\" if not str(response.status_code).startswith('2'): raise build_api_error(response) return response def _get(self, *args,",
"build_api_error(response) return response def _get(self, *args, **kwargs): return self._request('get', *args, **kwargs) def _post(self,",
"= bank_account ) if date is not None: params[\"date\"] = date if tracking_code",
"240, 1440 and 10080. Optional Arguments: page: Page number to query. Default is",
"'?%s' % urlencode(params)) else: url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return url def _request(self,",
"# Set up a requests session for interacting with the API. self.session =",
"list of the executed orders of the user on a given market. Required",
"amount = amount, currency = currency ) if memo is not None: params[\"memo\"]",
"response = self._post(self.API_VERSION, 'orders', 'cancel', data=params) return self._make_api_object(response, APIObject) def cancel_multi_orders(self, order_list): for",
"self.API_VERSION) # a container for the socket if needed. self.socket = None def",
"deposited to your wallet. bank_account: The address (id) of the bank account from",
"side is sell, returns an estimate of the amount of fiat obtained and",
"notify_deposit(self,amount,bank_account, date= None, tracking_code = None, voucher = None): \"\"\"Notifies a deposit from",
"\"\"\"Returns a list of active orders of a given side in a specified",
"= voucher response = self._post(self.API_VERSION, \"deposit\", data = params) return self._make_api_object(response,APIObject) def notify_withdrawal(self,",
"the transaction. side: 'buy' or 'sell' amount: Is the amount of crypto to",
"limit response = self._get(self.API_VERSION, 'trades', params=params) return self._make_api_object(response, APIObject) def get_prices(self, market, timeframe,",
"not in order or 'side' not in order or 'amount' not in order):",
"e.g: 'ETHCLP'. Optional Arguments: start: The older date to get trades from, inclusive.",
"cryptomkt. \"\"\" response = self._get(\"v2\", \"socket/auth\") return self._make_api_object(response, APIObject) def get_socket(self, debug=False): \"\"\"returns",
"returned in each page. Default is 20. \"\"\" params = dict( market=market, side=side",
"= page if limit is not None and isinstance(limit, int): params['limit'] = limit",
"data=params) return self._make_api_object(response, APIObject) def cancel_multi_orders(self, order_list): for order in order_list: if 'id'",
"was returned. warnings_data = blob.get('warnings', None) for warning_blob in warnings_data or []: message",
"response = self._get(self.API_VERSION, \"transactions\", params=params) return self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account, date= None, tracking_code",
"different API base. self.BASE_API_URI = check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION = api_version or self.API_VERSION",
"api_secret: raise ValueError('Missing `api_secret`.') # Allow passing in a different API base. self.BASE_API_URI",
"new_api_object(self, data, model_type, **kwargs) else: obj = APIObject(self, **kwargs) obj.data = new_api_object(self, data,",
"memo = None): \"\"\"transfer money between wallets. Required Arguments: adderss: The address of",
"\"\"\" response = self._get(\"v2\", \"socket/auth\") return self._make_api_object(response, APIObject) def get_socket(self, debug=False): \"\"\"returns a",
"on the market prices graph), given a timeframe. The earlier prices first and",
".error import build_api_error from .model import APIObject from .model import new_api_object from .socket",
"Is the amount of crypto to 'buy' or 'sell' \"\"\" rest = float(amount)",
"a timeframe. The earlier prices first and the older last. the list is",
"if rest < amount: amount_obtained += rest * price amount_required += rest rest",
"The amount of crypto to be buyed or selled. market: A market pair",
"a dict If no start date is given, returns trades since 2020-02-17. If",
"all the market pairs are returned. e.g: 'EHTARS'. \"\"\" params = {} if",
"from __future__ import print_function from __future__ import unicode_literals import json import requests import",
"not None: params['start'] = start if end is not None: params['end'] = end",
"is buy, returns an estimate of the amount ofOrder crypto obtained and the",
"self._make_api_object(response, APIObject) def get_trades(self, market, start=None, end=None, page=None, limit=None): \"\"\"returns a list of",
"Public API # ----------------------------------------------------------- def get_markets(self): \"\"\"Returns a list of the marketpairs as",
"Default is 20. \"\"\" params = dict( currency = currency ) if page",
"in the data member of a dict Required Arguments: market: A market pair",
"None: params[\"memo\"] = memo response = self._post(self.API_VERSION, \"transfer\", data = params) return self._make_api_object(response,",
"= blob.get('warnings', None) for warning_blob in warnings_data or []: message = \"%s (%s)\"",
"self._make_api_object(response, APIObject) def cancel_multi_orders(self, order_list): for order in order_list: if 'id' not in",
"of the transaction. side: 'buy' or 'sell' amount: Is the amount of crypto",
"**kwargs): \"\"\"Internal helper for creating a requests `session` with the correct authentication handling.\"\"\"",
"self._create_api_uri(*relative_path_parts, **kwargs) data = kwargs.get(\"data\", None) if data and isinstance(data, dict): kwargs['data'] =",
"trades (executed orders) of a market between the start date, until the end",
"a withdrawal from fiat wallet to your bank account. Required Arguments: amount: the",
"== 0 or len(book_page['data']) < n_entries: break else: time.sleep(3) page = page +",
"dict( amount = amount, bank_account = bank_account ) if date is not None:",
"cancel_order(self, id): \"\"\"Cancel an order given its id. Required Arguments: id: The identification",
"def get_transactions(self, currency, page = None, limit = None): \"\"\"return all the transactions",
"currency = currency ) if page is not None: params[\"page\"] = page if",
"% urlencode(params)) else: url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return url def _request(self, method,",
"= self._post(self.API_VERSION, \"deposit\", data = params) return self._make_api_object(response,APIObject) def notify_withdrawal(self, amount, bank_account): \"\"\"Notifies",
"of the prices of a market (candles on the market prices graph), given",
"Arguments: amount: The amount of crypto to be buyed or selled. market: A",
"intended for direct use by API consumers. \"\"\" uri = self._create_api_uri(*relative_path_parts, **kwargs) data",
"'orders', 'active', params=params) return self._make_api_object(response, APIObject) def get_executed_orders(self, market, page=None, limit=None): \"\"\"returns the",
"the specified market to get the book from. e.g: 'ETHCLP'. Optional Arguments: start:",
"for order in order_list: if ('market' not in order or 'type' not in",
"not None: params[\"memo\"] = memo response = self._post(self.API_VERSION, \"transfer\", data = params) return",
"market to get the book from. e.g: 'ETHCLP'. Optional Arguments: start: The older",
"base_api_uri=None, api_version=None, debug=False): if not api_key: raise ValueError('Missing `api_key`.') if not api_secret: raise",
"check_uri_security from .util import encode_params class Client(object): BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION = 'v2'",
"params = dict( amount = amount, bank_account = bank_account ) response = self._post(self.API_VERSION,",
"= self._post(self.API_VERSION, 'orders', 'create', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_order_status(self, id): \"\"\"returns",
"exclusive. page: Page number to query. Default is 0 limit: Number of orders",
"orders of the user in a given market. Required Arguments: market: A market",
"\"\"\"returns the list of the executed orders of the user on a given",
"data = blob.get('data', None) # All valid responses have a \"data\" key. if",
"self._post(self.API_VERSION, 'orders', 'create', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_order_status(self, id): \"\"\"returns the",
"file. \"\"\" params = dict( amount = amount, bank_account = bank_account ) if",
"to be authenticated. Optional Arguments: market: A market pair as string, if no",
"is not None and isinstance(limit, int): params['limit'] = limit response = self._get(self.API_VERSION, 'book',",
"socket connection with cryptomkt. \"\"\" if self.socket is None: auth = self.get_auth_socket() del",
"*args, **kwargs) def _post(self, *args, **kwargs): return self._request('post', *args, **kwargs) def _make_api_object(self, response,",
"Default is 20. \"\"\" params = dict( market=market ) if page is not",
"the user. \"\"\" response = self._get(self.API_VERSION, 'balance') return self._make_api_object(response, APIObject) def get_transactions(self, currency,",
"None: raise build_api_error(response, blob) # Warn the user about each warning that was",
"= limit response = self._get(self.API_VERSION, 'book', params=params) return self._make_api_object(response, APIObject) def get_trades(self, market,",
"socket connection with cryptomkt. \"\"\" response = self._get(\"v2\", \"socket/auth\") return self._make_api_object(response, APIObject) def",
"page if limit is not None and isinstance(limit, int): params['limit'] = limit response",
"amount, bank_account = bank_account ) response = self._post(self.API_VERSION, \"withdrawal\", data = params) return",
"params = dict( address = address, amount = amount, currency = currency )",
"an orders from the specified argument. Required Arguments: amount: The amount of crypto",
"page = None, limit = None): \"\"\"return all the transactions of a currency",
"container for the socket if needed. self.socket = None def _build_session(self, auth_class, *args,",
"adderss: The address of the wallet to transfer money. amount: The amount of",
"for one unit of crypto side: 'buy' or 'sell' the crypto type: one",
"a file. \"\"\" params = dict( amount = amount, bank_account = bank_account )",
"or self.API_VERSION self.socket = None # Set up a requests session for interacting",
"market state of all the market pairs are returned. e.g: 'EHTARS'. \"\"\" params",
"transfer(self,address, amount, currency, memo = None): \"\"\"transfer money between wallets. Required Arguments: adderss:",
"= self._create_api_uri(*relative_path_parts, **kwargs) data = kwargs.get(\"data\", None) if data and isinstance(data, dict): kwargs['data']",
"your wallet (fiat). Required Arguments: amount: The amount deposited to your wallet. bank_account:",
"def get_prices(self, market, timeframe, page = None, limit = None): \"\"\"returns a list",
"Number of orders returned in each page. Default is 20. \"\"\" params =",
"order in order_list: if 'id' not in order: return None params = dict(",
"self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION) # a container for the socket if needed. self.socket",
"The tracking code of the deposit. voucher: a file. \"\"\" params = dict(",
"Required Arguments: amount: the amount you need to withdraw to your bank account.",
"params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'active', params=params) return self._make_api_object(response, APIObject) def",
"= requests.session() session.auth = auth_class(*args, **kwargs) # session.headers.update({'Content-type': 'application/json'}) return session def _create_api_uri(self,",
"of the user on a given market. Required Arguments: market: A market pair",
"of a market between the start date, until the end date. the earlier",
"to get the book from. e.g: 'ETHCLP'. timeframe: timelapse between every candle in",
"for order in order_list: if 'id' not in order: return None params =",
"return self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account, date= None, tracking_code = None, voucher = None):",
"rest -= amount if rest == 0 or len(book_page['data']) < n_entries: break else:",
"keywords 'market', 'limit', 'stop_limit' \"\"\" params = dict( amount=amount, market=market, price=price, side=side, type=type,",
"params = dict( id=id ) response = self._post(self.API_VERSION, 'orders', 'cancel', data=params) return self._make_api_object(response,",
".util import encode_params class Client(object): BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION = 'v2' def __init__(self,",
"of the order. \"\"\" params = dict( id=id ) response = self._post(self.API_VERSION, 'orders',",
"*args, **kwargs): return self._request('get', *args, **kwargs) def _post(self, *args, **kwargs): return self._request('post', *args,",
"Not intended for direct use by API consumers. \"\"\" uri = self._create_api_uri(*relative_path_parts, **kwargs)",
"None: params[\"limit\"] = limit response = self._get(self.API_VERSION, \"transactions\", params=params) return self._make_api_object(response, APIObject) def",
"True: book_page = self.get_book(market, book_side, page=page, limit=n_entries) for entry in book_page['data']: price =",
"= start if end is not None: params['end'] = end if page is",
"the active orders of the user in a given market. Required Arguments: market:",
"self.session = self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION) # a container for the socket if",
"the market. Stored in the \"data\" member of a dict. Does not requiere",
"import new_api_object from .socket import Socket from .util import check_uri_security from .util import",
"each page. Default is 20. \"\"\" params = dict( currency = currency )",
"= dict( id=id ) response = self._get(self.API_VERSION, 'orders', 'status', params=params) return self._make_api_object(response, APIObject)",
"= 0 break else: amount_obtained += amount * price amount_required += amount rest",
"page if limit is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'trades',",
"be buyed or selled. market: A market pair as a string. Is the",
"= self._post(self.API_VERSION, 'orders', 'cancel', data=params) return self._make_api_object(response, APIObject) def cancel_multi_orders(self, order_list): for order",
"dict( id=id ) response = self._post(self.API_VERSION, 'orders', 'cancel', data=params) return self._make_api_object(response, APIObject) def",
"you need to withdraw to your bank account. bank_account: The address(id) of the",
"auth_class(*args, **kwargs) # session.headers.update({'Content-type': 'application/json'}) return session def _create_api_uri(self, *parts, **kwargs): \"\"\"Internal helper",
"'cancel', data=params) return self._make_api_object(response, APIObject) def cancel_multi_orders(self, order_list): for order in order_list: if",
"'/'.join(imap(quote, parts)) + '?%s' % urlencode(params)) else: url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return",
"= None, limit = None): \"\"\"return all the transactions of a currency of",
"**kwargs) def _make_api_object(self, response, model_type=None): blob = response.json() data = blob.get('data', None) #",
"and the European Union: voucher: a file. Extra Arguments required for Mexico: date:",
"book_page = self.get_book(market, book_side, page=page, limit=n_entries) for entry in book_page['data']: price = float(entry['price'])",
"of the bank account. \"\"\" params = dict( amount = amount, bank_account =",
"None) # All valid responses have a \"data\" key. if data is None:",
"= end if page is not None: params['page'] = page if limit is",
"is not None: params[\"page\"] = page if limit is not None: params[\"limit\"] =",
"= None, limit = None): \"\"\"returns a list of the prices of a",
"response = self._post(self.API_VERSION, 'orders', 'create', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_order_status(self, id):",
"from. e.g: 'ETHCLP'. Optional Arguments: page: Page number to query. Default is 0",
"\"\"\"returns the account information of the user. Name, email, rate and bank accounts.",
"order given its id. Required Arguments: id: The identification of the order. \"\"\"",
"get the book from. e.g: 'ETHCLP'. Optional Arguments: page: Page number to query.",
"the user about each warning that was returned. warnings_data = blob.get('warnings', None) for",
"urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return url def _request(self, method, *relative_path_parts, **kwargs): \"\"\"Internal helper for",
"the specified market to place the order in e.g: 'ETHCLP'. price: The price",
"in each page. Default is 20. \"\"\" params = dict( market=market ) if",
"trades from, exclusive. page: Page number to query. Default is 0 limit: Number",
"market state as a dict. Shows the actual bid and ask, the volume",
"json import requests import time import warnings from .auth import HMACAuth from .compat",
"not None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'active', params=params) return self._make_api_object(response,",
"20. \"\"\" params = dict( market = market, timeframe = timeframe ) if",
"isinstance(data, dict): kwargs['data'] = data response = getattr(self.session, method)(uri, **kwargs) return self._handle_response(response) def",
"API. Raises an APIError if the response is not 20X. Otherwise, returns the",
"if data and isinstance(data, dict): kwargs['data'] = data response = getattr(self.session, method)(uri, **kwargs)",
"from .compat import imap from .compat import quote from .compat import urljoin from",
"return self._make_api_object(response, APIObject) def get_order_status(self, id): \"\"\"returns the present status of an order,",
"None: params[\"voucher\"] = voucher response = self._post(self.API_VERSION, \"deposit\", data = params) return self._make_api_object(response,APIObject)",
"\"\"\"returns the present status of an order, given the order id. Required Arguments:",
"your bank account. Required Arguments: amount: the amount you need to withdraw to",
"\"\"\"returns a socket connection with cryptomkt. \"\"\" if self.socket is None: auth =",
"specified argument. Required Arguments: amount: The amount of crypto to be buyed or",
"return self._make_api_object(response,APIObject) # orders def get_active_orders(self, market, page=None, limit=None): \"\"\"returns a list of",
"until the end date. the earlier trades first, and the older last. stored",
"order or 'type' not in order or 'side' not in order or 'amount'",
"file. Extra Arguments required for Mexico: date: The date of the deposit, in",
"import warnings from .auth import HMACAuth from .compat import imap from .compat import",
"# All valid responses have a \"data\" key. if data is None: raise",
") if date is not None: params[\"date\"] = date if tracking_code is not",
"wallet. currency: The wallet from which to take the money. e.g. 'ETH' memo",
"dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'cancel', 'bulk', data=params) return",
"self._get(self.API_VERSION, \"transactions\", params=params) return self._make_api_object(response, APIObject) def notify_deposit(self,amount,bank_account, date= None, tracking_code = None,",
"connection with cryptomkt. \"\"\" if self.socket is None: auth = self.get_auth_socket() del auth['verify']",
"} if isinstance(data, dict): obj = new_api_object(self, data, model_type, **kwargs) else: obj =",
"Arguments: id: The identification of the order. \"\"\" params = dict( id=id )",
"the data member of a dict Required Arguments: market: A market pair as",
"self._post(self.API_VERSION, 'orders', 'cancel', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_instant(self,market, side, amount): \"\"\"If",
"the bank account. \"\"\" params = dict( amount = amount, bank_account = bank_account",
"pair. stored in the \"data\" member of a dict. Required Arguments: market: A",
"self._make_api_object(response, APIObject) def get_transactions(self, currency, page = None, limit = None): \"\"\"return all",
"the book from. e.g: 'ETHEUR'. side: 'buy' or 'sell'. Optional Arguments: page: Page",
"page=page, limit=n_entries) for entry in book_page['data']: price = float(entry['price']) amount = float(entry['amount']) if",
"the older last. the list is stored in the data member of a",
"ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'cancel', 'bulk', data=params) return self._make_api_object(response,",
"data=params) return self._make_api_object(response, APIObject) def get_order_status(self, id): \"\"\"returns the present status of an",
"# coding: utf-8 from __future__ import absolute_import from __future__ import division from __future__",
"20. \"\"\" params = dict( market=market, side=side ) if page is not None",
"self._make_api_object(response, APIObject) def get_book(self, market, side, page=None, limit=None): \"\"\"Returns a list of active",
"self._make_api_object(response, APIObject) # Authenticated endpoints #------------------------------------------------------------------- # account def get_account(self): \"\"\"returns the account",
"response, model_type=None): blob = response.json() data = blob.get('data', None) # All valid responses",
"a general view of the market state as a dict. Shows the actual",
"= APIObject(self, **kwargs) obj.data = new_api_object(self, data, model_type) return obj # Public API",
"'stop_limit' \"\"\" params = dict( amount=amount, market=market, price=price, side=side, type=type, ) response =",
"to transfer money. amount: The amount of money to transfer into the wallet.",
"\"\"\"returns the userid and the socket ids to permit a socket connection with",
"accounts. \"\"\" response = self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) # orders def get_active_orders(self, market, page=None,",
"`api_key`.') if not api_secret: raise ValueError('Missing `api_secret`.') # Allow passing in a different",
"= dict( market = market, timeframe = timeframe ) if page is not",
"email, rate and bank accounts. \"\"\" response = self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) # orders",
"__future__ import print_function from __future__ import unicode_literals import json import requests import time",
"if 'id' not in order: return None params = dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')),",
"APIObject) def create_multi_orders(self, order_list): for order in order_list: if ('market' not in order",
"end is not None: params['end'] = end if page is not None: params['page']",
"'book', params=params) return self._make_api_object(response, APIObject) def get_trades(self, market, start=None, end=None, page=None, limit=None): \"\"\"returns",
"to ask or bid for one unit of crypto side: 'buy' or 'sell'",
"_post(self, *args, **kwargs): return self._request('post', *args, **kwargs) def _make_api_object(self, response, model_type=None): blob =",
"APIObject), } if isinstance(data, dict): obj = new_api_object(self, data, model_type, **kwargs) else: obj",
"session = requests.session() session.auth = auth_class(*args, **kwargs) # session.headers.update({'Content-type': 'application/json'}) return session def",
"import json import requests import time import warnings from .auth import HMACAuth from",
"**kwargs) else: obj = APIObject(self, **kwargs) obj.data = new_api_object(self, data, model_type) return obj",
"of a dict If no start date is given, returns trades since 2020-02-17.",
"Arguments required for Brazil and the European Union: voucher: a file. Extra Arguments",
"imap from .compat import quote from .compat import urljoin from .compat import urlencode",
"+ '?%s' % urlencode(params)) else: url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return url def",
"= float(amount) book_side = 'sell' if side == 'buy' else 'buy' amount_required =",
"side, page=None, limit=None): \"\"\"Returns a list of active orders of a given side",
"id): \"\"\"returns the present status of an order, given the order id. Required",
"string. Is the specified market to get the book from. e.g: 'ETHCLP'. timeframe:",
"or len(book_page['data']) < n_entries: break else: time.sleep(3) page = page + 1 if",
"trades until the present moment. Required Arguments: market: A market pair as a",
"e.g: 'ETHCLP'. timeframe: timelapse between every candle in minutes. accepted values are 1,",
"Default is 20. \"\"\" params = dict( market=market, side=side ) if page is",
"or 'side' not in order or 'amount' not in order): return None params",
"for handling API responses from the CryptoMarket server. Raises the appropriate exceptions when",
"_handle_response(self, response): \"\"\"Internal helper for handling API responses from the CryptoMarket server. Raises",
"# Allow passing in a different API base. self.BASE_API_URI = check_uri_security(base_api_uri or self.BASE_API_URI)",
"data, model_type) return obj # Public API # ----------------------------------------------------------- def get_markets(self): \"\"\"Returns a",
"= kwargs.get(\"data\", None) if data and isinstance(data, dict): kwargs['data'] = data response =",
"'ticker', params=params) return self._make_api_object(response, APIObject) def get_book(self, market, side, page=None, limit=None): \"\"\"Returns a",
"20. \"\"\" params = dict( market=market ) if start is not None: params['start']",
"get_active_orders(self, market, page=None, limit=None): \"\"\"returns a list of the active orders of the",
"crypto required to obatin it. If side is buy, returns an estimate of",
"query. Default is 0 limit: Number of orders returned in each page. Default",
"order in order_list: if ('market' not in order or 'type' not in order",
"= amount_obtained amount_obtained = temp instant = dict(obtained=amount_obtained, required=amount_required) return instant #Wallet def",
"while True: book_page = self.get_book(market, book_side, page=page, limit=n_entries) for entry in book_page['data']: price",
"return self._make_api_object(response, APIObject) def get_executed_orders(self, market, page=None, limit=None): \"\"\"returns the list of the",
"is not None: params[\"date\"] = date if tracking_code is not None: params[\"tracking_code\"] =",
"market: A market pair as string, if no market pair is provided, the",
"bank_account = bank_account ) if date is not None: params[\"date\"] = date if",
"correct authentication handling.\"\"\" session = requests.session() session.auth = auth_class(*args, **kwargs) # session.headers.update({'Content-type': 'application/json'})",
"# a container for the socket if needed. self.socket = None def _build_session(self,",
"date. the earlier trades first, and the older last. stored in the \"data\"",
"self._get(\"v2\", \"socket/auth\") return self._make_api_object(response, APIObject) def get_socket(self, debug=False): \"\"\"returns a socket connection with",
"market to get the book from. e.g: 'ETHEUR'. side: 'buy' or 'sell'. Optional",
"isinstance(page, int): params['page'] = page if limit is not None and isinstance(limit, int):",
"None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'executed', params=params) return self._make_api_object(response, APIObject)",
"'pagination': pagination and new_api_object(None, pagination, APIObject), 'warnings': warnings_data and new_api_object(None, warnings_data, APIObject), }",
"None): \"\"\"transfer money between wallets. Required Arguments: adderss: The address of the wallet",
"amount, bank_account): \"\"\"Notifies a withdrawal from fiat wallet to your bank account. Required",
"amount_required amount_required = amount_obtained amount_obtained = temp instant = dict(obtained=amount_obtained, required=amount_required) return instant",
"the user on a given market. Required Arguments: market: A market pair as",
"bank_account ) response = self._post(self.API_VERSION, \"withdrawal\", data = params) return self._make_api_object(response, APIObject) def",
"page = page + 1 if book_side == 'sell': temp = amount_required amount_required",
"prices of a market (candles on the market prices graph), given a timeframe.",
"if limit is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'active',",
"api_key, api_secret, base_api_uri=None, api_version=None, debug=False): if not api_key: raise ValueError('Missing `api_key`.') if not",
"page=None, limit=None): \"\"\"returns a list of the active orders of the user in",
"side: 'buy' or 'sell'. Optional Arguments: page: Page number to query. Default is",
"the actual bid and ask, the volume and price, and the low and",
"params=params) return self._make_api_object(response, APIObject) def get_trades(self, market, start=None, end=None, page=None, limit=None): \"\"\"returns a",
"params = dict( market = market, timeframe = timeframe ) if page is",
"cancel_multi_orders(self, order_list): for order in order_list: if 'id' not in order: return None",
"return None params = dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders',",
"coding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import",
"orders of the user on a given market. Required Arguments: market: A market",
"page. Default is 20. \"\"\" params = dict( currency = currency ) if",
"data, model_type, **kwargs) else: obj = APIObject(self, **kwargs) obj.data = new_api_object(self, data, model_type)",
"if ('market' not in order or 'type' not in order or 'side' not",
"'trades', params=params) return self._make_api_object(response, APIObject) def get_prices(self, market, timeframe, page = None, limit",
"first, and the older last. stored in the \"data\" member of a dict",
"buy, returns an estimate of the amount ofOrder crypto obtained and the amount",
"is not None: params[\"voucher\"] = voucher response = self._post(self.API_VERSION, \"deposit\", data = params)",
"session for interacting with the API. self.session = self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION) #",
"is 20. \"\"\" params = dict( market = market, timeframe = timeframe )",
"each page. Default is 20. \"\"\" params = dict( market=market ) if page",
"to transfer into the wallet. currency: The wallet from which to take the",
"market pair as string, if no market pair is provided, the market state",
"self._make_api_object(response,APIObject) # orders def get_active_orders(self, market, page=None, limit=None): \"\"\"returns a list of the",
"from .model import new_api_object from .socket import Socket from .util import check_uri_security from",
"return self._make_api_object(response, APIObject) def get_prices(self, market, timeframe, page = None, limit = None):",
"start date, until the end date. the earlier trades first, and the older",
"ids to permit a socket connection with cryptomkt. \"\"\" response = self._get(\"v2\", \"socket/auth\")",
"for Brazil and the European Union: voucher: a file. Extra Arguments required for",
"money. amount: The amount of money to transfer into the wallet. currency: The",
"page is not None: params['page'] = page if limit is not None: params['limit']",
"\"\"\"returns a list of the prices of a market (candles on the market",
"model_type, **kwargs) else: obj = APIObject(self, **kwargs) obj.data = new_api_object(self, data, model_type) return",
"tracking_code if voucher is not None: params[\"voucher\"] = voucher response = self._post(self.API_VERSION, \"deposit\",",
"to get the book from. e.g: 'ETHEUR'. side: 'buy' or 'sell'. Optional Arguments:",
"warnings_data or []: message = \"%s (%s)\" % ( warning_blob.get('message', ''), warning_blob.get('url', ''))",
"older last. the list is stored in the data member of a dict",
"an APIError if the response is not 20X. Otherwise, returns the response object.",
"Stored in the \"data\" member of a dict. Does not requiere to be",
"of an order, given the order id. Required Arguments: id: The identification of",
"blob) # Warn the user about each warning that was returned. warnings_data =",
"market. Stored in the \"data\" member of a dict. Does not requiere to",
"page is not None: params[\"page\"] = page if limit is not None: params[\"limit\"]",
"market pair as a string. Is the specified market to place the order",
"a string. Is the specified market to place the order in e.g: 'ETHCLP'.",
"qualified endpoint URIs.\"\"\" params = kwargs.get(\"params\", None) if params and isinstance(params, dict): url",
"not None: params[\"voucher\"] = voucher response = self._post(self.API_VERSION, \"deposit\", data = params) return",
"self.API_VERSION self.socket = None # Set up a requests session for interacting with",
"'/'.join(imap(quote, parts))) return url def _request(self, method, *relative_path_parts, **kwargs): \"\"\"Internal helper for creating",
"minutes. accepted values are 1, 5, 15, 60, 240, 1440 and 10080. Optional",
"wallet to transfer money. amount: The amount of money to transfer into the",
"params['limit'] = limit response = self._get(self.API_VERSION, 'trades', params=params) return self._make_api_object(response, APIObject) def get_prices(self,",
"A market pair as a string. Is the specified market to get the",
"high of the market. Stored in the \"data\" member of a dict. Does",
") response = self._post(self.API_VERSION, 'orders', 'cancel', data=params) return self._make_api_object(response, APIObject) def cancel_multi_orders(self, order_list):",
"it. If side is buy, returns an estimate of the amount ofOrder crypto",
"the user in a given market. Required Arguments: market: A market pair as",
"dict( currency = currency ) if page is not None: params[\"page\"] = page",
"= None, voucher = None): \"\"\"Notifies a deposit from your bank account to",
"the market prices graph), given a timeframe. The earlier prices first and the",
"amount ofOrder crypto obtained and the amount of fiat required to obtain it.",
"tracking_code: The tracking code of the deposit. voucher: a file. \"\"\" params =",
"date is not None: params[\"date\"] = date if tracking_code is not None: params[\"tracking_code\"]",
"params=params) return self._make_api_object(response, APIObject) def get_book(self, market, side, page=None, limit=None): \"\"\"Returns a list",
"pair as a string. Is the specified market to get the book from.",
"of the amount of fiat obtained and the amount of crypto required to",
"response is not 20X. Otherwise, returns the response object. Not intended for direct",
"return self._make_api_object(response, APIObject) def transfer(self,address, amount, currency, memo = None): \"\"\"transfer money between",
"general view of the market state as a dict. Shows the actual bid",
"Shows the actual bid and ask, the volume and price, and the low",
"'sell' the crypto type: one of the keywords 'market', 'limit', 'stop_limit' \"\"\" params",
"is not None: params[\"memo\"] = memo response = self._post(self.API_VERSION, \"transfer\", data = params)",
"`api_secret`.') # Allow passing in a different API base. self.BASE_API_URI = check_uri_security(base_api_uri or",
"float(entry['price']) amount = float(entry['amount']) if rest < amount: amount_obtained += rest * price",
"params[\"limit\"] = limit response = self._get(self.API_VERSION,\"prices\", params = params) return self._make_api_object(response, APIObject) #",
"new_api_object(self, data, model_type) return obj # Public API # ----------------------------------------------------------- def get_markets(self): \"\"\"Returns",
"Union: voucher: a file. Extra Arguments required for Mexico: date: The date of",
"bank_account ) if date is not None: params[\"date\"] = date if tracking_code is",
"not api_key: raise ValueError('Missing `api_key`.') if not api_secret: raise ValueError('Missing `api_secret`.') # Allow",
".model import new_api_object from .socket import Socket from .util import check_uri_security from .util",
"in Cryptomkt as the \"data\" member of a dict. \"\"\" response = self._get(self.API_VERSION,",
"The price to ask or bid for one unit of crypto side: 'buy'",
"given market. Required Arguments: market: A market pair as a string. Is the",
"= self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION) # a container for the socket if needed.",
"end date. the earlier trades first, and the older last. stored in the",
"= self.get_book(market, book_side, page=page, limit=n_entries) for entry in book_page['data']: price = float(entry['price']) amount",
"returns trades since 2020-02-17. If no end date is given, returns trades until",
"specified market to place the order in e.g: 'ETHCLP'. price: The price to",
"id=id ) response = self._post(self.API_VERSION, 'orders', 'cancel', data=params) return self._make_api_object(response, APIObject) def cancel_multi_orders(self,",
"Mexico: date: The date of the deposit, in format dd/mm/yyyy. tracking_code: The tracking",
"= date if tracking_code is not None: params[\"tracking_code\"] = tracking_code if voucher is",
"estimate of the transaction. side: 'buy' or 'sell' amount: Is the amount of",
"import check_uri_security from .util import encode_params class Client(object): BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION =",
"debug=False): if not api_key: raise ValueError('Missing `api_key`.') if not api_secret: raise ValueError('Missing `api_secret`.')",
"amount of crypto to be buyed or selled. market: A market pair as",
"dict( amount=amount, market=market, price=price, side=side, type=type, ) response = self._post(self.API_VERSION, 'orders', 'create', data=params)",
"and the low and high of the market. Stored in the \"data\" member",
"= dict( id=id ) response = self._post(self.API_VERSION, 'orders', 'cancel', data=params) return self._make_api_object(response, APIObject)",
"given the order id. Required Arguments: id: The identification of the order. \"\"\"",
"crypto type: one of the keywords 'market', 'limit', 'stop_limit' \"\"\" params = dict(",
"the deposit. voucher: a file. \"\"\" params = dict( amount = amount, bank_account",
"\"socket/auth\") return self._make_api_object(response, APIObject) def get_socket(self, debug=False): \"\"\"returns a socket connection with cryptomkt.",
"if page is not None and isinstance(page, int): params['page'] = page if limit",
"in order_list: if ('market' not in order or 'type' not in order or",
"the market state as a dict. Shows the actual bid and ask, the",
"+= rest rest = 0 break else: amount_obtained += amount * price amount_required",
"def _make_api_object(self, response, model_type=None): blob = response.json() data = blob.get('data', None) # All",
"market to get the book from. e.g: 'ETHCLP'. Optional Arguments: page: Page number",
"page = None, limit = None): \"\"\"returns a list of the prices of",
"return url def _request(self, method, *relative_path_parts, **kwargs): \"\"\"Internal helper for creating HTTP requests",
"Optional Arguments: start: The older date to get trades from, inclusive. end: The",
"from. e.g: 'ETHEUR'. side: 'buy' or 'sell'. Optional Arguments: page: Page number to",
"currency, page = None, limit = None): \"\"\"return all the transactions of a",
"otherwise, returns the response. \"\"\" if not str(response.status_code).startswith('2'): raise build_api_error(response) return response def",
"string. Is the specified market to place the order in e.g: 'ETHCLP'. price:",
"required for Mexico: date: The date of the deposit, in format dd/mm/yyyy. tracking_code:",
"session.auth = auth_class(*args, **kwargs) # session.headers.update({'Content-type': 'application/json'}) return session def _create_api_uri(self, *parts, **kwargs):",
"Arguments: market: A market pair as a string. Is the specified market to",
"market to get the book from. e.g: 'ETHCLP'. timeframe: timelapse between every candle",
"= data response = getattr(self.session, method)(uri, **kwargs) return self._handle_response(response) def _handle_response(self, response): \"\"\"Internal",
"= dict( address = address, amount = amount, currency = currency ) if",
"self._get(self.API_VERSION, 'market') return self._make_api_object(response, APIObject) def get_ticker(self, market=None): \"\"\"Returns a general view of",
"is not None: params['page'] = page if limit is not None: params['limit'] =",
"bid and ask, the volume and price, and the low and high of",
"executed orders of the user on a given market. Required Arguments: market: A",
"APIObject) def get_order_status(self, id): \"\"\"returns the present status of an order, given the",
"The earlier date to get trades from, exclusive. page: Page number to query.",
"a string. Is the specified market to get the book from. e.g: 'ETHEUR'.",
"of the user in a given market. Required Arguments: market: A market pair",
"or 'type' not in order or 'side' not in order or 'amount' not",
"the crypto type: one of the keywords 'market', 'limit', 'stop_limit' \"\"\" params =",
"else: url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return url def _request(self, method, *relative_path_parts, **kwargs):",
"self.API_VERSION = api_version or self.API_VERSION self.socket = None # Set up a requests",
"market: params['market'] = market response = self._get(self.API_VERSION, 'ticker', params=params) return self._make_api_object(response, APIObject) def",
"a dict. Does not requiere to be authenticated. Optional Arguments: market: A market",
"None: params[\"limit\"] = limit response = self._get(self.API_VERSION,\"prices\", params = params) return self._make_api_object(response, APIObject)",
"'executed', params=params) return self._make_api_object(response, APIObject) def create_order(self, market, amount, price, side, type): \"\"\"creates",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function from",
"#Wallet def get_balance(self): \"\"\"returns the balance of the user. \"\"\" response = self._get(self.API_VERSION,",
"dict( market=market, side=side ) if page is not None and isinstance(page, int): params['page']",
"self._make_api_object(response, APIObject) def get_instant(self,market, side, amount): \"\"\"If side is sell, returns an estimate",
"ofOrder crypto obtained and the amount of fiat required to obtain it. Required",
"= amount, bank_account = bank_account ) if date is not None: params[\"date\"] =",
"__future__ import absolute_import from __future__ import division from __future__ import print_function from __future__",
"API consumers. \"\"\" uri = self._create_api_uri(*relative_path_parts, **kwargs) data = kwargs.get(\"data\", None) if data",
"creating fully qualified endpoint URIs.\"\"\" params = kwargs.get(\"params\", None) if params and isinstance(params,",
"response = getattr(self.session, method)(uri, **kwargs) return self._handle_response(response) def _handle_response(self, response): \"\"\"Internal helper for",
"def get_ticker(self, market=None): \"\"\"Returns a general view of the market state as a",
"bank_account): \"\"\"Notifies a withdrawal from fiat wallet to your bank account. Required Arguments:",
"account information of the user. Name, email, rate and bank accounts. \"\"\" response",
"\"\"\" params = dict( amount = amount, bank_account = bank_account ) if date",
"place the order in e.g: 'ETHCLP'. price: The price to ask or bid",
"warnings_data, APIObject), } if isinstance(data, dict): obj = new_api_object(self, data, model_type, **kwargs) else:",
"in warnings_data or []: message = \"%s (%s)\" % ( warning_blob.get('message', ''), warning_blob.get('url',",
"date if tracking_code is not None: params[\"tracking_code\"] = tracking_code if voucher is not",
"orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'create', 'bulk', data=params) return self._make_api_object(response,",
"or bid for one unit of crypto side: 'buy' or 'sell' the crypto",
"\"\"\"Internal helper for creating fully qualified endpoint URIs.\"\"\" params = kwargs.get(\"params\", None) if",
"required=amount_required) return instant #Wallet def get_balance(self): \"\"\"returns the balance of the user. \"\"\"",
"CryptoMarket API. Raises an APIError if the response is not 20X. Otherwise, returns",
"= \"%s (%s)\" % ( warning_blob.get('message', ''), warning_blob.get('url', '')) warnings.warn(message, UserWarning) pagination =",
"amount_obtained = temp instant = dict(obtained=amount_obtained, required=amount_required) return instant #Wallet def get_balance(self): \"\"\"returns",
"= { 'response': response, 'pagination': pagination and new_api_object(None, pagination, APIObject), 'warnings': warnings_data and",
"APIObject) def get_transactions(self, currency, page = None, limit = None): \"\"\"return all the",
"balance of the user. \"\"\" response = self._get(self.API_VERSION, 'balance') return self._make_api_object(response, APIObject) def",
"limit: Number of orders returned in each page. Default is 20. \"\"\" params",
"\"\"\"Notifies a withdrawal from fiat wallet to your bank account. Required Arguments: amount:",
"None: params[\"page\"] = page if limit is not None: params[\"limit\"] = limit response",
"raise build_api_error(response, blob) # Warn the user about each warning that was returned.",
"response, 'pagination': pagination and new_api_object(None, pagination, APIObject), 'warnings': warnings_data and new_api_object(None, warnings_data, APIObject),",
"page is not None and isinstance(page, int): params['page'] = page if limit is",
"(fiat). Required Arguments: amount: The amount deposited to your wallet. bank_account: The address",
"amount you need to withdraw to your bank account. bank_account: The address(id) of",
"\"transfer\", data = params) return self._make_api_object(response, APIObject) def get_auth_socket(self): \"\"\"returns the userid and",
"each page. Default is 20. \"\"\" params = dict( market=market ) if start",
") response = self._post(self.API_VERSION, 'orders', 'create', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_order_status(self,",
"return self._make_api_object(response, APIObject) def create_multi_orders(self, order_list): for order in order_list: if ('market' not",
"None, tracking_code = None, voucher = None): \"\"\"Notifies a deposit from your bank",
"book from. e.g: 'ETHCLP'. Optional Arguments: start: The older date to get trades",
"page if limit is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders',",
"of a dict. Required Arguments: market: A market pair as a string. Is",
"None: params['limit'] = limit response = self._get(self.API_VERSION, 'orders', 'active', params=params) return self._make_api_object(response, APIObject)",
"'active', params=params) return self._make_api_object(response, APIObject) def get_executed_orders(self, market, page=None, limit=None): \"\"\"returns the list",
"values are 1, 5, 15, 60, 240, 1440 and 10080. Optional Arguments: page:",
"* price amount_required += rest rest = 0 break else: amount_obtained += amount",
"amount_obtained = 0.0 page = 0 n_entries = 100 while True: book_page =",
"a container for the socket if needed. self.socket = None def _build_session(self, auth_class,",
"returned in each page. Default is 20. \"\"\" params = dict( market =",
"not None: params[\"date\"] = date if tracking_code is not None: params[\"tracking_code\"] = tracking_code",
"= params) return self._make_api_object(response, APIObject) def get_auth_socket(self): \"\"\"returns the userid and the socket",
"given its id. Required Arguments: id: The identification of the order. \"\"\" params",
"None: params[\"date\"] = date if tracking_code is not None: params[\"tracking_code\"] = tracking_code if",
".socket import Socket from .util import check_uri_security from .util import encode_params class Client(object):",
"between wallets. Required Arguments: adderss: The address of the wallet to transfer money.",
"Page number to query. Default is 0 limit: Number of orders returned in",
"= amount_required amount_required = amount_obtained amount_obtained = temp instant = dict(obtained=amount_obtained, required=amount_required) return",
"The earlier prices first and the older last. the list is stored in",
"present status of an order, given the order id. Required Arguments: id: The",
"division from __future__ import print_function from __future__ import unicode_literals import json import requests",
"= self._get(self.API_VERSION, 'balance') return self._make_api_object(response, APIObject) def get_transactions(self, currency, page = None, limit",
"= currency ) if memo is not None: params[\"memo\"] = memo response =",
"Required Arguments: market: The market to get the estimate of the transaction. side:",
"a socket connection with cryptomkt. \"\"\" response = self._get(\"v2\", \"socket/auth\") return self._make_api_object(response, APIObject)",
"marketpairs as strings available in Cryptomkt as the \"data\" member of a dict.",
"session.headers.update({'Content-type': 'application/json'}) return session def _create_api_uri(self, *parts, **kwargs): \"\"\"Internal helper for creating fully",
"argument. Required Arguments: amount: The amount of crypto to be buyed or selled.",
"requests.session() session.auth = auth_class(*args, **kwargs) # session.headers.update({'Content-type': 'application/json'}) return session def _create_api_uri(self, *parts,",
"specified market to get the book from. e.g: 'ETHCLP'. timeframe: timelapse between every",
"page=None, limit=None): \"\"\"returns the list of the executed orders of the user on",
"Brazil and the European Union: voucher: a file. Extra Arguments required for Mexico:",
"1440 and 10080. Optional Arguments: page: Page number to query. Default is 0",
"'buy' else 'buy' amount_required = 0.0 amount_obtained = 0.0 page = 0 n_entries",
"* price amount_required += amount rest -= amount if rest == 0 or",
"APIObject), 'warnings': warnings_data and new_api_object(None, warnings_data, APIObject), } if isinstance(data, dict): obj =",
"data member of a dict Required Arguments: market: A market pair as a",
"60, 240, 1440 and 10080. Optional Arguments: page: Page number to query. Default",
"rest * price amount_required += rest rest = 0 break else: amount_obtained +=",
"model_type=None): blob = response.json() data = blob.get('data', None) # All valid responses have",
"an order given its id. Required Arguments: id: The identification of the order.",
"side == 'buy' else 'buy' amount_required = 0.0 amount_obtained = 0.0 page =",
"money. e.g. 'ETH' memo (optional): memo of the wallet to transfer money. \"\"\"",
"given, returns trades since 2020-02-17. If no end date is given, returns trades",
"def get_trades(self, market, start=None, end=None, page=None, limit=None): \"\"\"returns a list of all trades",
") if page is not None: params['page'] = page if limit is not",
"None params = dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'create',",
"by API consumers. \"\"\" uri = self._create_api_uri(*relative_path_parts, **kwargs) data = kwargs.get(\"data\", None) if",
"params['limit'] = limit response = self._get(self.API_VERSION, 'book', params=params) return self._make_api_object(response, APIObject) def get_trades(self,",
"the marketpairs as strings available in Cryptomkt as the \"data\" member of a",
"not None: params['limit'] = limit response = self._get(self.API_VERSION, 'trades', params=params) return self._make_api_object(response, APIObject)",
"strings available in Cryptomkt as the \"data\" member of a dict. \"\"\" response",
"def _create_api_uri(self, *parts, **kwargs): \"\"\"Internal helper for creating fully qualified endpoint URIs.\"\"\" params",
"graph), given a timeframe. The earlier prices first and the older last. the",
"get_balance(self): \"\"\"returns the balance of the user. \"\"\" response = self._get(self.API_VERSION, 'balance') return",
"API. self.session = self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION) # a container for the socket",
"response = self._post(self.API_VERSION, 'orders', 'create', data=params) return self._make_api_object(response, APIObject) def create_multi_orders(self, order_list): for",
"from. e.g: 'ETHCLP'. timeframe: timelapse between every candle in minutes. accepted values are",
"url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) + '?%s' % urlencode(params)) else: url = urljoin(self.BASE_API_URI,",
"warning that was returned. warnings_data = blob.get('warnings', None) for warning_blob in warnings_data or",
"a market (candles on the market prices graph), given a timeframe. The earlier",
"market=market ) if page is not None: params['page'] = page if limit is",
"None: params['start'] = start if end is not None: params['end'] = end if",
"have a \"data\" key. if data is None: raise build_api_error(response, blob) # Warn",
"amount, currency, memo = None): \"\"\"transfer money between wallets. Required Arguments: adderss: The",
"the \"data\" member of a dict. Required Arguments: market: A market pair as",
"amount deposited to your wallet. bank_account: The address (id) of the bank account",
"APIObject) def cancel_order(self, id): \"\"\"Cancel an order given its id. Required Arguments: id:",
"kwargs.get(\"data\", None) if data and isinstance(data, dict): kwargs['data'] = data response = getattr(self.session,",
"'bulk', data=params) return self._make_api_object(response, APIObject) def get_instant(self,market, side, amount): \"\"\"If side is sell,",
"all trades (executed orders) of a market between the start date, until the",
"order. \"\"\" params = dict( id=id ) response = self._post(self.API_VERSION, 'orders', 'cancel', data=params)",
"unit of crypto side: 'buy' or 'sell' the crypto type: one of the",
"kwargs['data'] = data response = getattr(self.session, method)(uri, **kwargs) return self._handle_response(response) def _handle_response(self, response):",
"Optional Arguments: market: A market pair as string, if no market pair is",
"100 while True: book_page = self.get_book(market, book_side, page=page, limit=n_entries) for entry in book_page['data']:",
"= blob.get('pagination', None) kwargs = { 'response': response, 'pagination': pagination and new_api_object(None, pagination,",
"\"\"\" params = dict( id=id ) response = self._post(self.API_VERSION, 'orders', 'cancel', data=params) return",
"self._make_api_object(response, APIObject) def create_order(self, market, amount, price, side, type): \"\"\"creates an orders from",
"order_list): for order in order_list: if ('market' not in order or 'type' not",
"currency to get all the user transactions. Optional Arguments: page: Page number to",
"response def _get(self, *args, **kwargs): return self._request('get', *args, **kwargs) def _post(self, *args, **kwargs):",
"None, limit = None): \"\"\"returns a list of the prices of a market",
"bank account. bank_account: The address(id) of the bank account. \"\"\" params = dict(",
"to your bank account. bank_account: The address(id) of the bank account. \"\"\" params",
"identification of the order. \"\"\" params = dict( id=id ) response = self._post(self.API_VERSION,",
"get trades from, exclusive. page: Page number to query. Default is 0 limit:",
"amount rest -= amount if rest == 0 or len(book_page['data']) < n_entries: break",
"import imap from .compat import quote from .compat import urljoin from .compat import",
"= market, timeframe = timeframe ) if page is not None: params[\"page\"] =",
"to your wallet (fiat). Required Arguments: amount: The amount deposited to your wallet.",
"with cryptomkt. \"\"\" if self.socket is None: auth = self.get_auth_socket() del auth['verify'] self.socket",
"need to withdraw to your bank account. bank_account: The address(id) of the bank",
"is None: raise build_api_error(response, blob) # Warn the user about each warning that",
"= limit response = self._get(self.API_VERSION, 'orders', 'active', params=params) return self._make_api_object(response, APIObject) def get_executed_orders(self,",
"amount: amount_obtained += rest * price amount_required += rest rest = 0 break",
"date of the deposit, in format dd/mm/yyyy. tracking_code: The tracking code of the",
") if memo is not None: params[\"memo\"] = memo response = self._post(self.API_VERSION, \"transfer\",",
"'orders', 'cancel', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_instant(self,market, side, amount): \"\"\"If side",
"+= amount * price amount_required += amount rest -= amount if rest ==",
"the present moment. Required Arguments: market: A market pair as a string. Is",
"print_function from __future__ import unicode_literals import json import requests import time import warnings",
"get the book from. e.g: 'ETHCLP'. timeframe: timelapse between every candle in minutes.",
"response object. Not intended for direct use by API consumers. \"\"\" uri =",
"get_markets(self): \"\"\"Returns a list of the marketpairs as strings available in Cryptomkt as",
"bank account. \"\"\" params = dict( amount = amount, bank_account = bank_account )",
"the older last. stored in the \"data\" member of a dict If no",
"api_version or self.API_VERSION self.socket = None # Set up a requests session for",
"of the active orders of the user in a given market. Required Arguments:",
"page + 1 if book_side == 'sell': temp = amount_required amount_required = amount_obtained",
"not None: params['page'] = page if limit is not None: params['limit'] = limit",
"return instant #Wallet def get_balance(self): \"\"\"returns the balance of the user. \"\"\" response",
"self.socket is None: auth = self.get_auth_socket() del auth['verify'] self.socket = Socket(auth, debug=debug) return",
"and new_api_object(None, pagination, APIObject), 'warnings': warnings_data and new_api_object(None, warnings_data, APIObject), } if isinstance(data,",
"to transfer money. \"\"\" params = dict( address = address, amount = amount,",
"rest < amount: amount_obtained += rest * price amount_required += rest rest =",
"memo is not None: params[\"memo\"] = memo response = self._post(self.API_VERSION, \"transfer\", data =",
"the amount of fiat obtained and the amount of crypto required to obatin",
"if isinstance(data, dict): obj = new_api_object(self, data, model_type, **kwargs) else: obj = APIObject(self,",
"params) return self._make_api_object(response,APIObject) def notify_withdrawal(self, amount, bank_account): \"\"\"Notifies a withdrawal from fiat wallet",
"== 'buy' else 'buy' amount_required = 0.0 amount_obtained = 0.0 page = 0",
"price = float(entry['price']) amount = float(entry['amount']) if rest < amount: amount_obtained += rest",
"not None: params[\"tracking_code\"] = tracking_code if voucher is not None: params[\"voucher\"] = voucher",
"the wallet to transfer money. amount: The amount of money to transfer into",
"active orders of the user in a given market. Required Arguments: market: A",
"= None): \"\"\"Notifies a deposit from your bank account to your wallet (fiat).",
"'ETHCLP'. price: The price to ask or bid for one unit of crypto",
"is 20. \"\"\" params = dict( market=market ) if start is not None:",
"BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION = 'v2' def __init__(self, api_key, api_secret, base_api_uri=None, api_version=None, debug=False):",
"'orders', 'create', data=params) return self._make_api_object(response, APIObject) def create_multi_orders(self, order_list): for order in order_list:",
"specified market pair. stored in the \"data\" member of a dict. Required Arguments:",
"in the \"data\" member of a dict. Required Arguments: market: A market pair",
"Name, email, rate and bank accounts. \"\"\" response = self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) #",
"rate and bank accounts. \"\"\" response = self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) # orders def",
"in order): return None params = dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response =",
"exceptions when necessary; otherwise, returns the response. \"\"\" if not str(response.status_code).startswith('2'): raise build_api_error(response)",
"market, page=None, limit=None): \"\"\"returns the list of the executed orders of the user",
"'balance') return self._make_api_object(response, APIObject) def get_transactions(self, currency, page = None, limit = None):",
"import time import warnings from .auth import HMACAuth from .compat import imap from",
"def get_markets(self): \"\"\"Returns a list of the marketpairs as strings available in Cryptomkt",
"def get_auth_socket(self): \"\"\"returns the userid and the socket ids to permit a socket",
"rest == 0 or len(book_page['data']) < n_entries: break else: time.sleep(3) page = page",
"__future__ import division from __future__ import print_function from __future__ import unicode_literals import json",
"of all the market pairs are returned. e.g: 'EHTARS'. \"\"\" params = {}",
"orders def get_active_orders(self, market, page=None, limit=None): \"\"\"returns a list of the active orders",
"is given, returns trades until the present moment. Required Arguments: market: A market",
"the user transactions. Optional Arguments: page: Page number to query. Default is 0",
"message = \"%s (%s)\" % ( warning_blob.get('message', ''), warning_blob.get('url', '')) warnings.warn(message, UserWarning) pagination",
"< amount: amount_obtained += rest * price amount_required += rest rest = 0",
"(id) of the bank account from which you deposited. Extra Arguments required for",
"account. \"\"\" params = dict( amount = amount, bank_account = bank_account ) response",
"of the market state as a dict. Shows the actual bid and ask,",
"bank_account: The address(id) of the bank account. \"\"\" params = dict( amount =",
"auth_class, *args, **kwargs): \"\"\"Internal helper for creating a requests `session` with the correct",
"self._get(self.API_VERSION, 'orders', 'executed', params=params) return self._make_api_object(response, APIObject) def create_order(self, market, amount, price, side,",
"'orders', 'create', 'bulk', data=params) return self._make_api_object(response, APIObject) def get_order_status(self, id): \"\"\"returns the present",
"__future__ import unicode_literals import json import requests import time import warnings from .auth",
"side: 'buy' or 'sell' the crypto type: one of the keywords 'market', 'limit',",
"+ 1 if book_side == 'sell': temp = amount_required amount_required = amount_obtained amount_obtained",
"market, timeframe, page = None, limit = None): \"\"\"returns a list of the",
"the API. self.session = self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION) # a container for the",
"params and isinstance(params, dict): url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts)) + '?%s' % urlencode(params))",
"e.g: 'ETHCLP'. Optional Arguments: page: Page number to query. Default is 0 limit:",
"check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION = api_version or self.API_VERSION self.socket = None # Set",
"APIObject) # Authenticated endpoints #------------------------------------------------------------------- # account def get_account(self): \"\"\"returns the account information",
"self._post(self.API_VERSION, \"transfer\", data = params) return self._make_api_object(response, APIObject) def get_auth_socket(self): \"\"\"returns the userid",
"return response def _get(self, *args, **kwargs): return self._request('get', *args, **kwargs) def _post(self, *args,",
"to get trades from, exclusive. page: Page number to query. Default is 0",
"a list of all trades (executed orders) of a market between the start",
"response = self._get(\"v2\", \"socket/auth\") return self._make_api_object(response, APIObject) def get_socket(self, debug=False): \"\"\"returns a socket",
"limit is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION,\"prices\", params = params)",
"pagination and new_api_object(None, pagination, APIObject), 'warnings': warnings_data and new_api_object(None, warnings_data, APIObject), } if",
"'sell' if side == 'buy' else 'buy' amount_required = 0.0 amount_obtained = 0.0",
"amount of fiat obtained and the amount of crypto required to obatin it.",
"{ 'response': response, 'pagination': pagination and new_api_object(None, pagination, APIObject), 'warnings': warnings_data and new_api_object(None,",
"Arguments: start: The older date to get trades from, inclusive. end: The earlier",
"= self._get(self.API_VERSION, 'market') return self._make_api_object(response, APIObject) def get_ticker(self, market=None): \"\"\"Returns a general view",
"'ETHCLP'. Optional Arguments: start: The older date to get trades from, inclusive. end:",
"if page is not None: params['page'] = page if limit is not None:",
"if not str(response.status_code).startswith('2'): raise build_api_error(response) return response def _get(self, *args, **kwargs): return self._request('get',",
"new_api_object(None, warnings_data, APIObject), } if isinstance(data, dict): obj = new_api_object(self, data, model_type, **kwargs)",
"% ( warning_blob.get('message', ''), warning_blob.get('url', '')) warnings.warn(message, UserWarning) pagination = blob.get('pagination', None) kwargs",
"market between the start date, until the end date. the earlier trades first,",
"if end is not None: params['end'] = end if page is not None:",
"timeframe = timeframe ) if page is not None: params[\"page\"] = page if",
"limit response = self._get(self.API_VERSION, 'orders', 'active', params=params) return self._make_api_object(response, APIObject) def get_executed_orders(self, market,",
"\"\"\" if self.socket is None: auth = self.get_auth_socket() del auth['verify'] self.socket = Socket(auth,",
"is None: auth = self.get_auth_socket() del auth['verify'] self.socket = Socket(auth, debug=debug) return self.socket",
"The address (id) of the bank account from which you deposited. Extra Arguments",
"socket if needed. self.socket = None def _build_session(self, auth_class, *args, **kwargs): \"\"\"Internal helper",
"response = self._post(self.API_VERSION, \"withdrawal\", data = params) return self._make_api_object(response, APIObject) def transfer(self,address, amount,",
"if book_side == 'sell': temp = amount_required amount_required = amount_obtained amount_obtained = temp",
"Default is 20. \"\"\" params = dict( market=market ) if start is not",
"= kwargs.get(\"params\", None) if params and isinstance(params, dict): url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))",
"get_instant(self,market, side, amount): \"\"\"If side is sell, returns an estimate of the amount",
"params = kwargs.get(\"params\", None) if params and isinstance(params, dict): url = urljoin(self.BASE_API_URI, '/'.join(imap(quote,",
"amount = float(entry['amount']) if rest < amount: amount_obtained += rest * price amount_required",
"the deposit, in format dd/mm/yyyy. tracking_code: The tracking code of the deposit. voucher:",
"key. if data is None: raise build_api_error(response, blob) # Warn the user about",
"to get trades from, inclusive. end: The earlier date to get trades from,",
"market pair as a string. Is the specified market to get the book",
"= dict( currency = currency ) if page is not None: params[\"page\"] =",
"currency = currency ) if memo is not None: params[\"memo\"] = memo response",
"Set up a requests session for interacting with the API. self.session = self._build_session(HMACAuth,",
"the order id. Required Arguments: id: The identification of the order. \"\"\" params",
"responses from the CryptoMarket server. Raises the appropriate exceptions when necessary; otherwise, returns",
"address(id) of the bank account. \"\"\" params = dict( amount = amount, bank_account",
"separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'create', 'bulk', data=params) return self._make_api_object(response, APIObject) def",
"**kwargs) # session.headers.update({'Content-type': 'application/json'}) return session def _create_api_uri(self, *parts, **kwargs): \"\"\"Internal helper for",
"= None def _build_session(self, auth_class, *args, **kwargs): \"\"\"Internal helper for creating a requests",
"to get the book from. e.g: 'ETHCLP'. Optional Arguments: start: The older date",
"def get_active_orders(self, market, page=None, limit=None): \"\"\"returns a list of the active orders of",
"The amount of money to transfer into the wallet. currency: The wallet from",
"''), warning_blob.get('url', '')) warnings.warn(message, UserWarning) pagination = blob.get('pagination', None) kwargs = { 'response':",
"a dict. \"\"\" response = self._get(self.API_VERSION, 'market') return self._make_api_object(response, APIObject) def get_ticker(self, market=None):",
"= new_api_object(self, data, model_type, **kwargs) else: obj = APIObject(self, **kwargs) obj.data = new_api_object(self,",
"float(amount) book_side = 'sell' if side == 'buy' else 'buy' amount_required = 0.0",
"uri = self._create_api_uri(*relative_path_parts, **kwargs) data = kwargs.get(\"data\", None) if data and isinstance(data, dict):",
"it. Required Arguments: market: The market to get the estimate of the transaction.",
"time import warnings from .auth import HMACAuth from .compat import imap from .compat",
"Does not requiere to be authenticated. Optional Arguments: market: A market pair as",
"dict( market=market ) if start is not None: params['start'] = start if end",
"returned in each page. Default is 20. \"\"\" params = dict( currency =",
"market prices graph), given a timeframe. The earlier prices first and the older",
"\"\"\" response = self._get(self.API_VERSION, 'balance') return self._make_api_object(response, APIObject) def get_transactions(self, currency, page =",
"params[\"memo\"] = memo response = self._post(self.API_VERSION, \"transfer\", data = params) return self._make_api_object(response, APIObject)",
"\"\"\" params = dict( amount=amount, market=market, price=price, side=side, type=type, ) response = self._post(self.API_VERSION,",
"orders returned in each page. Default is 20. \"\"\" params = dict( market",
"of the keywords 'market', 'limit', 'stop_limit' \"\"\" params = dict( amount=amount, market=market, price=price,",
"of the bank account from which you deposited. Extra Arguments required for Brazil",
"params=params) return self._make_api_object(response, APIObject) def cancel_order(self, id): \"\"\"Cancel an order given its id.",
"of fiat required to obtain it. Required Arguments: market: The market to get",
"market: A market pair as a string. Is the specified market to place",
"API base. self.BASE_API_URI = check_uri_security(base_api_uri or self.BASE_API_URI) self.API_VERSION = api_version or self.API_VERSION self.socket",
"fiat wallet to your bank account. Required Arguments: amount: the amount you need",
"in each page. Default is 20. \"\"\" params = dict( market=market, side=side )",
"page = 0 n_entries = 100 while True: book_page = self.get_book(market, book_side, page=page,",
"date to get trades from, inclusive. end: The earlier date to get trades",
"number to query. Default is 0 limit: Number of orders returned in each",
"userid and the socket ids to permit a socket connection with cryptomkt. \"\"\"",
"= dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'create', 'bulk', data=params)",
"sell, returns an estimate of the amount of fiat obtained and the amount",
"None): \"\"\"return all the transactions of a currency of the user. Required Arguments:",
"APIObject from .model import new_api_object from .socket import Socket from .util import check_uri_security",
"'EHTARS'. \"\"\" params = {} if market: params['market'] = market response = self._get(self.API_VERSION,",
"= dict( amount = amount, bank_account = bank_account ) if date is not",
"APIObject) def create_order(self, market, amount, price, side, type): \"\"\"creates an orders from the",
"provided, the market state of all the market pairs are returned. e.g: 'EHTARS'.",
"APIObject(self, **kwargs) obj.data = new_api_object(self, data, model_type) return obj # Public API #",
"older date to get trades from, inclusive. end: The earlier date to get",
"stored in the data member of a dict Required Arguments: market: A market",
"warnings.warn(message, UserWarning) pagination = blob.get('pagination', None) kwargs = { 'response': response, 'pagination': pagination",
"the \"data\" member of a dict. \"\"\" response = self._get(self.API_VERSION, 'market') return self._make_api_object(response,",
"of all trades (executed orders) of a market between the start date, until",
"user on a given market. Required Arguments: market: A market pair as a",
"consumers. \"\"\" uri = self._create_api_uri(*relative_path_parts, **kwargs) data = kwargs.get(\"data\", None) if data and",
"= dict( amount=amount, market=market, price=price, side=side, type=type, ) response = self._post(self.API_VERSION, 'orders', 'create',",
"side=side, type=type, ) response = self._post(self.API_VERSION, 'orders', 'create', data=params) return self._make_api_object(response, APIObject) def",
"amount_obtained += rest * price amount_required += rest rest = 0 break else:",
"side, amount): \"\"\"If side is sell, returns an estimate of the amount of",
"memo (optional): memo of the wallet to transfer money. \"\"\" params = dict(",
"account. bank_account: The address(id) of the bank account. \"\"\" params = dict( amount",
"return self._make_api_object(response,APIObject) def notify_withdrawal(self, amount, bank_account): \"\"\"Notifies a withdrawal from fiat wallet to",
"and bank accounts. \"\"\" response = self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) # orders def get_active_orders(self,",
"deposit. voucher: a file. \"\"\" params = dict( amount = amount, bank_account =",
"amount_required = amount_obtained amount_obtained = temp instant = dict(obtained=amount_obtained, required=amount_required) return instant #Wallet",
"'ETHEUR'. side: 'buy' or 'sell'. Optional Arguments: page: Page number to query. Default",
"_request(self, method, *relative_path_parts, **kwargs): \"\"\"Internal helper for creating HTTP requests to the CryptoMarket",
"stored in the \"data\" member of a dict. Required Arguments: market: A market",
"side is buy, returns an estimate of the amount ofOrder crypto obtained and",
"the CryptoMarket server. Raises the appropriate exceptions when necessary; otherwise, returns the response.",
"\"\"\" params = {} if market: params['market'] = market response = self._get(self.API_VERSION, 'ticker',",
"required to obtain it. Required Arguments: market: The market to get the estimate",
"dict If no start date is given, returns trades since 2020-02-17. If no",
"return self._make_api_object(response, APIObject) def get_trades(self, market, start=None, end=None, page=None, limit=None): \"\"\"returns a list",
"pair as string, if no market pair is provided, the market state of",
"= dict( market=market ) if page is not None: params['page'] = page if",
"blob = response.json() data = blob.get('data', None) # All valid responses have a",
"'buy' or 'sell' amount: Is the amount of crypto to 'buy' or 'sell'",
".util import check_uri_security from .util import encode_params class Client(object): BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION",
"'orders', 'executed', params=params) return self._make_api_object(response, APIObject) def create_order(self, market, amount, price, side, type):",
"0 or len(book_page['data']) < n_entries: break else: time.sleep(3) page = page + 1",
"specified market to get the book from. e.g: 'ETHCLP'. Optional Arguments: page: Page",
"= None # Set up a requests session for interacting with the API.",
"break else: time.sleep(3) page = page + 1 if book_side == 'sell': temp",
"def create_order(self, market, amount, price, side, type): \"\"\"creates an orders from the specified",
"an order, given the order id. Required Arguments: id: The identification of the",
"urlencode from .error import build_api_error from .model import APIObject from .model import new_api_object",
"bank accounts. \"\"\" response = self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) # orders def get_active_orders(self, market,",
"Arguments required for Mexico: date: The date of the deposit, in format dd/mm/yyyy.",
"user about each warning that was returned. warnings_data = blob.get('warnings', None) for warning_blob",
"HTTP requests to the CryptoMarket API. Raises an APIError if the response is",
"dict): obj = new_api_object(self, data, model_type, **kwargs) else: obj = APIObject(self, **kwargs) obj.data",
"that was returned. warnings_data = blob.get('warnings', None) for warning_blob in warnings_data or []:",
"The older date to get trades from, inclusive. end: The earlier date to",
"the executed orders of the user on a given market. Required Arguments: market:",
"url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return url def _request(self, method, *relative_path_parts, **kwargs): \"\"\"Internal",
"the amount you need to withdraw to your bank account. bank_account: The address(id)",
"Is the specified market to get the book from. e.g: 'ETHEUR'. side: 'buy'",
"not None and isinstance(limit, int): params['limit'] = limit response = self._get(self.API_VERSION, 'book', params=params)",
"(candles on the market prices graph), given a timeframe. The earlier prices first",
") response = self._post(self.API_VERSION, 'orders', 'create', data=params) return self._make_api_object(response, APIObject) def create_multi_orders(self, order_list):",
"as a string. Is the specified market to get the book from. e.g:",
"page. Default is 20. \"\"\" params = dict( market=market ) if page is",
"response = self._get(self.API_VERSION, 'balance') return self._make_api_object(response, APIObject) def get_transactions(self, currency, page = None,",
"in order: return None params = dict( ids=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response =",
"return obj # Public API # ----------------------------------------------------------- def get_markets(self): \"\"\"Returns a list of",
"= 'v2' def __init__(self, api_key, api_secret, base_api_uri=None, api_version=None, debug=False): if not api_key: raise",
"the wallet to transfer money. \"\"\" params = dict( address = address, amount",
"def get_book(self, market, side, page=None, limit=None): \"\"\"Returns a list of active orders of",
".compat import quote from .compat import urljoin from .compat import urlencode from .error",
"data=params) return self._make_api_object(response, APIObject) def create_multi_orders(self, order_list): for order in order_list: if ('market'",
"from .util import check_uri_security from .util import encode_params class Client(object): BASE_API_URI = 'https://api.cryptomkt.com/'",
"\"\"\" if not str(response.status_code).startswith('2'): raise build_api_error(response) return response def _get(self, *args, **kwargs): return",
"HMACAuth from .compat import imap from .compat import quote from .compat import urljoin",
"state as a dict. Shows the actual bid and ask, the volume and",
"Arguments: amount: the amount you need to withdraw to your bank account. bank_account:",
"orders returned in each page. Default is 20. \"\"\" params = dict( market=market,",
"is provided, the market state of all the market pairs are returned. e.g:",
"is 20. \"\"\" params = dict( currency = currency ) if page is",
"amount: Is the amount of crypto to 'buy' or 'sell' \"\"\" rest =",
"None: params['limit'] = limit response = self._get(self.API_VERSION, 'trades', params=params) return self._make_api_object(response, APIObject) def",
"endpoint URIs.\"\"\" params = kwargs.get(\"params\", None) if params and isinstance(params, dict): url =",
"Default is 0 limit: Number of orders returned in each page. Default is",
"responses have a \"data\" key. if data is None: raise build_api_error(response, blob) #",
"import quote from .compat import urljoin from .compat import urlencode from .error import",
"unicode_literals import json import requests import time import warnings from .auth import HMACAuth",
"market=market, price=price, side=side, type=type, ) response = self._post(self.API_VERSION, 'orders', 'create', data=params) return self._make_api_object(response,",
"a list of the prices of a market (candles on the market prices",
"api_version=None, debug=False): if not api_key: raise ValueError('Missing `api_key`.') if not api_secret: raise ValueError('Missing",
"type): \"\"\"creates an orders from the specified argument. Required Arguments: amount: The amount",
"# ----------------------------------------------------------- def get_markets(self): \"\"\"Returns a list of the marketpairs as strings available",
"Cryptomkt as the \"data\" member of a dict. \"\"\" response = self._get(self.API_VERSION, 'market')",
"None) if data and isinstance(data, dict): kwargs['data'] = data response = getattr(self.session, method)(uri,",
"voucher: a file. Extra Arguments required for Mexico: date: The date of the",
"market to get the estimate of the transaction. side: 'buy' or 'sell' amount:",
"as strings available in Cryptomkt as the \"data\" member of a dict. \"\"\"",
"params = dict( amount=amount, market=market, price=price, side=side, type=type, ) response = self._post(self.API_VERSION, 'orders',",
"handling API responses from the CryptoMarket server. Raises the appropriate exceptions when necessary;",
"APIObject) def get_socket(self, debug=False): \"\"\"returns a socket connection with cryptomkt. \"\"\" if self.socket",
"str(response.status_code).startswith('2'): raise build_api_error(response) return response def _get(self, *args, **kwargs): return self._request('get', *args, **kwargs)",
"Arguments: market: The market to get the estimate of the transaction. side: 'buy'",
"transfer money. amount: The amount of money to transfer into the wallet. currency:",
"{} if market: params['market'] = market response = self._get(self.API_VERSION, 'ticker', params=params) return self._make_api_object(response,",
"money. \"\"\" params = dict( address = address, amount = amount, currency =",
"if limit is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION, \"transactions\", params=params)",
"None: params['end'] = end if page is not None: params['page'] = page if",
"id: The identification of the order. \"\"\" params = dict( id=id ) response",
"\"\"\" params = dict( currency = currency ) if page is not None:",
"response = self._get(self.API_VERSION, 'book', params=params) return self._make_api_object(response, APIObject) def get_trades(self, market, start=None, end=None,",
"list of active orders of a given side in a specified market pair.",
"id=id ) response = self._get(self.API_VERSION, 'orders', 'status', params=params) return self._make_api_object(response, APIObject) def cancel_order(self,",
"#------------------------------------------------------------------- # account def get_account(self): \"\"\"returns the account information of the user. Name,",
"'amount' not in order): return None params = dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), )",
"'orders', 'status', params=params) return self._make_api_object(response, APIObject) def cancel_order(self, id): \"\"\"Cancel an order given",
"accepted values are 1, 5, 15, 60, 240, 1440 and 10080. Optional Arguments:",
"ask or bid for one unit of crypto side: 'buy' or 'sell' the",
"limit is not None: params['limit'] = limit response = self._get(self.API_VERSION, 'trades', params=params) return",
"1 if book_side == 'sell': temp = amount_required amount_required = amount_obtained amount_obtained =",
"deposit, in format dd/mm/yyyy. tracking_code: The tracking code of the deposit. voucher: a",
"'buy' or 'sell' \"\"\" rest = float(amount) book_side = 'sell' if side ==",
"is sell, returns an estimate of the amount of fiat obtained and the",
"older last. stored in the \"data\" member of a dict If no start",
"interacting with the API. self.session = self._build_session(HMACAuth, api_key, api_secret, self.API_VERSION) # a container",
"+= amount rest -= amount if rest == 0 or len(book_page['data']) < n_entries:",
"create_multi_orders(self, order_list): for order in order_list: if ('market' not in order or 'type'",
"# orders def get_active_orders(self, market, page=None, limit=None): \"\"\"returns a list of the active",
"class Client(object): BASE_API_URI = 'https://api.cryptomkt.com/' API_VERSION = 'v2' def __init__(self, api_key, api_secret, base_api_uri=None,",
"for the socket if needed. self.socket = None def _build_session(self, auth_class, *args, **kwargs):",
"cryptomkt. \"\"\" if self.socket is None: auth = self.get_auth_socket() del auth['verify'] self.socket =",
"Arguments: amount: The amount deposited to your wallet. bank_account: The address (id) of",
"= limit response = self._get(self.API_VERSION,\"prices\", params = params) return self._make_api_object(response, APIObject) # Authenticated",
"earlier date to get trades from, exclusive. page: Page number to query. Default",
"amount, price, side, type): \"\"\"creates an orders from the specified argument. Required Arguments:",
"crypto to be buyed or selled. market: A market pair as a string.",
"\"\"\" params = dict( market=market, side=side ) if page is not None and",
"_make_api_object(self, response, model_type=None): blob = response.json() data = blob.get('data', None) # All valid",
"# Public API # ----------------------------------------------------------- def get_markets(self): \"\"\"Returns a list of the marketpairs",
"the low and high of the market. Stored in the \"data\" member of",
"if rest == 0 or len(book_page['data']) < n_entries: break else: time.sleep(3) page =",
"params=params) return self._make_api_object(response, APIObject) def get_prices(self, market, timeframe, page = None, limit =",
"20X. Otherwise, returns the response object. Not intended for direct use by API",
"page. Default is 20. \"\"\" params = dict( market=market ) if start is",
"Warn the user about each warning that was returned. warnings_data = blob.get('warnings', None)",
"market pair. stored in the \"data\" member of a dict. Required Arguments: market:",
"in each page. Default is 20. \"\"\" params = dict( currency = currency",
"end if page is not None: params['page'] = page if limit is not",
"and price, and the low and high of the market. Stored in the",
"_get(self, *args, **kwargs): return self._request('get', *args, **kwargs) def _post(self, *args, **kwargs): return self._request('post',",
"from .compat import quote from .compat import urljoin from .compat import urlencode from",
"stored in the \"data\" member of a dict If no start date is",
"raise ValueError('Missing `api_secret`.') # Allow passing in a different API base. self.BASE_API_URI =",
"sort_keys=True, separators=(',',':')), ) response = self._post(self.API_VERSION, 'orders', 'cancel', 'bulk', data=params) return self._make_api_object(response, APIObject)",
"book_side = 'sell' if side == 'buy' else 'buy' amount_required = 0.0 amount_obtained",
"the bank account from which you deposited. Extra Arguments required for Brazil and",
"the socket if needed. self.socket = None def _build_session(self, auth_class, *args, **kwargs): \"\"\"Internal",
"bank_account = bank_account ) response = self._post(self.API_VERSION, \"withdrawal\", data = params) return self._make_api_object(response,",
"def _build_session(self, auth_class, *args, **kwargs): \"\"\"Internal helper for creating a requests `session` with",
"if not api_key: raise ValueError('Missing `api_key`.') if not api_secret: raise ValueError('Missing `api_secret`.') #",
"\"\"\"Internal helper for handling API responses from the CryptoMarket server. Raises the appropriate",
"obj.data = new_api_object(self, data, model_type) return obj # Public API # ----------------------------------------------------------- def",
"not None: params['end'] = end if page is not None: params['page'] = page",
"memo response = self._post(self.API_VERSION, \"transfer\", data = params) return self._make_api_object(response, APIObject) def get_auth_socket(self):",
"model_type) return obj # Public API # ----------------------------------------------------------- def get_markets(self): \"\"\"Returns a list",
"is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION, \"transactions\", params=params) return self._make_api_object(response,",
"float(entry['amount']) if rest < amount: amount_obtained += rest * price amount_required += rest",
"a list of active orders of a given side in a specified market",
"\"\"\" response = self._get(self.API_VERSION, 'market') return self._make_api_object(response, APIObject) def get_ticker(self, market=None): \"\"\"Returns a",
"data = params) return self._make_api_object(response,APIObject) def notify_withdrawal(self, amount, bank_account): \"\"\"Notifies a withdrawal from",
"if self.socket is None: auth = self.get_auth_socket() del auth['verify'] self.socket = Socket(auth, debug=debug)",
"deposit from your bank account to your wallet (fiat). Required Arguments: amount: The",
"voucher: a file. \"\"\" params = dict( amount = amount, bank_account = bank_account",
"you deposited. Extra Arguments required for Brazil and the European Union: voucher: a",
"a deposit from your bank account to your wallet (fiat). Required Arguments: amount:",
"raise ValueError('Missing `api_key`.') if not api_secret: raise ValueError('Missing `api_secret`.') # Allow passing in",
"orders from the specified argument. Required Arguments: amount: The amount of crypto to",
"= currency ) if page is not None: params[\"page\"] = page if limit",
"prices graph), given a timeframe. The earlier prices first and the older last.",
"crypto obtained and the amount of fiat required to obtain it. Required Arguments:",
"with cryptomkt. \"\"\" response = self._get(\"v2\", \"socket/auth\") return self._make_api_object(response, APIObject) def get_socket(self, debug=False):",
"a list of the marketpairs as strings available in Cryptomkt as the \"data\"",
"from, inclusive. end: The earlier date to get trades from, exclusive. page: Page",
"is stored in the data member of a dict Required Arguments: market: A",
"Raises the appropriate exceptions when necessary; otherwise, returns the response. \"\"\" if not",
"= auth_class(*args, **kwargs) # session.headers.update({'Content-type': 'application/json'}) return session def _create_api_uri(self, *parts, **kwargs): \"\"\"Internal",
"None def _build_session(self, auth_class, *args, **kwargs): \"\"\"Internal helper for creating a requests `session`",
"= None): \"\"\"transfer money between wallets. Required Arguments: adderss: The address of the",
"orders returned in each page. Default is 20. \"\"\" params = dict( market=market",
"Required Arguments: id: The identification of the order. \"\"\" params = dict( id=id",
"Required Arguments: amount: The amount of crypto to be buyed or selled. market:",
"your wallet. bank_account: The address (id) of the bank account from which you",
"the list is stored in the data member of a dict Required Arguments:",
"urlencode(params)) else: url = urljoin(self.BASE_API_URI, '/'.join(imap(quote, parts))) return url def _request(self, method, *relative_path_parts,",
"**kwargs): return self._request('post', *args, **kwargs) def _make_api_object(self, response, model_type=None): blob = response.json() data",
"**kwargs): \"\"\"Internal helper for creating HTTP requests to the CryptoMarket API. Raises an",
"= self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) # orders def get_active_orders(self, market, page=None, limit=None): \"\"\"returns a",
"is not None: params['end'] = end if page is not None: params['page'] =",
".auth import HMACAuth from .compat import imap from .compat import quote from .compat",
"authentication handling.\"\"\" session = requests.session() session.auth = auth_class(*args, **kwargs) # session.headers.update({'Content-type': 'application/json'}) return",
"APIObject) def get_ticker(self, market=None): \"\"\"Returns a general view of the market state as",
"APIObject) def transfer(self,address, amount, currency, memo = None): \"\"\"transfer money between wallets. Required",
"to be buyed or selled. market: A market pair as a string. Is",
"get_ticker(self, market=None): \"\"\"Returns a general view of the market state as a dict.",
"or 'sell' \"\"\" rest = float(amount) book_side = 'sell' if side == 'buy'",
"return self._make_api_object(response, APIObject) def create_order(self, market, amount, price, side, type): \"\"\"creates an orders",
"+= rest * price amount_required += rest rest = 0 break else: amount_obtained",
"string. Is the specified market to get the book from. e.g: 'ETHCLP'. Optional",
"selled. market: A market pair as a string. Is the specified market to",
"self._get(self.API_VERSION,\"account\") return self._make_api_object(response,APIObject) # orders def get_active_orders(self, market, page=None, limit=None): \"\"\"returns a list",
"= 0.0 amount_obtained = 0.0 page = 0 n_entries = 100 while True:",
"= limit response = self._get(self.API_VERSION, 'orders', 'executed', params=params) return self._make_api_object(response, APIObject) def create_order(self,",
"inclusive. end: The earlier date to get trades from, exclusive. page: Page number",
"= address, amount = amount, currency = currency ) if memo is not",
"until the present moment. Required Arguments: market: A market pair as a string.",
"limit is not None: params[\"limit\"] = limit response = self._get(self.API_VERSION, \"transactions\", params=params) return",
"transfer money. \"\"\" params = dict( address = address, amount = amount, currency",
"amount of fiat required to obtain it. Required Arguments: market: The market to",
"\"\"\" params = dict( market=market ) if page is not None: params['page'] =",
"each page. Default is 20. \"\"\" params = dict( market = market, timeframe",
"market=None): \"\"\"Returns a general view of the market state as a dict. Shows",
"e.g: 'ETHCLP'. price: The price to ask or bid for one unit of",
"response = self._get(self.API_VERSION, 'orders', 'status', params=params) return self._make_api_object(response, APIObject) def cancel_order(self, id): \"\"\"Cancel",
"bank account to your wallet (fiat). Required Arguments: amount: The amount deposited to",
"bid for one unit of crypto side: 'buy' or 'sell' the crypto type:",
"page=None, limit=None): \"\"\"Returns a list of active orders of a given side in",
"order or 'amount' not in order): return None params = dict( orders=json.dumps(order_list, sort_keys=True,",
"**kwargs) obj.data = new_api_object(self, data, model_type) return obj # Public API # -----------------------------------------------------------",
"to 'buy' or 'sell' \"\"\" rest = float(amount) book_side = 'sell' if side",
"amount = amount, bank_account = bank_account ) response = self._post(self.API_VERSION, \"withdrawal\", data =",
"price, and the low and high of the market. Stored in the \"data\"",
"params = {} if market: params['market'] = market response = self._get(self.API_VERSION, 'ticker', params=params)",
"params = dict( market=market, side=side ) if page is not None and isinstance(page,",
"for warning_blob in warnings_data or []: message = \"%s (%s)\" % ( warning_blob.get('message',",
"tracking_code is not None: params[\"tracking_code\"] = tracking_code if voucher is not None: params[\"voucher\"]",
"import urlencode from .error import build_api_error from .model import APIObject from .model import",
"if needed. self.socket = None def _build_session(self, auth_class, *args, **kwargs): \"\"\"Internal helper for",
"*args, **kwargs): return self._request('post', *args, **kwargs) def _make_api_object(self, response, model_type=None): blob = response.json()",
"limit = None): \"\"\"returns a list of the prices of a market (candles",
"0 limit: Number of orders returned in each page. Default is 20. \"\"\"",
".compat import imap from .compat import quote from .compat import urljoin from .compat",
"Arguments: market: A market pair as string, if no market pair is provided,",
"if memo is not None: params[\"memo\"] = memo response = self._post(self.API_VERSION, \"transfer\", data",
"dd/mm/yyyy. tracking_code: The tracking code of the deposit. voucher: a file. \"\"\" params",
"def _request(self, method, *relative_path_parts, **kwargs): \"\"\"Internal helper for creating HTTP requests to the",
"not in order): return None params = dict( orders=json.dumps(order_list, sort_keys=True, separators=(',',':')), ) response",
"helper for creating HTTP requests to the CryptoMarket API. Raises an APIError if",
"the European Union: voucher: a file. Extra Arguments required for Mexico: date: The",
"None and isinstance(limit, int): params['limit'] = limit response = self._get(self.API_VERSION, 'book', params=params) return",
"first and the older last. the list is stored in the data member",
"import absolute_import from __future__ import division from __future__ import print_function from __future__ import",
"account from which you deposited. Extra Arguments required for Brazil and the European",
"utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function",
"price, side, type): \"\"\"creates an orders from the specified argument. Required Arguments: amount:",
"returns the response object. Not intended for direct use by API consumers. \"\"\"",
"returned. warnings_data = blob.get('warnings', None) for warning_blob in warnings_data or []: message =",
"the specified market to get the book from. e.g: 'ETHEUR'. side: 'buy' or",
"in each page. Default is 20. \"\"\" params = dict( market = market,",
"APIObject) def cancel_multi_orders(self, order_list): for order in order_list: if 'id' not in order:",
"\"\"\"transfer money between wallets. Required Arguments: adderss: The address of the wallet to",
"and the older last. the list is stored in the data member of",
"date is given, returns trades since 2020-02-17. If no end date is given,",
"active orders of a given side in a specified market pair. stored in",
"in a specified market pair. stored in the \"data\" member of a dict.",
"from. e.g: 'ETHCLP'. Optional Arguments: start: The older date to get trades from,",
"market, page=None, limit=None): \"\"\"returns a list of the active orders of the user",
"permit a socket connection with cryptomkt. \"\"\" response = self._get(\"v2\", \"socket/auth\") return self._make_api_object(response,"
] |
[
"version='1.1', description='assembly and variant calling for stlfr and hybrid assembler for linked-reads', author='XinZhou',",
"setuptools import setup, find_packages, Extension setup(name='aquila_stlfr', version='1.1', description='assembly and variant calling for stlfr",
"from setuptools import setup, find_packages, Extension setup(name='aquila_stlfr', version='1.1', description='assembly and variant calling for",
"and variant calling for stlfr and hybrid assembler for linked-reads', author='XinZhou', author_email='<EMAIL>', packages=['bin',],",
"variant calling for stlfr and hybrid assembler for linked-reads', author='XinZhou', author_email='<EMAIL>', packages=['bin',], entry_points={'console_scripts':['Aquila_stLFR_step1=bin.Aquila_stLFR_step1:main','Aquila_step1_hybrid=bin.Aquila_step1_hybrid:main','Aquila_stLFR_step2=bin.Aquila_stLFR_step2:main','Aquila_stLFR_assembly_based_variants_call=bin.Aquila_stLFR_assembly_based_variants_call:main','Aquila_stLFR_phasing_all_variants=bin.Aquila_stLFR_phasing_all_variants:main','Aquila_stLFR_clean=bin.Aquila_stLFR_clean:main','Aquila_step0_sortbam_hybrid=bin.Aquila_step0_sortbam_hybrid:main','Aquila_stLFR_fastq_preprocess=bin.Aquila_stLFR_fastq_preprocess:main']},",
"calling for stlfr and hybrid assembler for linked-reads', author='XinZhou', author_email='<EMAIL>', packages=['bin',], entry_points={'console_scripts':['Aquila_stLFR_step1=bin.Aquila_stLFR_step1:main','Aquila_step1_hybrid=bin.Aquila_step1_hybrid:main','Aquila_stLFR_step2=bin.Aquila_stLFR_step2:main','Aquila_stLFR_assembly_based_variants_call=bin.Aquila_stLFR_assembly_based_variants_call:main','Aquila_stLFR_phasing_all_variants=bin.Aquila_stLFR_phasing_all_variants:main','Aquila_stLFR_clean=bin.Aquila_stLFR_clean:main','Aquila_step0_sortbam_hybrid=bin.Aquila_step0_sortbam_hybrid:main','Aquila_stLFR_fastq_preprocess=bin.Aquila_stLFR_fastq_preprocess:main']}, zip_safe=False)",
"setup, find_packages, Extension setup(name='aquila_stlfr', version='1.1', description='assembly and variant calling for stlfr and hybrid",
"description='assembly and variant calling for stlfr and hybrid assembler for linked-reads', author='XinZhou', author_email='<EMAIL>',",
"setup(name='aquila_stlfr', version='1.1', description='assembly and variant calling for stlfr and hybrid assembler for linked-reads',",
"import setup, find_packages, Extension setup(name='aquila_stlfr', version='1.1', description='assembly and variant calling for stlfr and",
"find_packages, Extension setup(name='aquila_stlfr', version='1.1', description='assembly and variant calling for stlfr and hybrid assembler",
"Extension setup(name='aquila_stlfr', version='1.1', description='assembly and variant calling for stlfr and hybrid assembler for"
] |
[
"observer.on_next, on_error, observer.on_completed, scheduler ) return subscription return Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception,",
"or an exception handler function that returns an observable sequence given the error",
"Union[Observable, Callable[[Exception, Observable], Observable]] ) -> Callable[[Observable], Observable]: def catch(source: Observable) -> Observable:",
"subscription.disposable = d d.disposable = result.subscribe(observer, scheduler=scheduler) d1.disposable = source.subscribe_( observer.on_next, on_error, observer.on_completed,",
"return Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception, Observable], Observable]] ) -> Callable[[Observable], Observable]: def",
"Observable]) -> Observable: def subscribe(observer, scheduler=None): d1 = SingleAssignmentDisposable() subscription = SerialDisposable() subscription.disposable",
"occurred in the first sequence. Returns: An observable sequence containing the first sequence's",
"-> Observable: \"\"\"Continues an observable sequence that is terminated by an exception with",
"elements, followed by the elements of the handler sequence in case an exception",
"an observable sequence given the error and source observable that occurred in the",
"terminated by an exception with the next observable sequence. Examples: >>> op =",
"Union import rx from rx.core import Observable, typing from rx.disposable import SingleAssignmentDisposable, SerialDisposable",
"subscription = SerialDisposable() subscription.disposable = d1 def on_error(exception): try: result = handler(exception, source)",
"handler: Callable[[Exception, Observable], Observable]) -> Observable: def subscribe(observer, scheduler=None): d1 = SingleAssignmentDisposable() subscription",
"Observable: \"\"\"Continues an observable sequence that is terminated by an exception with the",
"subscription.disposable = d1 def on_error(exception): try: result = handler(exception, source) except Exception as",
"Observable, typing from rx.disposable import SingleAssignmentDisposable, SerialDisposable from rx.internal.utils import is_future def catch_handler(source:",
"on_error(exception): try: result = handler(exception, source) except Exception as ex: # By design.",
"rx.disposable import SingleAssignmentDisposable, SerialDisposable from rx.internal.utils import is_future def catch_handler(source: Observable, handler: Callable[[Exception,",
"returns an observable sequence given the error and source observable that occurred in",
"that occurred in the first sequence. Returns: An observable sequence containing the first",
"return catch_handler(source, handler) elif isinstance(handler, typing.Observable): return rx.catch(source, handler) else: raise TypeError('catch operator",
"of the handler sequence in case an exception occurred. \"\"\" if callable(handler): return",
"SerialDisposable() subscription.disposable = d1 def on_error(exception): try: result = handler(exception, source) except Exception",
"containing the first sequence's elements, followed by the elements of the handler sequence",
"raise TypeError('catch operator takes whether an Observable or a callable handler as argument.')",
"source) except Exception as ex: # By design. pylint: disable=W0703 observer.on_error(ex) return result",
"= SingleAssignmentDisposable() subscription = SerialDisposable() subscription.disposable = d1 def on_error(exception): try: result =",
"observable sequence that is terminated by an exception with the next observable sequence.",
"exception handler function that returns an observable sequence given the error and source",
"in the first sequence, or an exception handler function that returns an observable",
"catch(ys) >>> op = catch(lambda ex, src: ys(ex)) Args: handler: Second observable sequence",
"next observable sequence. Examples: >>> op = catch(ys) >>> op = catch(lambda ex,",
"observable that occurred in the first sequence. Returns: An observable sequence containing the",
"sequence. Examples: >>> op = catch(ys) >>> op = catch(lambda ex, src: ys(ex))",
"on_error, observer.on_completed, scheduler ) return subscription return Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception, Observable],",
"that returns an observable sequence given the error and source observable that occurred",
"result.subscribe(observer, scheduler=scheduler) d1.disposable = source.subscribe_( observer.on_next, on_error, observer.on_completed, scheduler ) return subscription return",
"callable(handler): return catch_handler(source, handler) elif isinstance(handler, typing.Observable): return rx.catch(source, handler) else: raise TypeError('catch",
"SingleAssignmentDisposable, SerialDisposable from rx.internal.utils import is_future def catch_handler(source: Observable, handler: Callable[[Exception, Observable], Observable])",
"ys(ex)) Args: handler: Second observable sequence used to produce results when an error",
"pylint: disable=W0703 observer.on_error(ex) return result = rx.from_future(result) if is_future(result) else result d =",
"d d.disposable = result.subscribe(observer, scheduler=scheduler) d1.disposable = source.subscribe_( observer.on_next, on_error, observer.on_completed, scheduler )",
"Callable[[Exception, Observable], Observable]] ) -> Callable[[Observable], Observable]: def catch(source: Observable) -> Observable: \"\"\"Continues",
"\"\"\"Continues an observable sequence that is terminated by an exception with the next",
"subscription return Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception, Observable], Observable]] ) -> Callable[[Observable], Observable]:",
"sequence containing the first sequence's elements, followed by the elements of the handler",
"given the error and source observable that occurred in the first sequence. Returns:",
"in case an exception occurred. \"\"\" if callable(handler): return catch_handler(source, handler) elif isinstance(handler,",
"first sequence, or an exception handler function that returns an observable sequence given",
"import is_future def catch_handler(source: Observable, handler: Callable[[Exception, Observable], Observable]) -> Observable: def subscribe(observer,",
"Callable[[Exception, Observable], Observable]) -> Observable: def subscribe(observer, scheduler=None): d1 = SingleAssignmentDisposable() subscription =",
"that is terminated by an exception with the next observable sequence. Examples: >>>",
"exception occurred. \"\"\" if callable(handler): return catch_handler(source, handler) elif isinstance(handler, typing.Observable): return rx.catch(source,",
"Observable], Observable]) -> Observable: def subscribe(observer, scheduler=None): d1 = SingleAssignmentDisposable() subscription = SerialDisposable()",
"= SerialDisposable() subscription.disposable = d1 def on_error(exception): try: result = handler(exception, source) except",
"handler: Second observable sequence used to produce results when an error occurred in",
"_catch(handler: Union[Observable, Callable[[Exception, Observable], Observable]] ) -> Callable[[Observable], Observable]: def catch(source: Observable) ->",
"import SingleAssignmentDisposable, SerialDisposable from rx.internal.utils import is_future def catch_handler(source: Observable, handler: Callable[[Exception, Observable],",
"function that returns an observable sequence given the error and source observable that",
"ex: # By design. pylint: disable=W0703 observer.on_error(ex) return result = rx.from_future(result) if is_future(result)",
"= rx.from_future(result) if is_future(result) else result d = SingleAssignmentDisposable() subscription.disposable = d d.disposable",
"-> Observable: def subscribe(observer, scheduler=None): d1 = SingleAssignmentDisposable() subscription = SerialDisposable() subscription.disposable =",
"sequence. Returns: An observable sequence containing the first sequence's elements, followed by the",
"return result = rx.from_future(result) if is_future(result) else result d = SingleAssignmentDisposable() subscription.disposable =",
">>> op = catch(lambda ex, src: ys(ex)) Args: handler: Second observable sequence used",
"an exception handler function that returns an observable sequence given the error and",
"catch(source: Observable) -> Observable: \"\"\"Continues an observable sequence that is terminated by an",
"by the elements of the handler sequence in case an exception occurred. \"\"\"",
") -> Callable[[Observable], Observable]: def catch(source: Observable) -> Observable: \"\"\"Continues an observable sequence",
"observable sequence used to produce results when an error occurred in the first",
"result = handler(exception, source) except Exception as ex: # By design. pylint: disable=W0703",
"= handler(exception, source) except Exception as ex: # By design. pylint: disable=W0703 observer.on_error(ex)",
"the first sequence's elements, followed by the elements of the handler sequence in",
"# By design. pylint: disable=W0703 observer.on_error(ex) return result = rx.from_future(result) if is_future(result) else",
"used to produce results when an error occurred in the first sequence, or",
"catch_handler(source: Observable, handler: Callable[[Exception, Observable], Observable]) -> Observable: def subscribe(observer, scheduler=None): d1 =",
") return subscription return Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception, Observable], Observable]] ) ->",
"from rx.internal.utils import is_future def catch_handler(source: Observable, handler: Callable[[Exception, Observable], Observable]) -> Observable:",
"rx.internal.utils import is_future def catch_handler(source: Observable, handler: Callable[[Exception, Observable], Observable]) -> Observable: def",
"-> Callable[[Observable], Observable]: def catch(source: Observable) -> Observable: \"\"\"Continues an observable sequence that",
"sequence that is terminated by an exception with the next observable sequence. Examples:",
"observable sequence. Examples: >>> op = catch(ys) >>> op = catch(lambda ex, src:",
"handler function that returns an observable sequence given the error and source observable",
"handler) elif isinstance(handler, typing.Observable): return rx.catch(source, handler) else: raise TypeError('catch operator takes whether",
"op = catch(ys) >>> op = catch(lambda ex, src: ys(ex)) Args: handler: Second",
"An observable sequence containing the first sequence's elements, followed by the elements of",
"d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer, scheduler=scheduler) d1.disposable = source.subscribe_(",
"the handler sequence in case an exception occurred. \"\"\" if callable(handler): return catch_handler(source,",
"an exception occurred. \"\"\" if callable(handler): return catch_handler(source, handler) elif isinstance(handler, typing.Observable): return",
"Observable: def subscribe(observer, scheduler=None): d1 = SingleAssignmentDisposable() subscription = SerialDisposable() subscription.disposable = d1",
"= result.subscribe(observer, scheduler=scheduler) d1.disposable = source.subscribe_( observer.on_next, on_error, observer.on_completed, scheduler ) return subscription",
"exception with the next observable sequence. Examples: >>> op = catch(ys) >>> op",
"results when an error occurred in the first sequence, or an exception handler",
"and source observable that occurred in the first sequence. Returns: An observable sequence",
"result d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer, scheduler=scheduler) d1.disposable =",
"SerialDisposable from rx.internal.utils import is_future def catch_handler(source: Observable, handler: Callable[[Exception, Observable], Observable]) ->",
"def catch(source: Observable) -> Observable: \"\"\"Continues an observable sequence that is terminated by",
"Examples: >>> op = catch(ys) >>> op = catch(lambda ex, src: ys(ex)) Args:",
"sequence given the error and source observable that occurred in the first sequence.",
"Returns: An observable sequence containing the first sequence's elements, followed by the elements",
"observable sequence containing the first sequence's elements, followed by the elements of the",
"ex, src: ys(ex)) Args: handler: Second observable sequence used to produce results when",
"scheduler=scheduler) d1.disposable = source.subscribe_( observer.on_next, on_error, observer.on_completed, scheduler ) return subscription return Observable(subscribe)",
"an error occurred in the first sequence, or an exception handler function that",
"sequence's elements, followed by the elements of the handler sequence in case an",
"an observable sequence that is terminated by an exception with the next observable",
"design. pylint: disable=W0703 observer.on_error(ex) return result = rx.from_future(result) if is_future(result) else result d",
"return rx.catch(source, handler) else: raise TypeError('catch operator takes whether an Observable or a",
"is_future def catch_handler(source: Observable, handler: Callable[[Exception, Observable], Observable]) -> Observable: def subscribe(observer, scheduler=None):",
"Observable]: def catch(source: Observable) -> Observable: \"\"\"Continues an observable sequence that is terminated",
"the next observable sequence. Examples: >>> op = catch(ys) >>> op = catch(lambda",
"Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception, Observable], Observable]] ) -> Callable[[Observable], Observable]: def catch(source:",
"produce results when an error occurred in the first sequence, or an exception",
"error and source observable that occurred in the first sequence. Returns: An observable",
"handler) else: raise TypeError('catch operator takes whether an Observable or a callable handler",
"from rx.disposable import SingleAssignmentDisposable, SerialDisposable from rx.internal.utils import is_future def catch_handler(source: Observable, handler:",
"sequence used to produce results when an error occurred in the first sequence,",
"catch(lambda ex, src: ys(ex)) Args: handler: Second observable sequence used to produce results",
"typing from rx.disposable import SingleAssignmentDisposable, SerialDisposable from rx.internal.utils import is_future def catch_handler(source: Observable,",
"result = rx.from_future(result) if is_future(result) else result d = SingleAssignmentDisposable() subscription.disposable = d",
"= catch(lambda ex, src: ys(ex)) Args: handler: Second observable sequence used to produce",
"as ex: # By design. pylint: disable=W0703 observer.on_error(ex) return result = rx.from_future(result) if",
"def _catch(handler: Union[Observable, Callable[[Exception, Observable], Observable]] ) -> Callable[[Observable], Observable]: def catch(source: Observable)",
"op = catch(lambda ex, src: ys(ex)) Args: handler: Second observable sequence used to",
"typing.Observable): return rx.catch(source, handler) else: raise TypeError('catch operator takes whether an Observable or",
"in the first sequence. Returns: An observable sequence containing the first sequence's elements,",
"handler sequence in case an exception occurred. \"\"\" if callable(handler): return catch_handler(source, handler)",
"Args: handler: Second observable sequence used to produce results when an error occurred",
"import rx from rx.core import Observable, typing from rx.disposable import SingleAssignmentDisposable, SerialDisposable from",
"isinstance(handler, typing.Observable): return rx.catch(source, handler) else: raise TypeError('catch operator takes whether an Observable",
"scheduler ) return subscription return Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception, Observable], Observable]] )",
"def catch_handler(source: Observable, handler: Callable[[Exception, Observable], Observable]) -> Observable: def subscribe(observer, scheduler=None): d1",
"case an exception occurred. \"\"\" if callable(handler): return catch_handler(source, handler) elif isinstance(handler, typing.Observable):",
">>> op = catch(ys) >>> op = catch(lambda ex, src: ys(ex)) Args: handler:",
"Exception as ex: # By design. pylint: disable=W0703 observer.on_error(ex) return result = rx.from_future(result)",
"rx from rx.core import Observable, typing from rx.disposable import SingleAssignmentDisposable, SerialDisposable from rx.internal.utils",
"= d d.disposable = result.subscribe(observer, scheduler=scheduler) d1.disposable = source.subscribe_( observer.on_next, on_error, observer.on_completed, scheduler",
"elif isinstance(handler, typing.Observable): return rx.catch(source, handler) else: raise TypeError('catch operator takes whether an",
"Observable, handler: Callable[[Exception, Observable], Observable]) -> Observable: def subscribe(observer, scheduler=None): d1 = SingleAssignmentDisposable()",
"d1.disposable = source.subscribe_( observer.on_next, on_error, observer.on_completed, scheduler ) return subscription return Observable(subscribe) def",
"observable sequence given the error and source observable that occurred in the first",
"def on_error(exception): try: result = handler(exception, source) except Exception as ex: # By",
"to produce results when an error occurred in the first sequence, or an",
"source.subscribe_( observer.on_next, on_error, observer.on_completed, scheduler ) return subscription return Observable(subscribe) def _catch(handler: Union[Observable,",
"when an error occurred in the first sequence, or an exception handler function",
"typing import Callable, Union import rx from rx.core import Observable, typing from rx.disposable",
"with the next observable sequence. Examples: >>> op = catch(ys) >>> op =",
"import Callable, Union import rx from rx.core import Observable, typing from rx.disposable import",
"TypeError('catch operator takes whether an Observable or a callable handler as argument.') return",
"d1 = SingleAssignmentDisposable() subscription = SerialDisposable() subscription.disposable = d1 def on_error(exception): try: result",
"sequence in case an exception occurred. \"\"\" if callable(handler): return catch_handler(source, handler) elif",
"except Exception as ex: # By design. pylint: disable=W0703 observer.on_error(ex) return result =",
"from typing import Callable, Union import rx from rx.core import Observable, typing from",
"try: result = handler(exception, source) except Exception as ex: # By design. pylint:",
"subscribe(observer, scheduler=None): d1 = SingleAssignmentDisposable() subscription = SerialDisposable() subscription.disposable = d1 def on_error(exception):",
"handler(exception, source) except Exception as ex: # By design. pylint: disable=W0703 observer.on_error(ex) return",
"else result d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer, scheduler=scheduler) d1.disposable",
"import Observable, typing from rx.disposable import SingleAssignmentDisposable, SerialDisposable from rx.internal.utils import is_future def",
"elements of the handler sequence in case an exception occurred. \"\"\" if callable(handler):",
"by an exception with the next observable sequence. Examples: >>> op = catch(ys)",
"is_future(result) else result d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer, scheduler=scheduler)",
"Observable) -> Observable: \"\"\"Continues an observable sequence that is terminated by an exception",
"observer.on_error(ex) return result = rx.from_future(result) if is_future(result) else result d = SingleAssignmentDisposable() subscription.disposable",
"src: ys(ex)) Args: handler: Second observable sequence used to produce results when an",
"\"\"\" if callable(handler): return catch_handler(source, handler) elif isinstance(handler, typing.Observable): return rx.catch(source, handler) else:",
"the first sequence. Returns: An observable sequence containing the first sequence's elements, followed",
"def subscribe(observer, scheduler=None): d1 = SingleAssignmentDisposable() subscription = SerialDisposable() subscription.disposable = d1 def",
"sequence, or an exception handler function that returns an observable sequence given the",
"SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer, scheduler=scheduler) d1.disposable = source.subscribe_( observer.on_next, on_error,",
"Observable]] ) -> Callable[[Observable], Observable]: def catch(source: Observable) -> Observable: \"\"\"Continues an observable",
"an exception with the next observable sequence. Examples: >>> op = catch(ys) >>>",
"scheduler=None): d1 = SingleAssignmentDisposable() subscription = SerialDisposable() subscription.disposable = d1 def on_error(exception): try:",
"d.disposable = result.subscribe(observer, scheduler=scheduler) d1.disposable = source.subscribe_( observer.on_next, on_error, observer.on_completed, scheduler ) return",
"first sequence's elements, followed by the elements of the handler sequence in case",
"= SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer, scheduler=scheduler) d1.disposable = source.subscribe_( observer.on_next,",
"the elements of the handler sequence in case an exception occurred. \"\"\" if",
"Callable[[Observable], Observable]: def catch(source: Observable) -> Observable: \"\"\"Continues an observable sequence that is",
"Observable], Observable]] ) -> Callable[[Observable], Observable]: def catch(source: Observable) -> Observable: \"\"\"Continues an",
"disable=W0703 observer.on_error(ex) return result = rx.from_future(result) if is_future(result) else result d = SingleAssignmentDisposable()",
"= catch(ys) >>> op = catch(lambda ex, src: ys(ex)) Args: handler: Second observable",
"followed by the elements of the handler sequence in case an exception occurred.",
"rx.core import Observable, typing from rx.disposable import SingleAssignmentDisposable, SerialDisposable from rx.internal.utils import is_future",
"the first sequence, or an exception handler function that returns an observable sequence",
"if is_future(result) else result d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer,",
"By design. pylint: disable=W0703 observer.on_error(ex) return result = rx.from_future(result) if is_future(result) else result",
"= d1 def on_error(exception): try: result = handler(exception, source) except Exception as ex:",
"source observable that occurred in the first sequence. Returns: An observable sequence containing",
"SingleAssignmentDisposable() subscription = SerialDisposable() subscription.disposable = d1 def on_error(exception): try: result = handler(exception,",
"Callable, Union import rx from rx.core import Observable, typing from rx.disposable import SingleAssignmentDisposable,",
"d1 def on_error(exception): try: result = handler(exception, source) except Exception as ex: #",
"observer.on_completed, scheduler ) return subscription return Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception, Observable], Observable]]",
"= source.subscribe_( observer.on_next, on_error, observer.on_completed, scheduler ) return subscription return Observable(subscribe) def _catch(handler:",
"rx.catch(source, handler) else: raise TypeError('catch operator takes whether an Observable or a callable",
"if callable(handler): return catch_handler(source, handler) elif isinstance(handler, typing.Observable): return rx.catch(source, handler) else: raise",
"occurred in the first sequence, or an exception handler function that returns an",
"Second observable sequence used to produce results when an error occurred in the",
"operator takes whether an Observable or a callable handler as argument.') return catch",
"catch_handler(source, handler) elif isinstance(handler, typing.Observable): return rx.catch(source, handler) else: raise TypeError('catch operator takes",
"from rx.core import Observable, typing from rx.disposable import SingleAssignmentDisposable, SerialDisposable from rx.internal.utils import",
"first sequence. Returns: An observable sequence containing the first sequence's elements, followed by",
"else: raise TypeError('catch operator takes whether an Observable or a callable handler as",
"is terminated by an exception with the next observable sequence. Examples: >>> op",
"rx.from_future(result) if is_future(result) else result d = SingleAssignmentDisposable() subscription.disposable = d d.disposable =",
"error occurred in the first sequence, or an exception handler function that returns",
"occurred. \"\"\" if callable(handler): return catch_handler(source, handler) elif isinstance(handler, typing.Observable): return rx.catch(source, handler)",
"the error and source observable that occurred in the first sequence. Returns: An",
"return subscription return Observable(subscribe) def _catch(handler: Union[Observable, Callable[[Exception, Observable], Observable]] ) -> Callable[[Observable],"
] |
[
"path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) # Case insensitive self.assertEqual(",
"filter_paths, get_print_directories, get_best_match) TEST_DIR = \"fixtures\" def touch(path): with open(path, 'a'): os.utime(path, None)",
"1 hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1 regular file and 1 symlink file_path",
"# Case insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\",",
"beginning or end self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list)) # Match",
"test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self): path_list =",
"self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list",
"get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) # Case insensitive",
"= os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path) # 1 hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1",
"\"else\", get_best_match(\"else\", path_list)) # Fuzzy match self.assertEqual( \"Everything Else\", get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\",",
"regular file and 1 symlink file_path = os.path.join(test_dir_path, \"some_file\") file_link_path = os.path.join(test_dir_path, \"file_link\")",
"self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self): path_list = [\"one\", \"two\",",
"test_dir_path = os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) # Root directory for tests",
"os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path = os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) # 1 symlink to",
"self.assertEqual( \"Documents\", get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self): path_list = [\"one\", \"two\", \"three\"] self.assertEqual(None, get_best_match(\"xyz\",",
"Fuzzy match self.assertEqual( \"Everything Else\", get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\",",
"import ( path_is_directory, filter_paths, get_print_directories, get_best_match) TEST_DIR = \"fixtures\" def touch(path): with open(path,",
"script_dir_path = os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) # Root",
"file and 1 symlink file_path = os.path.join(test_dir_path, \"some_file\") file_link_path = os.path.join(test_dir_path, \"file_link\") touch(file_path)",
"self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list()",
"\"two\", \"three\", \"four\"] output = get_print_directories(path_list, as_list=True) output_list = output.split(\"\\n\") self.assertEqual(len(output_list), 4) def",
"filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output",
"setUpClass(cls): script_path = os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path):",
"path_list)) # XXX Anomalies... # - 'do' normally gets us 'Desktop', but 'Documents'",
"def test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self):",
"= filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list,",
"= [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list, as_list=True) output_list = output.split(\"\\n\") self.assertEqual(len(output_list),",
"os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path = os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) # 1",
"get_best_match(\"else\", path_list)) # Fuzzy match self.assertEqual( \"Everything Else\", get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\",",
"4 directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path = os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path)",
"self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self):",
"self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual( \"Everything Else\", get_best_match(\"y\", path_list)) # Full match self.assertEqual(",
"given to exact matches at the beginning self.assertEqual( \"Documents\", get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self):",
"1 symlink to a directory dir_link_path = os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path) # 1",
"Match within self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual( \"Everything Else\", get_best_match(\"y\", path_list)) # Full",
"follow_links=False) self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list),",
"output = get_print_directories(path_list) output_list = output.split(\" \") self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self): path_list =",
"# Match beginning or end self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list))",
"os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) #",
"output = get_print_directories(path_list, as_list=True) output_list = output.split(\"\\n\") self.assertEqual(len(output_list), 4) def test_get_best_match(self): path_list =",
"os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def",
"\"Projects\", \"Everything Else\", \"else\"] # Match beginning or end self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list))",
"symlink file_path = os.path.join(test_dir_path, \"some_file\") file_link_path = os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path, file_link_path) #",
"1 regular file and 1 symlink file_path = os.path.join(test_dir_path, \"some_file\") file_link_path = os.path.join(test_dir_path,",
"file_link_path @classmethod def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def",
"os.path.join(test_dir_path, \"some_file\") file_link_path = os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path, file_link_path) # Paths used in",
"= \"fixtures\" def touch(path): with open(path, 'a'): os.utime(path, None) class TestFuzzyCD(unittest.TestCase): @classmethod def",
"if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) # Root directory for tests os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4",
"def test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self):",
"- 'do' normally gets us 'Desktop', but 'Documents' seems more useful, # so",
"None) class TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls): script_path = os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path) test_dir_path",
"\"four\"] output = get_print_directories(path_list) output_list = output.split(\" \") self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self): path_list",
"= os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path, file_link_path) # Paths used in tests below cls.test_dir_path",
"test_get_best_match_no_match(self): path_list = [\"one\", \"two\", \"three\"] self.assertEqual(None, get_best_match(\"xyz\", path_list)) if __name__ == \"__main__\":",
"4) def test_get_print_directories_as_list(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list, as_list=True)",
"= file_path cls.file_link_path = file_link_path @classmethod def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path))",
"test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self): path_list",
"path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self): path_list =",
"1 symlink file_path = os.path.join(test_dir_path, \"some_file\") file_link_path = os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path, file_link_path)",
"# 1 hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1 regular file and 1 symlink",
"path_list)) def test_get_best_match_no_match(self): path_list = [\"one\", \"two\", \"three\"] self.assertEqual(None, get_best_match(\"xyz\", path_list)) if __name__",
"os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path, file_link_path) # Paths used in tests below cls.test_dir_path =",
"path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list, as_list=True) output_list = output.split(\"\\n\")",
"test_dir_path cls.dir_link_path = dir_link_path cls.file_path = file_path cls.file_link_path = file_link_path @classmethod def get_test_dir_path_list(cls):",
"get_print_directories, get_best_match) TEST_DIR = \"fixtures\" def touch(path): with open(path, 'a'): os.utime(path, None) class",
"( path_is_directory, filter_paths, get_print_directories, get_best_match) TEST_DIR = \"fixtures\" def touch(path): with open(path, 'a'):",
"path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) # Case insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual(",
"[ \"Desktop\", \"Documents\", \"Downloads\", \"Projects\", \"Everything Else\", \"else\"] # Match beginning or end",
"dir_link_path cls.file_path = file_path cls.file_link_path = file_link_path @classmethod def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def",
"ignore_errors=False) # Root directory for tests os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4 directories os.mkdir(os.path.join(test_dir_path, \"one\"))",
"self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4)",
"test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse(",
"a higher priority is given to exact matches at the beginning self.assertEqual( \"Documents\",",
"= filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list,",
"filtered_path_list = filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list =",
"'do' normally gets us 'Desktop', but 'Documents' seems more useful, # so a",
"4) def test_get_best_match(self): path_list = [ \"Desktop\", \"Documents\", \"Downloads\", \"Projects\", \"Everything Else\", \"else\"]",
"\"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\", get_best_match(\"Else\", path_list)) # XXX Anomalies... # - 'do'",
"file_path = os.path.join(test_dir_path, \"some_file\") file_link_path = os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path, file_link_path) # Paths",
"useful, # so a higher priority is given to exact matches at the",
"match self.assertEqual( \"else\", get_best_match(\"else\", path_list)) # Fuzzy match self.assertEqual( \"Everything Else\", get_best_match(\"something\", path_list))",
"directory for tests os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4 directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path,",
"\"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list)) # Match within self.assertEqual( \"Downloads\", get_best_match(\"load\",",
"filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=False)",
"= dir_link_path cls.file_path = file_path cls.file_link_path = file_link_path @classmethod def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path)",
"# - 'do' normally gets us 'Desktop', but 'Documents' seems more useful, #",
"fuzzycd import ( path_is_directory, filter_paths, get_print_directories, get_best_match) TEST_DIR = \"fixtures\" def touch(path): with",
"match self.assertEqual( \"Everything Else\", get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\",",
"os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) # Root directory for",
"import os import shutil import unittest from fuzzycd import ( path_is_directory, filter_paths, get_print_directories,",
"get_best_match(\"y\", path_list)) # Full match self.assertEqual( \"else\", get_best_match(\"else\", path_list)) # Fuzzy match self.assertEqual(",
"= self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list()",
"self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\", get_best_match(\"Else\", path_list)) # XXX Anomalies... # -",
"end self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list)) # Match within self.assertEqual(",
"self.assertEqual( \"else\", get_best_match(\"Else\", path_list)) # XXX Anomalies... # - 'do' normally gets us",
"= file_link_path @classmethod def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path))",
"path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self): path_list =",
"\"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\", get_best_match(\"Else\", path_list)) # XXX",
"= get_print_directories(path_list, as_list=True) output_list = output.split(\"\\n\") self.assertEqual(len(output_list), 4) def test_get_best_match(self): path_list = [",
"= output.split(\"\\n\") self.assertEqual(len(output_list), 4) def test_get_best_match(self): path_list = [ \"Desktop\", \"Documents\", \"Downloads\", \"Projects\",",
"\"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) # Case insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\",",
"get_best_match(\"top\", path_list)) # Match within self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual( \"Everything Else\", get_best_match(\"y\",",
"Match beginning or end self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list)) #",
"insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\", get_best_match(\"Else\", path_list))",
"\") self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output =",
"@classmethod def setUpClass(cls): script_path = os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path, TEST_DIR)",
"\"Everything Else\", get_best_match(\"y\", path_list)) # Full match self.assertEqual( \"else\", get_best_match(\"else\", path_list)) # Fuzzy",
"follow_links=True) self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list),",
"or end self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list)) # Match within",
"def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue(",
"= self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list()",
"get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list)) # Match within self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list))",
"\"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path = os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) # 1 symlink",
"\"three\", \"four\"] output = get_print_directories(path_list) output_list = output.split(\" \") self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self):",
"os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) # Root directory for tests os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4 directories",
"cls.test_dir_path = test_dir_path cls.dir_link_path = dir_link_path cls.file_path = file_path cls.file_link_path = file_link_path @classmethod",
"open(path, 'a'): os.utime(path, None) class TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls): script_path = os.path.realpath(__file__) script_dir_path",
"def setUpClass(cls): script_path = os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path, TEST_DIR) if",
"so a higher priority is given to exact matches at the beginning self.assertEqual(",
"output_list = output.split(\"\\n\") self.assertEqual(len(output_list), 4) def test_get_best_match(self): path_list = [ \"Desktop\", \"Documents\", \"Downloads\",",
"<gh_stars>0 import os import shutil import unittest from fuzzycd import ( path_is_directory, filter_paths,",
"shutil.rmtree(test_dir_path, ignore_errors=False) # Root directory for tests os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4 directories os.mkdir(os.path.join(test_dir_path,",
"os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path = os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) # 1 symlink to a directory",
"return os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True))",
"= os.path.join(test_dir_path, \"some_file\") file_link_path = os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path, file_link_path) # Paths used",
"'Documents' seems more useful, # so a higher priority is given to exact",
"path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self): path_list =",
"hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1 regular file and 1 symlink file_path =",
"gets us 'Desktop', but 'Documents' seems more useful, # so a higher priority",
"5) def test_get_print_directories(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list) output_list",
"# Root directory for tests os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4 directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path,",
"below cls.test_dir_path = test_dir_path cls.dir_link_path = dir_link_path cls.file_path = file_path cls.file_link_path = file_link_path",
"and 1 symlink file_path = os.path.join(test_dir_path, \"some_file\") file_link_path = os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path,",
"filtered_path_list = filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list =",
"directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path = os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) #",
"dir_link_path) # 1 hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1 regular file and 1",
"= test_dir_path cls.dir_link_path = dir_link_path cls.file_path = file_path cls.file_link_path = file_link_path @classmethod def",
"cls.file_link_path = file_link_path @classmethod def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self):",
"self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list),",
"= [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list) output_list = output.split(\" \") self.assertEqual(len(output_list),",
"self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list)) # Match within self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual( \"Everything",
"path_is_directory, filter_paths, get_print_directories, get_best_match) TEST_DIR = \"fixtures\" def touch(path): with open(path, 'a'): os.utime(path,",
"filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=False)",
"os.utime(path, None) class TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls): script_path = os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path)",
"def test_get_best_match(self): path_list = [ \"Desktop\", \"Documents\", \"Downloads\", \"Projects\", \"Everything Else\", \"else\"] #",
"= get_print_directories(path_list) output_list = output.split(\" \") self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self): path_list = [\"one\",",
"\"else\"] # Match beginning or end self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\",",
"include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output =",
"follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list =",
"\"Downloads\", get_best_match(\"dol\", path_list)) # Case insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\",",
"# Match within self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual( \"Everything Else\", get_best_match(\"y\", path_list)) #",
"get_best_match(\"dol\", path_list)) # Case insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list))",
"touch(file_path) os.symlink(file_path, file_link_path) # Paths used in tests below cls.test_dir_path = test_dir_path cls.dir_link_path",
"test_get_print_directories(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list) output_list = output.split(\"",
"filtered_path_list = filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self): path_list = [\"one\", \"two\", \"three\",",
"seems more useful, # so a higher priority is given to exact matches",
"\"two\", \"three\", \"four\"] output = get_print_directories(path_list) output_list = output.split(\" \") self.assertEqual(len(output_list), 4) def",
"\".hidden_dir\")) # 1 regular file and 1 symlink file_path = os.path.join(test_dir_path, \"some_file\") file_link_path",
"import shutil import unittest from fuzzycd import ( path_is_directory, filter_paths, get_print_directories, get_best_match) TEST_DIR",
"get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) # Case insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list))",
"\"Everything Else\", get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) #",
"\"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path = os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) # 1 symlink to a",
"test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def",
"get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\", get_best_match(\"Else\", path_list)) # XXX Anomalies... # - 'do' normally",
"[\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list) output_list = output.split(\" \") self.assertEqual(len(output_list), 4)",
"os.symlink(file_path, file_link_path) # Paths used in tests below cls.test_dir_path = test_dir_path cls.dir_link_path =",
"output.split(\" \") self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output",
"path_list)) self.assertEqual( \"Everything Else\", get_best_match(\"y\", path_list)) # Full match self.assertEqual( \"else\", get_best_match(\"else\", path_list))",
"get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path,",
"\"four\") os.mkdir(four_dir_path) # 1 symlink to a directory dir_link_path = os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path,",
"= os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) # Root directory",
"path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self): path_list =",
"tests os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4 directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path",
"test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self): path_list",
"import unittest from fuzzycd import ( path_is_directory, filter_paths, get_print_directories, get_best_match) TEST_DIR = \"fixtures\"",
"self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list",
"normally gets us 'Desktop', but 'Documents' seems more useful, # so a higher",
"TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) # Root directory for tests os.mkdir(test_dir_path) os.chdir(test_dir_path) #",
"filtered_path_list = filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list =",
"four_dir_path = os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) # 1 symlink to a directory dir_link_path =",
"with open(path, 'a'): os.utime(path, None) class TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls): script_path = os.path.realpath(__file__)",
"\"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual( \"Everything Else\", get_best_match(\"y\", path_list)) # Full match self.assertEqual( \"else\",",
"Case insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\", get_best_match(\"Else\",",
"def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self):",
"within self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual( \"Everything Else\", get_best_match(\"y\", path_list)) # Full match",
"= os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False)",
"cls.dir_link_path = dir_link_path cls.file_path = file_path cls.file_link_path = file_link_path @classmethod def get_test_dir_path_list(cls): return",
"path_list)) # Fuzzy match self.assertEqual( \"Everything Else\", get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list))",
"'Desktop', but 'Documents' seems more useful, # so a higher priority is given",
"test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self): path_list",
"us 'Desktop', but 'Documents' seems more useful, # so a higher priority is",
"\"Desktop\", get_best_match(\"top\", path_list)) # Match within self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual( \"Everything Else\",",
"= filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self): path_list = [\"one\", \"two\", \"three\", \"four\"]",
"\"three\")) four_dir_path = os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) # 1 symlink to a directory dir_link_path",
"def touch(path): with open(path, 'a'): os.utime(path, None) class TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls): script_path",
"directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1 regular file and 1 symlink file_path = os.path.join(test_dir_path,",
"get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self): path_list = [\"one\", \"two\", \"three\"] self.assertEqual(None, get_best_match(\"xyz\", path_list)) if",
"tests below cls.test_dir_path = test_dir_path cls.dir_link_path = dir_link_path cls.file_path = file_path cls.file_link_path =",
"self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5)",
"touch(path): with open(path, 'a'): os.utime(path, None) class TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls): script_path =",
"\"three\", \"four\"] output = get_print_directories(path_list, as_list=True) output_list = output.split(\"\\n\") self.assertEqual(len(output_list), 4) def test_get_best_match(self):",
"def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list,",
"def test_get_print_directories(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list) output_list =",
"= os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) # Root directory for tests os.mkdir(test_dir_path)",
"\"four\"] output = get_print_directories(path_list, as_list=True) output_list = output.split(\"\\n\") self.assertEqual(len(output_list), 4) def test_get_best_match(self): path_list",
"Else\", get_best_match(\"y\", path_list)) # Full match self.assertEqual( \"else\", get_best_match(\"else\", path_list)) # Fuzzy match",
"os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) # 1 symlink to a directory dir_link_path = os.path.join(test_dir_path, \"dir_link\")",
"self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path,",
"filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=True)",
"exact matches at the beginning self.assertEqual( \"Documents\", get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self): path_list =",
"get_print_directories(path_list, as_list=True) output_list = output.split(\"\\n\") self.assertEqual(len(output_list), 4) def test_get_best_match(self): path_list = [ \"Desktop\",",
"def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False))",
"path_list = [ \"Desktop\", \"Documents\", \"Downloads\", \"Projects\", \"Everything Else\", \"else\"] # Match beginning",
"def test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self):",
"symlink to a directory dir_link_path = os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path) # 1 hidden",
"Root directory for tests os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4 directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\"))",
"get_best_match) TEST_DIR = \"fixtures\" def touch(path): with open(path, 'a'): os.utime(path, None) class TestFuzzyCD(unittest.TestCase):",
"self.assertEqual( \"Everything Else\", get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list))",
"def test_get_best_match_no_match(self): path_list = [\"one\", \"two\", \"three\"] self.assertEqual(None, get_best_match(\"xyz\", path_list)) if __name__ ==",
"a directory dir_link_path = os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path) # 1 hidden directory os.mkdir(os.path.join(test_dir_path,",
"self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list)) # Match within self.assertEqual( \"Downloads\",",
"'a'): os.utime(path, None) class TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls): script_path = os.path.realpath(__file__) script_dir_path =",
"self.assertEqual( \"Everything Else\", get_best_match(\"y\", path_list)) # Full match self.assertEqual( \"else\", get_best_match(\"else\", path_list)) #",
"Anomalies... # - 'do' normally gets us 'Desktop', but 'Documents' seems more useful,",
"priority is given to exact matches at the beginning self.assertEqual( \"Documents\", get_best_match(\"do\", path_list))",
"path_list)) self.assertEqual( \"Desktop\", get_best_match(\"top\", path_list)) # Match within self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual(",
"higher priority is given to exact matches at the beginning self.assertEqual( \"Documents\", get_best_match(\"do\",",
"used in tests below cls.test_dir_path = test_dir_path cls.dir_link_path = dir_link_path cls.file_path = file_path",
"[\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list, as_list=True) output_list = output.split(\"\\n\") self.assertEqual(len(output_list), 4)",
"@classmethod def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def test_path_is_directory_reject_file(self): self.assertFalse(path_is_directory(self.file_path)) def test_path_is_directory_accept_symlink(self):",
"XXX Anomalies... # - 'do' normally gets us 'Desktop', but 'Documents' seems more",
"\"Documents\", \"Downloads\", \"Projects\", \"Everything Else\", \"else\"] # Match beginning or end self.assertEqual( \"Desktop\",",
"from fuzzycd import ( path_is_directory, filter_paths, get_print_directories, get_best_match) TEST_DIR = \"fixtures\" def touch(path):",
"self.assertEqual(len(filtered_path_list), 4) def test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6)",
"cls.file_path = file_path cls.file_link_path = file_link_path @classmethod def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def test_path_is_directory(self):",
"= self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list()",
"self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list",
"= os.path.join(test_dir_path, \"four\") os.mkdir(four_dir_path) # 1 symlink to a directory dir_link_path = os.path.join(test_dir_path,",
"= filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list,",
"\"Desktop\", \"Documents\", \"Downloads\", \"Projects\", \"Everything Else\", \"else\"] # Match beginning or end self.assertEqual(",
"unittest from fuzzycd import ( path_is_directory, filter_paths, get_print_directories, get_best_match) TEST_DIR = \"fixtures\" def",
"os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1 regular file and 1 symlink file_path = os.path.join(test_dir_path, \"some_file\")",
"def test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self):",
"self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\", get_best_match(\"Else\", path_list)) #",
"path_list = [\"one\", \"two\", \"three\"] self.assertEqual(None, get_best_match(\"xyz\", path_list)) if __name__ == \"__main__\": unittest.main()",
"os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path, ignore_errors=False) # Root directory for tests os.mkdir(test_dir_path) os.chdir(test_dir_path)",
"os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4 directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path =",
"os.mkdir(four_dir_path) # 1 symlink to a directory dir_link_path = os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path)",
"\"fixtures\" def touch(path): with open(path, 'a'): os.utime(path, None) class TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls):",
"os.chdir(test_dir_path) # 4 directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path = os.path.join(test_dir_path,",
"self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list)",
"Full match self.assertEqual( \"else\", get_best_match(\"else\", path_list)) # Fuzzy match self.assertEqual( \"Everything Else\", get_best_match(\"something\",",
"more useful, # so a higher priority is given to exact matches at",
"self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) # Case insensitive self.assertEqual( \"Desktop\",",
"self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) # Case insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\",",
"output_list = output.split(\" \") self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self): path_list = [\"one\", \"two\", \"three\",",
"test_get_best_match(self): path_list = [ \"Desktop\", \"Documents\", \"Downloads\", \"Projects\", \"Everything Else\", \"else\"] # Match",
"def test_path_is_directory_accept_symlink(self): self.assertTrue( path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self): path_list",
"path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5)",
"dir_link_path = os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path) # 1 hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) #",
"but 'Documents' seems more useful, # so a higher priority is given to",
"is given to exact matches at the beginning self.assertEqual( \"Documents\", get_best_match(\"do\", path_list)) def",
"test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5) def test_filter_paths_exclude_symlinks(self): path_list",
"5) def test_filter_paths_exclude_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=False) self.assertEqual(len(filtered_path_list), 4) def",
"\"some_file\") file_link_path = os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path, file_link_path) # Paths used in tests",
"at the beginning self.assertEqual( \"Documents\", get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self): path_list = [\"one\", \"two\",",
"as_list=True) output_list = output.split(\"\\n\") self.assertEqual(len(output_list), 4) def test_get_best_match(self): path_list = [ \"Desktop\", \"Documents\",",
"test_get_print_directories_as_list(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list, as_list=True) output_list =",
"class TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls): script_path = os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path) test_dir_path =",
"follow_links=False)) def test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=True) self.assertEqual(len(filtered_path_list), 5) def",
"file_path cls.file_link_path = file_link_path @classmethod def get_test_dir_path_list(cls): return os.listdir(cls.test_dir_path) def test_path_is_directory(self): self.assertTrue(path_is_directory(self.test_dir_path)) def",
"in tests below cls.test_dir_path = test_dir_path cls.dir_link_path = dir_link_path cls.file_path = file_path cls.file_link_path",
"get_print_directories(path_list) output_list = output.split(\" \") self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self): path_list = [\"one\", \"two\",",
"path_list)) # Full match self.assertEqual( \"else\", get_best_match(\"else\", path_list)) # Fuzzy match self.assertEqual( \"Everything",
"path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list) output_list = output.split(\" \")",
"for tests os.mkdir(test_dir_path) os.chdir(test_dir_path) # 4 directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\"))",
"\"Everything Else\", \"else\"] # Match beginning or end self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual(",
"os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path) # 1 hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1 regular",
"get_best_match(\"load\", path_list)) self.assertEqual( \"Everything Else\", get_best_match(\"y\", path_list)) # Full match self.assertEqual( \"else\", get_best_match(\"else\",",
"output.split(\"\\n\") self.assertEqual(len(output_list), 4) def test_get_best_match(self): path_list = [ \"Desktop\", \"Documents\", \"Downloads\", \"Projects\", \"Everything",
"get_best_match(\"Else\", path_list)) # XXX Anomalies... # - 'do' normally gets us 'Desktop', but",
"# Paths used in tests below cls.test_dir_path = test_dir_path cls.dir_link_path = dir_link_path cls.file_path",
"path_list)) # Match within self.assertEqual( \"Downloads\", get_best_match(\"load\", path_list)) self.assertEqual( \"Everything Else\", get_best_match(\"y\", path_list))",
"Paths used in tests below cls.test_dir_path = test_dir_path cls.dir_link_path = dir_link_path cls.file_path =",
"# 1 symlink to a directory dir_link_path = os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path) #",
"matches at the beginning self.assertEqual( \"Documents\", get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self): path_list = [\"one\",",
"# so a higher priority is given to exact matches at the beginning",
"# XXX Anomalies... # - 'do' normally gets us 'Desktop', but 'Documents' seems",
"self.assertEqual(len(output_list), 4) def test_get_best_match(self): path_list = [ \"Desktop\", \"Documents\", \"Downloads\", \"Projects\", \"Everything Else\",",
"os import shutil import unittest from fuzzycd import ( path_is_directory, filter_paths, get_print_directories, get_best_match)",
"\"dir_link\") os.symlink(four_dir_path, dir_link_path) # 1 hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1 regular file",
"self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list,",
"Else\", get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"dol\", path_list)) # Case",
"\"Downloads\", \"Projects\", \"Everything Else\", \"else\"] # Match beginning or end self.assertEqual( \"Desktop\", get_best_match(\"desk\",",
"= output.split(\" \") self.assertEqual(len(output_list), 4) def test_get_print_directories_as_list(self): path_list = [\"one\", \"two\", \"three\", \"four\"]",
"self.assertEqual( \"else\", get_best_match(\"else\", path_list)) # Fuzzy match self.assertEqual( \"Everything Else\", get_best_match(\"something\", path_list)) self.assertEqual(",
"# 1 regular file and 1 symlink file_path = os.path.join(test_dir_path, \"some_file\") file_link_path =",
"6) def test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def",
"path_is_directory(self.dir_link_path, follow_links=True)) def test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list",
"get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\", get_best_match(\"Else\", path_list)) # XXX Anomalies...",
"\"Documents\", get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self): path_list = [\"one\", \"two\", \"three\"] self.assertEqual(None, get_best_match(\"xyz\", path_list))",
"directory dir_link_path = os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path) # 1 hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\"))",
"to exact matches at the beginning self.assertEqual( \"Documents\", get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self): path_list",
"path_list)) self.assertEqual( \"else\", get_best_match(\"Else\", path_list)) # XXX Anomalies... # - 'do' normally gets",
"TEST_DIR = \"fixtures\" def touch(path): with open(path, 'a'): os.utime(path, None) class TestFuzzyCD(unittest.TestCase): @classmethod",
"= self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list), 5) def test_get_print_directories(self): path_list = [\"one\",",
"file_link_path) # Paths used in tests below cls.test_dir_path = test_dir_path cls.dir_link_path = dir_link_path",
"4) def test_filter_paths_include_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def",
"def test_get_print_directories_as_list(self): path_list = [\"one\", \"two\", \"three\", \"four\"] output = get_print_directories(path_list, as_list=True) output_list",
"path_list)) # Case insensitive self.assertEqual( \"Desktop\", get_best_match(\"DESK\", path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual(",
"\"else\", get_best_match(\"Else\", path_list)) # XXX Anomalies... # - 'do' normally gets us 'Desktop',",
"# Fuzzy match self.assertEqual( \"Everything Else\", get_best_match(\"something\", path_list)) self.assertEqual( \"Documents\", get_best_match(\"dos\", path_list)) self.assertEqual(",
"= [ \"Desktop\", \"Documents\", \"Downloads\", \"Projects\", \"Everything Else\", \"else\"] # Match beginning or",
"file_link_path = os.path.join(test_dir_path, \"file_link\") touch(file_path) os.symlink(file_path, file_link_path) # Paths used in tests below",
"test_path_is_directory_reject_symlink(self): self.assertFalse( path_is_directory(self.dir_link_path, follow_links=False)) def test_filter_paths_include_symlinks(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, follow_links=True)",
"to a directory dir_link_path = os.path.join(test_dir_path, \"dir_link\") os.symlink(four_dir_path, dir_link_path) # 1 hidden directory",
"TestFuzzyCD(unittest.TestCase): @classmethod def setUpClass(cls): script_path = os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path,",
"script_path = os.path.realpath(__file__) script_dir_path = os.path.dirname(script_path) test_dir_path = os.path.join(script_dir_path, TEST_DIR) if os.path.exists(test_dir_path): shutil.rmtree(test_dir_path,",
"include_hidden=True) self.assertEqual(len(filtered_path_list), 6) def test_filter_paths_exlude_hidden(self): path_list = self.get_test_dir_path_list() filtered_path_list = filter_paths(path_list, include_hidden=False) self.assertEqual(len(filtered_path_list),",
"# 4 directories os.mkdir(os.path.join(test_dir_path, \"one\")) os.mkdir(os.path.join(test_dir_path, \"two\")) os.mkdir(os.path.join(test_dir_path, \"three\")) four_dir_path = os.path.join(test_dir_path, \"four\")",
"path_list)) self.assertEqual( \"Downloads\", get_best_match(\"DOL\", path_list)) self.assertEqual( \"else\", get_best_match(\"Else\", path_list)) # XXX Anomalies... #",
"shutil import unittest from fuzzycd import ( path_is_directory, filter_paths, get_print_directories, get_best_match) TEST_DIR =",
"Else\", \"else\"] # Match beginning or end self.assertEqual( \"Desktop\", get_best_match(\"desk\", path_list)) self.assertEqual( \"Desktop\",",
"# Full match self.assertEqual( \"else\", get_best_match(\"else\", path_list)) # Fuzzy match self.assertEqual( \"Everything Else\",",
"os.symlink(four_dir_path, dir_link_path) # 1 hidden directory os.mkdir(os.path.join(test_dir_path, \".hidden_dir\")) # 1 regular file and",
"beginning self.assertEqual( \"Documents\", get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self): path_list = [\"one\", \"two\", \"three\"] self.assertEqual(None,",
"the beginning self.assertEqual( \"Documents\", get_best_match(\"do\", path_list)) def test_get_best_match_no_match(self): path_list = [\"one\", \"two\", \"three\"]",
"\"file_link\") touch(file_path) os.symlink(file_path, file_link_path) # Paths used in tests below cls.test_dir_path = test_dir_path"
] |
[
"# -*- coding: utf-8 -*- class classproperty(property): def __get__(self, cls, owner): return classmethod(self.fget).__get__(None,",
"-*- coding: utf-8 -*- class classproperty(property): def __get__(self, cls, owner): return classmethod(self.fget).__get__(None, owner)()"
] |
[
"!!! ''' ################################# # import PyMbs & Lib. # ################################# from PyMbs.Input import",
"Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0])",
"Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x'))",
"F_c, name='Spring') ################################# # generate equations & sim Code # ################################# world.genEquations.Recursive() #world.genCode.Modelica('hexapod_z_kpl','.\\HP_Output',inputsAsInputs=True,",
"BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2',",
"'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6')",
"'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints or Loops #",
"Lesser General Public License for more details. You should have received a copy",
"Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs,",
"p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5",
"should have received a copy of the GNU Lesser General Public License along",
"phi_AP_3 = phi_AP_1 + 2*pi/3 phi_AP_4 = phi_AP_3 + 2*pi/3-pi/9 phi_AP_5 = phi_AP_3",
"Für Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual,",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody(",
"frame # ################################# world=MbsSystem([0,0,-1]) ################################# # Parameters # ################################# # Länge der Zylinderstangen",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl)",
"it under the terms of the GNU Lesser General Public License as published",
"# Hexapod # ################ ################################# # Bodies & KS # ################################# Ground =",
"= phi_BP_1 + 2*pi/3 phi_BP_4 = phi_BP_2 + 2*pi/3 phi_BP_5 = phi_BP_3 +",
"You should have received a copy of the GNU Lesser General Public License",
"Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4',",
"R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl)",
"'I2y', (m2*H2**2)/12) # Traägheit eines Vollzylinders um y die x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2)",
"# ################################# # Länge der Zylinderstangen und Gehäuse hoehe = 0.01 R_AP=0.3 R_BP=0.5",
"Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 =",
"= phi_AP_3 + 2*pi/3-pi/9 phi_AP_5 = phi_AP_3 + 2*pi/3 phi_AP_6 = phi_AP_4 +",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual',",
"l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4)",
"<NAME>, <NAME>, <NAME> ''' ''' Created on 13.05.2011 @author: <NAME> Pfade für Visualisierung",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2')",
"world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual,",
"Foundation, either version 3 of the License, or (at your option) any later",
"2*pi/3 phi_BP_6 = phi_BP_4 + 2*pi/3 phi_AP_1 = pi/6+pi/18 phi_AP_2 = phi_AP_1 +",
"Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 =",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual',",
"add visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' # Für Visualisierung im",
"Public License along with PyMbs. If not, see <http://www.gnu.org/licenses/>. Copyright 2011, 2012 <NAME>,",
"pi/6+pi/18 phi_AP_2 = phi_AP_1 + 2*pi/3-pi/9 phi_AP_3 = phi_AP_1 + 2*pi/3 phi_AP_4 =",
"world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3')",
"name='Spring') ################################# # generate equations & sim Code # ################################# world.genEquations.Recursive() #world.genCode.Modelica('hexapod_z_kpl','.\\HP_Output',inputsAsInputs=True, debugMode=False)",
"General Public License for more details. You should have received a copy of",
"die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061)",
"the GNU Lesser General Public License for more details. You should have received",
"a copy of the GNU Lesser General Public License along with PyMbs. If",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual',",
"Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0])",
"0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### # Anordnungen # ############### phi_BP_1 = pi/2-pi/18 phi_BP_2 =",
"Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### #",
"p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5",
"world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual,",
"p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2',",
"R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl)",
"der Zylinderstangen und Gehäuse hoehe = 0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh",
"p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2',",
"AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für Visualisierung im Dymola Zyl_geh_1",
"coding: utf-8 -*- ''' This file is part of PyMbs. PyMbs is free",
"2*pi/3 phi_AP_6 = phi_AP_4 + 2*pi/3 ################ # Hexapod # ################ ################################# #",
"but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS",
"p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################",
"of the License, or (at your option) any later version. PyMbs is distributed",
"terms of the GNU Lesser General Public License as published by the Free",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"that it will be useful, but WITHOUT ANY WARRANTY; without even the implied",
"m_z_geh = 0.1 m_z_st = 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2',",
"Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"BP = Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0])",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody(",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs',",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual',",
"#l = world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz = world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50 #F_c =",
"Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0])",
"world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints or Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1')",
"= pi/6+pi/18 phi_AP_2 = phi_AP_1 + 2*pi/3-pi/9 phi_AP_3 = phi_AP_1 + 2*pi/3 phi_AP_4",
"world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### # add visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe)",
"################################# Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2',",
"<http://www.gnu.org/licenses/>. Copyright 2011, 2012 <NAME>, <NAME>, <NAME>, <NAME> ''' ''' Created on 13.05.2011",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody(",
"################################# world=MbsSystem([0,0,-1]) ################################# # Parameters # ################################# # Länge der Zylinderstangen und Gehäuse",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual',",
"Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 =",
"from PyMbs.Input import * from PyMbs.Symbolics import Matrix,cos,sin pi = 3.1415926535897932384626433832795 ################################# #",
"p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs',",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' # Für Visualisierung im PyMbs Zyl_geh_1 =",
"Gehäuse hoehe = 0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh = 0.1 m_z_st",
"phi_AP_5 = phi_AP_3 + 2*pi/3 phi_AP_6 = phi_AP_4 + 2*pi/3 ################ # Hexapod",
"Lesser General Public License along with PyMbs. If not, see <http://www.gnu.org/licenses/>. Copyright 2011,",
"BP) world.addJoint( world, Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1')",
"################################# # Länge der Zylinderstangen und Gehäuse hoehe = 0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02",
"2*pi/3 ################ # Hexapod # ################ ################################# # Bodies & KS # #################################",
"#F_c = world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') ################################# # generate equations &",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual',",
"world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' # Für Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual,",
"* from PyMbs.Symbolics import Matrix,cos,sin pi = 3.1415926535897932384626433832795 ################################# # set up inertial",
"BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1])",
"I2z=world.addParam( 'I2z', (m2*R2**2)/2) # Traägheit eines Vollzylinders um z die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh',",
"or Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3')",
"PyMbs. If not, see <http://www.gnu.org/licenses/>. Copyright 2011, 2012 <NAME>, <NAME>, <NAME>, <NAME> '''",
"################################# # generate equations & sim Code # ################################# world.genEquations.Recursive() #world.genCode.Modelica('hexapod_z_kpl','.\\HP_Output',inputsAsInputs=True, debugMode=False) world.show('hexapod_z_kpl')",
"Load # ##################### #l = world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz = world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder')",
"R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1)",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"x die x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12) # Traägheit eines Vollzylinders um y die",
"& KS # ################################# Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x'))",
"KS # ################################# Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1',",
"= Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5',",
"License as published by the Free Software Foundation, either version 3 of the",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6')",
"version. PyMbs is distributed in the hope that it will be useful, but",
"c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12)",
"Dymola Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2",
"Zylinderstangen und Gehäuse hoehe = 0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh =",
"'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### # add",
"can redistribute it and/or modify it under the terms of the GNU Lesser",
"#world.addJoint('fix_BP', world, BP) world.addJoint( world, Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP')",
"world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6,",
"Vollzylinders um z die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027)",
"have received a copy of the GNU Lesser General Public License along with",
"Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs',",
"p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0])",
"m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061)",
"Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0])",
"not, see <http://www.gnu.org/licenses/>. Copyright 2011, 2012 <NAME>, <NAME>, <NAME>, <NAME> ''' ''' Created",
"PyMbs.Symbolics import Matrix,cos,sin pi = 3.1415926535897932384626433832795 ################################# # set up inertial frame #",
"the Free Software Foundation, either version 3 of the License, or (at your",
"<NAME>, <NAME>, <NAME>, <NAME> ''' ''' Created on 13.05.2011 @author: <NAME> Pfade für",
"'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4')",
"################################# print(\"System has been assembled\") ################################# # add Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP')",
"p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs',",
"world.addJoint( world, Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz',",
"R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12) # Traägheit eines Vollzylinders",
"+ 2*pi/3 phi_BP_4 = phi_BP_2 + 2*pi/3 phi_BP_5 = phi_BP_3 + 2*pi/3 phi_BP_6",
"################################################################################ AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0])",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# # Joints #",
"'DistanceSensor') #lz = world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50 #F_c = world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder,",
"the GNU Lesser General Public License along with PyMbs. If not, see <http://www.gnu.org/licenses/>.",
"Vollzylinders um y die x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2) # Traägheit eines Vollzylinders um",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody(",
"p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2',",
"<NAME> ''' ''' Created on 13.05.2011 @author: <NAME> Pfade für Visualisierung anpassen !!!",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody(",
"p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2',",
"Lib. # ################################# from PyMbs.Input import * from PyMbs.Symbolics import Matrix,cos,sin pi =",
"# Anordnungen # ############### phi_BP_1 = pi/2-pi/18 phi_BP_2 = phi_BP_1 + pi/9 phi_BP_3",
"'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## #",
"Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0])",
"Lesser General Public License as published by the Free Software Foundation, either version",
"published by the Free Software Foundation, either version 3 of the License, or",
"world=MbsSystem([0,0,-1]) ################################# # Parameters # ################################# # Länge der Zylinderstangen und Gehäuse hoehe",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4')",
"Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 =",
"Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0])",
"Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 =",
"BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP",
"################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2",
"Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x'))",
"Parameters # ################################# # Länge der Zylinderstangen und Gehäuse hoehe = 0.01 R_AP=0.3",
"################################# #world.addJoint('fix_BP', world, BP) world.addJoint( world, Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx', 'Ry',",
"utf-8 -*- ''' This file is part of PyMbs. PyMbs is free software:",
"GNU Lesser General Public License along with PyMbs. If not, see <http://www.gnu.org/licenses/>. Copyright",
"##################### #l = world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz = world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50 #F_c",
"'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints or",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs',",
"I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y',",
"world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual,",
"Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' # Für Visualisierung im PyMbs Zyl_geh_1 = world.addBody(",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5')",
"Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0])",
"Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x'))",
"R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl)",
"Visualisierung im PyMbs Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2',",
"Software Foundation, either version 3 of the License, or (at your option) any",
"Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5')",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody(",
"Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# # Joints # ################################# #world.addJoint('fix_BP', world,",
"up inertial frame # ################################# world=MbsSystem([0,0,-1]) ################################# # Parameters # ################################# # Länge",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### # Anordnungen #",
"= pi/2-pi/18 phi_BP_2 = phi_BP_1 + pi/9 phi_BP_3 = phi_BP_1 + 2*pi/3 phi_BP_4",
"= world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz = world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50 #F_c = world.addExpression('SpringForce',",
"p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für Visualisierung im Dymola Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual',",
"um y die x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2) # Traägheit eines Vollzylinders um z",
"p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x'))",
"Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' # Für Visualisierung im PyMbs Zyl_geh_1",
"inertial frame # ################################# world=MbsSystem([0,0,-1]) ################################# # Parameters # ################################# # Länge der",
"0.1 m_z_st = 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2',",
"Traägheit eines Vollzylinders um z die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam(",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' # Für Visualisierung im",
"by the Free Software Foundation, either version 3 of the License, or (at",
"world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints or Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1,",
"Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2',",
"p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z]))",
"um z die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam(",
"Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0])",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody(",
"import PyMbs & Lib. # ################################# from PyMbs.Input import * from PyMbs.Symbolics import",
"License, or (at your option) any later version. PyMbs is distributed in the",
"= 0.1 m_z_st = 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50)",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für Visualisierung im Dymola",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody(",
"# Bodies & KS # ################################# Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1",
"'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ###############",
"Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0])",
"50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12) # Traägheit eines Vollzylinders um x",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### # Anordnungen # ############### phi_BP_1 = pi/2-pi/18",
"Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x'))",
"m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### # Anordnungen",
"''' ################################# # import PyMbs & Lib. # ################################# from PyMbs.Input import *",
"A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.",
"of the GNU Lesser General Public License as published by the Free Software",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für Visualisierung im Dymola",
"#world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') ################################# # generate equations & sim Code # ################################# world.genEquations.Recursive()",
"R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) #################################",
"Public License as published by the Free Software Foundation, either version 3 of",
"PURPOSE. See the GNU Lesser General Public License for more details. You should",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs',",
"world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz = world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50 #F_c = world.addExpression('SpringForce', 'F_c',",
"BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1',",
"assembled\") ################################# # add Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### # add Imput",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody(",
"p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs',",
"p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0])",
"world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints or Loops",
"= phi_AP_1 + 2*pi/3 phi_AP_4 = phi_AP_3 + 2*pi/3-pi/9 phi_AP_5 = phi_AP_3 +",
"+ 2*pi/3 phi_AP_6 = phi_AP_4 + 2*pi/3 ################ # Hexapod # ################ #################################",
"& Load # ##################### #l = world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz = world.addSensor.Distance(BP,AP, 'lz',",
"''' ''' Created on 13.05.2011 @author: <NAME> Pfade für Visualisierung anpassen !!! '''",
"Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0])",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2')",
"General Public License as published by the Free Software Foundation, either version 3",
"Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x'))",
"world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50 #F_c = world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') #################################",
"# Für Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4')",
"im PyMbs Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0])",
"Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0])",
"############### # Anordnungen # ############### phi_BP_1 = pi/2-pi/18 phi_BP_2 = phi_BP_1 + pi/9",
"'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6')",
"See the GNU Lesser General Public License for more details. You should have",
"Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints or Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs,",
"world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' # Für Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual,",
"AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für Visualisierung im Dymola Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1')",
"FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for",
"FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more",
"phi_AP_3 + 2*pi/3-pi/9 phi_AP_5 = phi_AP_3 + 2*pi/3 phi_AP_6 = phi_AP_4 + 2*pi/3",
"p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4",
"2*pi/3-pi/9 phi_AP_3 = phi_AP_1 + 2*pi/3 phi_AP_4 = phi_AP_3 + 2*pi/3-pi/9 phi_AP_5 =",
"Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0])",
"p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2',",
"für Visualisierung anpassen !!! ''' ################################# # import PyMbs & Lib. # #################################",
"Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0])",
"world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual,",
"Free Software Foundation, either version 3 of the License, or (at your option)",
"import Matrix,cos,sin pi = 3.1415926535897932384626433832795 ################################# # set up inertial frame # #################################",
"world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# #",
"it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty",
"world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für",
"p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6",
"I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432)",
"I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### # Anordnungen # ############### phi_BP_1 = pi/2-pi/18 phi_BP_2",
"'I2z', (m2*R2**2)/2) # Traägheit eines Vollzylinders um z die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6)",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual',",
"without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"<NAME> Pfade für Visualisierung anpassen !!! ''' ################################# # import PyMbs & Lib.",
"# Länge der Zylinderstangen und Gehäuse hoehe = 0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04",
"# add visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' # Für Visualisierung",
"# Constraints or Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3,",
"p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5",
"under the terms of the GNU Lesser General Public License as published by",
"2012 <NAME>, <NAME>, <NAME>, <NAME> ''' ''' Created on 13.05.2011 @author: <NAME> Pfade",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1')",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# # Joints # ################################# #world.addJoint('fix_BP',",
"################################# # Parameters # ################################# # Länge der Zylinderstangen und Gehäuse hoehe =",
"Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' # Für Visualisierung im PyMbs Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1')",
"Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 =",
"p=[0,0,0]) ''' # Für Visualisierung im PyMbs Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual',",
"= phi_BP_4 + 2*pi/3 phi_AP_1 = pi/6+pi/18 phi_AP_2 = phi_AP_1 + 2*pi/3-pi/9 phi_AP_3",
"Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody(",
"Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs,",
"eines Vollzylinders um z die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x',",
"I2x=world.addParam( 'I2x', (m2*H2**2)/12) # Traägheit eines Vollzylinders um x die x-Achse I2y=world.addParam( 'I2y',",
"p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0])",
"Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 =",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3')",
"'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5')",
"your option) any later version. PyMbs is distributed in the hope that it",
"R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12) # Traägheit eines Vollzylinders um x die x-Achse",
"world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6)",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs',",
"phi_AP_1 = pi/6+pi/18 phi_AP_2 = phi_AP_1 + 2*pi/3-pi/9 phi_AP_3 = phi_AP_1 + 2*pi/3",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody(",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1",
"of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General",
"Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0])",
"0.432) ############### # Anordnungen # ############### phi_BP_1 = pi/2-pi/18 phi_BP_2 = phi_BP_1 +",
"Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0])",
"p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4",
"'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6')",
"world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1')",
"phi_BP_1 + 2*pi/3 phi_BP_4 = phi_BP_2 + 2*pi/3 phi_BP_5 = phi_BP_3 + 2*pi/3",
"p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0])",
"+ 2*pi/3 phi_AP_1 = pi/6+pi/18 phi_AP_2 = phi_AP_1 + 2*pi/3-pi/9 phi_AP_3 = phi_AP_1",
"file is part of PyMbs. PyMbs is free software: you can redistribute it",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"AP,['Tx', 'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4')",
"phi_BP_4 + 2*pi/3 phi_AP_1 = pi/6+pi/18 phi_AP_2 = phi_AP_1 + 2*pi/3-pi/9 phi_AP_3 =",
"# Traägheit eines Vollzylinders um y die x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2) # Traägheit",
"Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x'))",
"0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003)",
"= phi_AP_1 + 2*pi/3-pi/9 phi_AP_3 = phi_AP_1 + 2*pi/3 phi_AP_4 = phi_AP_3 +",
"the hope that it will be useful, but WITHOUT ANY WARRANTY; without even",
"im Dymola Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0])",
"will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of",
"y die x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2) # Traägheit eines Vollzylinders um z die",
"along with PyMbs. If not, see <http://www.gnu.org/licenses/>. Copyright 2011, 2012 <NAME>, <NAME>, <NAME>,",
"<NAME>, <NAME> ''' ''' Created on 13.05.2011 @author: <NAME> Pfade für Visualisierung anpassen",
"Traägheit eines Vollzylinders um x die x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12) # Traägheit eines",
"(m2*R2**2)/2) # Traägheit eines Vollzylinders um z die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74)",
"(m2*H2**2)/12) # Traägheit eines Vollzylinders um y die x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2) #",
"Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### # add visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) '''",
"p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2',",
"######################## # Constraints or Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2')",
"Für Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual,",
"(m2*H2**2)/12) # Traägheit eines Vollzylinders um x die x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12) #",
"world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual,",
"'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x',",
"p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2',",
"Joints # ################################# #world.addJoint('fix_BP', world, BP) world.addJoint( world, Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty',",
"# ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs,",
"m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12) # Traägheit eines Vollzylinders um",
"# add Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### # add Imput & Load",
"Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0])",
"p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2',",
"is part of PyMbs. PyMbs is free software: you can redistribute it and/or",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual',",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs',",
"H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12) # Traägheit eines Vollzylinders um x die x-Achse I2y=world.addParam(",
"& Lib. # ################################# from PyMbs.Input import * from PyMbs.Symbolics import Matrix,cos,sin pi",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5')",
"p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4",
"2011, 2012 <NAME>, <NAME>, <NAME>, <NAME> ''' ''' Created on 13.05.2011 @author: <NAME>",
"p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für Visualisierung im Dymola Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"# ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' # Für Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual,",
"Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0])",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual,",
"m_z_st = 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP)",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs',",
"Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0])",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' # Für Visualisierung im PyMbs",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody(",
"Created on 13.05.2011 @author: <NAME> Pfade für Visualisierung anpassen !!! ''' ################################# #",
"more details. You should have received a copy of the GNU Lesser General",
"p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2',",
"18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange',",
"world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ########################",
"2*pi/3-pi/9 phi_AP_5 = phi_AP_3 + 2*pi/3 phi_AP_6 = phi_AP_4 + 2*pi/3 ################ #",
"l_zyl=0.6 m_z_geh = 0.1 m_z_st = 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP)",
"R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# # add visualisation # ################################# print(\"System",
"Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2',",
"world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5,",
"'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2')",
"p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' # Für Visualisierung im PyMbs Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x'))",
"world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') #####################",
"0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh = 0.1 m_z_st = 0.1 c=world.addParam('c',10)",
"################################# # add Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### # add Imput &",
"Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0])",
"p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) '''",
"Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 =",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2')",
"p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################",
"p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs',",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4')",
"Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 =",
"Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4,",
"############### phi_BP_1 = pi/2-pi/18 phi_BP_2 = phi_BP_1 + pi/9 phi_BP_3 = phi_BP_1 +",
"Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# # Joints # ################################# #world.addJoint('fix_BP', world, BP) world.addJoint(",
"p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2',",
"''' # Für Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual,",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"'lz', 'DistanceSensor_Cylinder') #c=50 #F_c = world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') ################################# #",
"= phi_AP_3 + 2*pi/3 phi_AP_6 = phi_AP_4 + 2*pi/3 ################ # Hexapod #",
"the terms of the GNU Lesser General Public License as published by the",
"Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 =",
"of the GNU Lesser General Public License along with PyMbs. If not, see",
"Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# #",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2')",
"Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### # add visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe)",
"p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0])",
"-*- ''' This file is part of PyMbs. PyMbs is free software: you",
"phi_AP_1 + 2*pi/3-pi/9 phi_AP_3 = phi_AP_1 + 2*pi/3 phi_AP_4 = phi_AP_3 + 2*pi/3-pi/9",
"-c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') ################################# # generate equations & sim Code # #################################",
"+ 2*pi/3-pi/9 phi_AP_3 = phi_AP_1 + 2*pi/3 phi_AP_4 = phi_AP_3 + 2*pi/3-pi/9 phi_AP_5",
"# Parameters # ################################# # Länge der Zylinderstangen und Gehäuse hoehe = 0.01",
"p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4",
"#world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### # add Imput & Load # ##################### #l = world.addSensor.Distance(AP,BP.BP_Feder,",
"p=[0,0,0]) ################################# # Joints # ################################# #world.addJoint('fix_BP', world, BP) world.addJoint( world, Ground, name='fix_BP')",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' # Für",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 =",
"I2y=world.addParam( 'I2y', (m2*H2**2)/12) # Traägheit eines Vollzylinders um y die x-Achse I2z=world.addParam( 'I2z',",
"+ 2*pi/3 ################ # Hexapod # ################ ################################# # Bodies & KS #",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3')",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"################################# # Bodies & KS # ################################# Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP =",
"################################# # add visualisation # ################################# print(\"System has been assembled\") ################################# # add",
"Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0])",
"world, Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2')",
"you can redistribute it and/or modify it under the terms of the GNU",
"Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### # add Imput & Load # #####################",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6')",
"Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl)",
"R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh = 0.1 m_z_st = 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5)",
"world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') '''",
"be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY",
"BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6',",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0])",
"Constraints or Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs,",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6')",
"#c=50 #F_c = world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') ################################# # generate equations",
"#Für Visualisierung im Dymola Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0])",
"redistribute it and/or modify it under the terms of the GNU Lesser General",
"Vollzylinders um x die x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12) # Traägheit eines Vollzylinders um",
"Anordnungen # ############### phi_BP_1 = pi/2-pi/18 phi_BP_2 = phi_BP_1 + pi/9 phi_BP_3 =",
"################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z',",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4')",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für Visualisierung",
"Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0])",
"for more details. You should have received a copy of the GNU Lesser",
"p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2',",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody(",
"world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual,",
"# Traägheit eines Vollzylinders um z die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353)",
"phi_AP_4 = phi_AP_3 + 2*pi/3-pi/9 phi_AP_5 = phi_AP_3 + 2*pi/3 phi_AP_6 = phi_AP_4",
"'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### # add visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP,",
"die x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12) # Traägheit eines Vollzylinders um y die x-Achse",
"the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6",
"world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# # add visualisation # #################################",
"hoehe = 0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh = 0.1 m_z_st =",
"'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5')",
"Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 =",
"''' # Für Visualisierung im PyMbs Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x'))",
"p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0])",
"''' This file is part of PyMbs. PyMbs is free software: you can",
"m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12) #",
"Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0])",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6')",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual',",
"+ pi/9 phi_BP_3 = phi_BP_1 + 2*pi/3 phi_BP_4 = phi_BP_2 + 2*pi/3 phi_BP_5",
"################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2",
"# ################################# world=MbsSystem([0,0,-1]) ################################# # Parameters # ################################# # Länge der Zylinderstangen und",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6')",
"world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual,",
"print(\"System has been assembled\") ################################# # add Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') #####################",
"################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### # add Imput & Load # ##################### #l =",
"world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# # add visualisation # ################################# print(\"System has been assembled\")",
"world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4)",
"or (at your option) any later version. PyMbs is distributed in the hope",
"General Public License along with PyMbs. If not, see <http://www.gnu.org/licenses/>. Copyright 2011, 2012",
"################################# # set up inertial frame # ################################# world=MbsSystem([0,0,-1]) ################################# # Parameters #",
"= 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe)",
"phi_BP_1 + pi/9 phi_BP_3 = phi_BP_1 + 2*pi/3 phi_BP_4 = phi_BP_2 + 2*pi/3",
"Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x'))",
"AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für Visualisierung im Dymola Zyl_geh_1 = world.addBody(",
"'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz',",
"# ################################# Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0])",
"Für Visualisierung im PyMbs Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0])",
"'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433)",
"'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### # add visualisation # #####################",
"#world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# # add visualisation # ################################# print(\"System has been assembled\") #################################",
"Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# # Joints # ################################# #world.addJoint('fix_BP', world, BP) world.addJoint( world, Ground,",
"PyMbs is distributed in the hope that it will be useful, but WITHOUT",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5')",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4')",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody(",
"later version. PyMbs is distributed in the hope that it will be useful,",
"world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual,",
"p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2',",
"world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual,",
"License for more details. You should have received a copy of the GNU",
"world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints or Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2,",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody(",
"und Gehäuse hoehe = 0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh = 0.1",
"Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 =",
"phi_BP_4 = phi_BP_2 + 2*pi/3 phi_BP_5 = phi_BP_3 + 2*pi/3 phi_BP_6 = phi_BP_4",
"Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"world, BP) world.addJoint( world, Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz',",
"p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# # Joints # ################################# #world.addJoint('fix_BP', world, BP) world.addJoint( world,",
"Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0])",
"GNU Lesser General Public License for more details. You should have received a",
"world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# # add visualisation # ################################# print(\"System has",
"p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs',",
"Visualisierung im Dymola Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2',",
"'I2x', (m2*H2**2)/12) # Traägheit eines Vollzylinders um x die x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12)",
"has been assembled\") ################################# # add Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### #",
"R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# # add visualisation #",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3')",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs',",
"Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0])",
"add visualisation # ################################# print(\"System has been assembled\") ################################# # add Sensors #",
"= world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3',",
"# Für Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl)",
"is free software: you can redistribute it and/or modify it under the terms",
"phi_BP_5 = phi_BP_3 + 2*pi/3 phi_BP_6 = phi_BP_4 + 2*pi/3 phi_AP_1 = pi/6+pi/18",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# # Joints",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# # Joints # #################################",
"distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;",
"p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für Visualisierung",
"Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0])",
"any later version. PyMbs is distributed in the hope that it will be",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public",
"WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual',",
"world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') ################################# # generate equations & sim Code",
"pi/2-pi/18 phi_BP_2 = phi_BP_1 + pi/9 phi_BP_3 = phi_BP_1 + 2*pi/3 phi_BP_4 =",
"Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0])",
"free software: you can redistribute it and/or modify it under the terms of",
"1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12) # Traägheit",
"p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5",
"Matrix,cos,sin pi = 3.1415926535897932384626433832795 ################################# # set up inertial frame # ################################# world=MbsSystem([0,0,-1])",
"import * from PyMbs.Symbolics import Matrix,cos,sin pi = 3.1415926535897932384626433832795 ################################# # set up",
"world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### # add visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP,",
"# set up inertial frame # ################################# world=MbsSystem([0,0,-1]) ################################# # Parameters # #################################",
"2*pi/3 phi_BP_5 = phi_BP_3 + 2*pi/3 phi_BP_6 = phi_BP_4 + 2*pi/3 phi_AP_1 =",
"phi_AP_4 + 2*pi/3 ################ # Hexapod # ################ ################################# # Bodies & KS",
"world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0])",
"world.addVisualisation.Frame(Ground,0.6) ################################# # add visualisation # ################################# print(\"System has been assembled\") ################################# #",
"################################# # Joints # ################################# #world.addJoint('fix_BP', world, BP) world.addJoint( world, Ground, name='fix_BP') jAP=world.addJoint(world,",
"R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh = 0.1 m_z_st = 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1',",
"# import PyMbs & Lib. # ################################# from PyMbs.Input import * from PyMbs.Symbolics",
"p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2',",
"R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl)",
"Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 =",
"If not, see <http://www.gnu.org/licenses/>. Copyright 2011, 2012 <NAME>, <NAME>, <NAME>, <NAME> ''' '''",
"received a copy of the GNU Lesser General Public License along with PyMbs.",
"implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU",
"even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"= phi_BP_3 + 2*pi/3 phi_BP_6 = phi_BP_4 + 2*pi/3 phi_AP_1 = pi/6+pi/18 phi_AP_2",
"BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP = world.addBody(name='Arbeitsplattform',",
"# add Imput & Load # ##################### #l = world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz",
"######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs, 'Verbindung_1') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_2, Zyl_stange_2.Zyl_stange_2_cs, 'Verbindung_2') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_3, Zyl_stange_3.Zyl_stange_3_cs, 'Verbindung_3') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4')",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual',",
"phi_BP_2 = phi_BP_1 + pi/9 phi_BP_3 = phi_BP_1 + 2*pi/3 phi_BP_4 = phi_BP_2",
"p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs',",
"p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2',",
"phi_AP_3 + 2*pi/3 phi_AP_6 = phi_AP_4 + 2*pi/3 ################ # Hexapod # ################",
"Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0])",
"world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual,",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl)",
"hoehe) ''' # Für Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3')",
"R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl)",
"(at your option) any later version. PyMbs is distributed in the hope that",
"License along with PyMbs. If not, see <http://www.gnu.org/licenses/>. Copyright 2011, 2012 <NAME>, <NAME>,",
"13.05.2011 @author: <NAME> Pfade für Visualisierung anpassen !!! ''' ################################# # import PyMbs",
"+ 2*pi/3-pi/9 phi_AP_5 = phi_AP_3 + 2*pi/3 phi_AP_6 = phi_AP_4 + 2*pi/3 ################",
"p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs',",
"world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5',",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3')",
"'Verbindung_6') ##################### # add visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' #",
"Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0])",
"'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz',",
"Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0])",
"# -*- coding: utf-8 -*- ''' This file is part of PyMbs. PyMbs",
"p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs',",
"# Traägheit eines Vollzylinders um x die x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12) # Traägheit",
"Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0])",
"1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### #",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"'l', 'DistanceSensor') #lz = world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50 #F_c = world.addExpression('SpringForce', 'F_c', -c*l[0])",
"p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2',",
"##################### # add visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' # Für",
"phi_BP_1 = pi/2-pi/18 phi_BP_2 = phi_BP_1 + pi/9 phi_BP_3 = phi_BP_1 + 2*pi/3",
"Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6')",
"cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### # Anordnungen # ############### phi_BP_1",
"'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') ################################# # generate equations & sim Code #",
"# Joints # ################################# #world.addJoint('fix_BP', world, BP) world.addJoint( world, Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx',",
"1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z',",
"Länge der Zylinderstangen und Gehäuse hoehe = 0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6",
"im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual,",
"been assembled\") ################################# # add Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### # add",
"PyMbs Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2",
"add Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### # add Imput & Load #",
"Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 =",
"Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz',",
"Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0])",
"BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3',",
"p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2',",
"''' # Für Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual,",
"Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 =",
"''' Created on 13.05.2011 @author: <NAME> Pfade für Visualisierung anpassen !!! ''' #################################",
"PyMbs. PyMbs is free software: you can redistribute it and/or modify it under",
"Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0])",
"on 13.05.2011 @author: <NAME> Pfade für Visualisierung anpassen !!! ''' ################################# # import",
"I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### # Anordnungen # ############### phi_BP_1 =",
"Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0])",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual',",
"and/or modify it under the terms of the GNU Lesser General Public License",
"# ################################# #world.addJoint('fix_BP', world, BP) world.addJoint( world, Ground, name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx',",
"Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0])",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_5.addFrame('Zyl_geh_5_cs', p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual',",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5')",
"'DistanceSensor_Cylinder') #c=50 #F_c = world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') ################################# # generate",
"= phi_AP_4 + 2*pi/3 ################ # Hexapod # ################ ################################# # Bodies &",
"Bodies & KS # ################################# Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP = Ground.KS_1 BP.addFrame(name='BP_visual',",
"add Imput & Load # ##################### #l = world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz =",
"um x die x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12) # Traägheit eines Vollzylinders um y",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"phi_BP_3 = phi_BP_1 + 2*pi/3 phi_BP_4 = phi_BP_2 + 2*pi/3 phi_BP_5 = phi_BP_3",
"the GNU Lesser General Public License as published by the Free Software Foundation,",
"Public License for more details. You should have received a copy of the",
"= world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody(",
"##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' # Für Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1')",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody(",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347)",
"AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für Visualisierung im",
"p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2',",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody(",
"################################# # import PyMbs & Lib. # ################################# from PyMbs.Input import * from",
"Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' #",
"phi_BP_2 + 2*pi/3 phi_BP_5 = phi_BP_3 + 2*pi/3 phi_BP_6 = phi_BP_4 + 2*pi/3",
"p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody(",
"Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x'))",
"p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0])",
"Traägheit eines Vollzylinders um y die x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2) # Traägheit eines",
"world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# # add visualisation",
"im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual,",
"warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual',",
"Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0])",
"################ # Hexapod # ################ ################################# # Bodies & KS # ################################# Ground",
"Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0])",
"set up inertial frame # ################################# world=MbsSystem([0,0,-1]) ################################# # Parameters # ################################# #",
"# ################################# from PyMbs.Input import * from PyMbs.Symbolics import Matrix,cos,sin pi = 3.1415926535897932384626433832795",
"p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2',",
"Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_4') world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5')",
"p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ '''",
"p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3",
"Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual',",
"# ################################# print(\"System has been assembled\") ################################# # add Sensors # ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\")",
"world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints or Loops # ######################## world.addLoop.Hexapod(AP.AP_Anlenkpunkt_1, Zyl_stange_1.Zyl_stange_1_cs,",
"or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License",
"#lz = world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50 #F_c = world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c,",
"Imput & Load # ##################### #l = world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz = world.addSensor.Distance(BP,AP,",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' #",
"# ################################# #world.addSensor.Position(world,AP.AP_Anlenkpunkt_1,\"P_AP_1\") #world.addSensor.Energy(AP,'E_AP') ##################### # add Imput & Load # ##################### #l",
"p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6",
"world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0],",
"jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3') world.addJoint(BP.BP_Anlenkpunkt_4,Zyl_geh_4.Zyl_geh_4_cs_2,['Rz',",
"Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x'))",
"from PyMbs.Symbolics import Matrix,cos,sin pi = 3.1415926535897932384626433832795 ################################# # set up inertial frame",
"eines Vollzylinders um x die x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12) # Traägheit eines Vollzylinders",
"# Für Visualisierung im PyMbs Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs',",
"p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x'))",
"visualisation # ##################### world.addVisualisation.Cylinder(BP.BP_visual,R_BP, hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' # Für Visualisierung im Dymola",
"PyMbs.Input import * from PyMbs.Symbolics import Matrix,cos,sin pi = 3.1415926535897932384626433832795 ################################# # set",
"Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0])",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual',",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual',",
"@author: <NAME> Pfade für Visualisierung anpassen !!! ''' ################################# # import PyMbs &",
"Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 =",
"ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A",
"# ##################### #l = world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor') #lz = world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5')",
"= world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring') ################################# # generate equations & sim",
"= 0.01 R_AP=0.3 R_BP=0.5 R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh = 0.1 m_z_st = 0.1",
"p=[0,0,0]) Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2',",
"Hexapod # ################ ################################# # Bodies & KS # ################################# Ground = world.addBody(name='Ground',mass=1)",
"software: you can redistribute it and/or modify it under the terms of the",
"0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam(",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2')",
"Visualisierung anpassen !!! ''' ################################# # import PyMbs & Lib. # ################################# from",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1')",
"phi_AP_1 + 2*pi/3 phi_AP_4 = phi_AP_3 + 2*pi/3-pi/9 phi_AP_5 = phi_AP_3 + 2*pi/3",
"I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### # Anordnungen # ############### phi_BP_1 = pi/2-pi/18 phi_BP_2 = phi_BP_1",
"p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs',",
"PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You",
"R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# # add visualisation # ################################# print(\"System has been",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1')",
"x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2) # Traägheit eines Vollzylinders um z die x-Achse ################################################",
"BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual',",
"world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für Visualisierung im",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual',",
"die x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2) # Traägheit eines Vollzylinders um z die x-Achse",
"Ground.KS_1 BP.addFrame(name='BP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) BP.addFrame(name='BP_Anlenkpunkt_1', p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0])",
"mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4')",
"Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 =",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs',",
"2*pi/3 phi_AP_1 = pi/6+pi/18 phi_AP_2 = phi_AP_1 + 2*pi/3-pi/9 phi_AP_3 = phi_AP_1 +",
"world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2') world.addVisualisation.File(Zyl_geh_3.Zyl_geh_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_3') world.addVisualisation.File(Zyl_geh_4.Zyl_geh_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_4') world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual,",
"PyMbs is free software: you can redistribute it and/or modify it under the",
"Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_5') Zyl_geh_5.addFrame('Zyl_geh_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"= world.addSensor.Distance(BP,AP, 'lz', 'DistanceSensor_Cylinder') #c=50 #F_c = world.addExpression('SpringForce', 'F_c', -c*l[0]) #world.addLoad.PtPForce(AP,BP.BP_Feder, F_c, name='Spring')",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_4') Zyl_stange_4.addFrame('Zyl_stange_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_4.addFrame('Zyl_stange_4_cs', p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"copy of the GNU Lesser General Public License along with PyMbs. If not,",
"of PyMbs. PyMbs is free software: you can redistribute it and/or modify it",
"x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam(",
"in the hope that it will be useful, but WITHOUT ANY WARRANTY; without",
"x-Achse I2y=world.addParam( 'I2y', (m2*H2**2)/12) # Traägheit eines Vollzylinders um y die x-Achse I2z=world.addParam(",
"R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_3.Zyl_stange_3_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl)",
"world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints or Loops # ########################",
"details. You should have received a copy of the GNU Lesser General Public",
"Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0])",
"# ############### phi_BP_1 = pi/2-pi/18 phi_BP_2 = phi_BP_1 + pi/9 phi_BP_3 = phi_BP_1",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 =",
"pi/9 phi_BP_3 = phi_BP_1 + 2*pi/3 phi_BP_4 = phi_BP_2 + 2*pi/3 phi_BP_5 =",
"''' #Für Visualisierung im Dymola Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs',",
"p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für Visualisierung im Dymola Zyl_geh_1 =",
"= world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0])",
"Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual',",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody(",
"eines Vollzylinders um y die x-Achse I2z=world.addParam( 'I2z', (m2*R2**2)/2) # Traägheit eines Vollzylinders",
"-*- coding: utf-8 -*- ''' This file is part of PyMbs. PyMbs is",
"it and/or modify it under the terms of the GNU Lesser General Public",
"inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_1.addFrame('Zyl_geh_1_cs', p=[0,0,0]) Zyl_geh_1.addFrame('Zyl_geh_1_cs_2', p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual',",
"Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl)",
"3.1415926535897932384626433832795 ################################# # set up inertial frame # ################################# world=MbsSystem([0,0,-1]) ################################# # Parameters",
"Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1",
"+ 2*pi/3 phi_BP_6 = phi_BP_4 + 2*pi/3 phi_AP_1 = pi/6+pi/18 phi_AP_2 = phi_AP_1",
"mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0])",
"# add visualisation # ################################# print(\"System has been assembled\") ################################# # add Sensors",
"version 3 of the License, or (at your option) any later version. PyMbs",
"PyMbs & Lib. # ################################# from PyMbs.Input import * from PyMbs.Symbolics import Matrix,cos,sin",
"phi_BP_3 + 2*pi/3 phi_BP_6 = phi_BP_4 + 2*pi/3 phi_AP_1 = pi/6+pi/18 phi_AP_2 =",
"2*pi/3 phi_BP_4 = phi_BP_2 + 2*pi/3 phi_BP_5 = phi_BP_3 + 2*pi/3 phi_BP_6 =",
"################ ################################# # Bodies & KS # ################################# Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0]) BP",
"Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs',",
"Pfade für Visualisierung anpassen !!! ''' ################################# # import PyMbs & Lib. #",
"R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12) # Traägheit eines",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ################################# # Joints # ################################# #world.addJoint('fix_BP', world, BP)",
"Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### # add visualisation #",
"################################################################################ ''' #Für Visualisierung im Dymola Zyl_geh_1 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_1') Zyl_geh_1.addFrame('Zyl_geh_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"as published by the Free Software Foundation, either version 3 of the License,",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0]) Zyl_geh_5 = world.addBody(",
"c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1', R_BP) m2=world.addParam('m2', 50) R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x',",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs', p=[0,0,0]) Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs',",
"AP = world.addBody(name='Arbeitsplattform', mass=m2,inertia=diag([I2x,I2y,I2z])) AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4',",
"R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_4.Zyl_stange_4_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_5.Zyl_stange_5_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_6.Zyl_stange_6_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Frame(AP,0.4) #world.addVisualisation.Frame(BP.BP_Feder,1) world.addVisualisation.Frame(Ground,0.6) ################################# # add",
"world.addLoop.Hexapod(AP.AP_Anlenkpunkt_4, Zyl_stange_4.Zyl_stange_4_cs, 'Verbindung_4') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_5, Zyl_stange_5.Zyl_stange_5_cs, 'Verbindung_5') world.addLoop.Hexapod(AP.AP_Anlenkpunkt_6, Zyl_stange_6.Zyl_stange_6_cs, 'Verbindung_6') ##################### # add visualisation",
"AP.addFrame(name='AP_visual', p=[0,0,0],R=rotMat(pi/2,'x')) AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6',",
"p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3",
"2*pi/3 phi_AP_4 = phi_AP_3 + 2*pi/3-pi/9 phi_AP_5 = phi_AP_3 + 2*pi/3 phi_AP_6 =",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs', p=[0,0,0]) Zyl_stange_2.addFrame('Zyl_stange_2_cs_2', p=[0,0,0]) Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual',",
"# ################ ################################# # Bodies & KS # ################################# Ground = world.addBody(name='Ground',mass=1) Ground.addFrame(name='KS_1',p=[0,0,0])",
"anpassen !!! ''' ################################# # import PyMbs & Lib. # ################################# from PyMbs.Input",
"3 of the License, or (at your option) any later version. PyMbs is",
"z die x-Achse ################################################ m_Zyl_Geh=world.addParam('m_Zyl_Geh', 18.6) l_Zyl_Geh=world.addParam('l_Zyl_Geh',0.74) cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y',",
"p=[0,0,0]) Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3",
"inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual',",
"cg_Zyl_Geh_x=world.addParam('cg_Zyl_Geh_x',0.353) I_Zyl_Geh_x=world.addParam( 'I_Zyl_Geh_x', 0.027) I_Zyl_Geh_y=world.addParam( 'I_Zyl_Geh_y', 1.061) I_Zyl_Geh_z=world.addParam( 'I_Zyl_Geh_z', 1.061) m_Zyl_Stange=world.addParam('m_Zyl_Stange', 8.4) l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66)",
"hope that it will be useful, but WITHOUT ANY WARRANTY; without even the",
"#world.addSensor.Energy(AP,'E_AP') ##################### # add Imput & Load # ##################### #l = world.addSensor.Distance(AP,BP.BP_Feder, 'l',",
"p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_2') Zyl_stange_2.addFrame('Zyl_stange_2_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_2.addFrame('Zyl_stange_2_cs',",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) ''' # Für Visualisierung",
"AP.addFrame(name='AP_Anlenkpunkt_1', p=[R2*cos(phi_AP_1),R2*sin(phi_AP_1),0]) AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################",
"= phi_BP_1 + pi/9 phi_BP_3 = phi_BP_1 + 2*pi/3 phi_BP_4 = phi_BP_2 +",
"world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_5') world.addVisualisation.File(Zyl_stange_6.Zyl_stange_6_visual,",
"mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3')",
"p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_6.addFrame('Zyl_stange_6_cs', p=[0,0,0]) Zyl_stange_6.addFrame('Zyl_stange_6_cs_2', p=[0,0,0]) #################################",
"+ 2*pi/3 phi_AP_4 = phi_AP_3 + 2*pi/3-pi/9 phi_AP_5 = phi_AP_3 + 2*pi/3 phi_AP_6",
"hoehe) world.addVisualisation.Cylinder(AP.AP_visual,R_AP, hoehe) ''' # Für Visualisierung im Dymola world.addVisualisation.File(Zyl_geh_1.Zyl_geh_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_1') world.addVisualisation.File(Zyl_geh_2.Zyl_geh_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_2')",
"Copyright 2011, 2012 <NAME>, <NAME>, <NAME>, <NAME> ''' ''' Created on 13.05.2011 @author:",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"part of PyMbs. PyMbs is free software: you can redistribute it and/or modify",
"This file is part of PyMbs. PyMbs is free software: you can redistribute",
"option) any later version. PyMbs is distributed in the hope that it will",
"p=[0,0,0]) Zyl_stange_4.addFrame('Zyl_stange_4_cs_2', p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2',",
"the License, or (at your option) any later version. PyMbs is distributed in",
"phi_AP_2 = phi_AP_1 + 2*pi/3-pi/9 phi_AP_3 = phi_AP_1 + 2*pi/3 phi_AP_4 = phi_AP_3",
"l_Zyl_Stange=world.addParam('l_Zyl_Stange',0.66) cg_Zyl_Stange_x=world.addParam('cg_Zyl_Stange_x',-0.347) I_Zyl_Stange_x=world.addParam('I_Zyl_Stange_x', 0.003) I_Zyl_Stange_y=world.addParam('I_Zyl_Stange_y', 0.433) I_Zyl_Stange_z=world.addParam('I_Zyl_Stange_z', 0.432) ############### # Anordnungen # ###############",
"Zyl_geh_2 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 =",
"Zyl_geh_3.addFrame('Zyl_geh_3_cs_2', p=[0,0,0]) Zyl_geh_4 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_4') Zyl_geh_4.addFrame('Zyl_geh_4_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_4.addFrame('Zyl_geh_4_cs', p=[0,0,0]) Zyl_geh_4.addFrame('Zyl_geh_4_cs_2', p=[0,0,0])",
"Zyl_geh_5.addFrame('Zyl_geh_5_cs_2', p=[0,0,0]) Zyl_geh_6 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_6') Zyl_geh_6.addFrame('Zyl_geh_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_6.addFrame('Zyl_geh_6_cs', p=[0,0,0]) Zyl_geh_6.addFrame('Zyl_geh_6_cs_2', p=[0,0,0])",
"R2=world.addParam('R2', R_AP) H2=world.addParam('H2',hoehe) I2x=world.addParam( 'I2x', (m2*H2**2)/12) # Traägheit eines Vollzylinders um x die",
"world.addJoint(BP.BP_Anlenkpunkt_5,Zyl_geh_5.Zyl_geh_5_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_5') world.addJoint(BP.BP_Anlenkpunkt_6,Zyl_geh_6.Zyl_geh_6_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_6') world.addJoint(Zyl_geh_1.Zyl_geh_1_cs,Zyl_stange_1.Zyl_stange_1_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_1') world.addJoint(Zyl_geh_2.Zyl_geh_2_cs,Zyl_stange_2.Zyl_stange_2_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_2') world.addJoint(Zyl_geh_3.Zyl_geh_3_cs,Zyl_stange_3.Zyl_stange_3_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_3') world.addJoint(Zyl_geh_4.Zyl_geh_4_cs,Zyl_stange_4.Zyl_stange_4_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_4') world.addJoint(Zyl_geh_5.Zyl_geh_5_cs,Zyl_stange_5.Zyl_stange_5_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_5') world.addJoint(Zyl_geh_6.Zyl_geh_6_cs,Zyl_stange_6.Zyl_stange_6_cs_2,'Tz',0,name='Zyl_stange_1_an_Zyl_geh_6') ######################## # Constraints",
"useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or",
"either version 3 of the License, or (at your option) any later version.",
"Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_6') Zyl_stange_6.addFrame('Zyl_stange_6_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x'))",
"visualisation # ################################# print(\"System has been assembled\") ################################# # add Sensors # #################################",
"+ 2*pi/3 phi_BP_5 = phi_BP_3 + 2*pi/3 phi_BP_6 = phi_BP_4 + 2*pi/3 phi_AP_1",
"modify it under the terms of the GNU Lesser General Public License as",
"p=[0,0,0]) ################################################################################ Zyl_stange_1 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0])",
"GNU Lesser General Public License as published by the Free Software Foundation, either",
"p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_3') Zyl_geh_3.addFrame('Zyl_geh_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_geh_3.addFrame('Zyl_geh_3_cs',",
"is distributed in the hope that it will be useful, but WITHOUT ANY",
"##################### # add Imput & Load # ##################### #l = world.addSensor.Distance(AP,BP.BP_Feder, 'l', 'DistanceSensor')",
"'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_6') ''' # Für Visualisierung im Dymola world.addVisualisation.Cylinder(Zyl_geh_1.Zyl_geh_1_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl)",
"with PyMbs. If not, see <http://www.gnu.org/licenses/>. Copyright 2011, 2012 <NAME>, <NAME>, <NAME>, <NAME>",
"Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6 =",
"AP.addFrame(name='AP_Anlenkpunkt_2', p=[R2*cos(phi_AP_2),R2*sin(phi_AP_2),0]) AP.addFrame(name='AP_Anlenkpunkt_3', p=[R2*cos(phi_AP_3),R2*sin(phi_AP_3),0]) AP.addFrame(name='AP_Anlenkpunkt_4', p=[R2*cos(phi_AP_4),R2*sin(phi_AP_4),0]) AP.addFrame(name='AP_Anlenkpunkt_5', p=[R2*cos(phi_AP_5),R2*sin(phi_AP_5),0]) AP.addFrame(name='AP_Anlenkpunkt_6', p=[R2*cos(phi_AP_6),R2*sin(phi_AP_6),0]) ################################################################################ ''' #Für",
"R_Zyl_stange=0.02 R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh = 0.1 m_z_st = 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0)",
"= phi_BP_2 + 2*pi/3 phi_BP_5 = phi_BP_3 + 2*pi/3 phi_BP_6 = phi_BP_4 +",
"world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_1') Zyl_stange_1.addFrame('Zyl_stange_1_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_1.addFrame('Zyl_stange_1_cs', p=[0,0,0]) Zyl_stange_1.addFrame('Zyl_stange_1_cs_2', p=[0,0,0]) Zyl_stange_2 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0],",
"name='fix_BP') jAP=world.addJoint(world, AP,['Tx', 'Ty', 'Tz','Rx', 'Ry', 'Rz'],[0,0,1,0,0,0],name='free_AP') world.addJoint(BP.BP_Anlenkpunkt_1,Zyl_geh_1.Zyl_geh_1_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_1') world.addJoint(BP.BP_Anlenkpunkt_2,Zyl_geh_2.Zyl_geh_2_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_2') world.addJoint(BP.BP_Anlenkpunkt_3,Zyl_geh_3.Zyl_geh_3_cs_2,['Rz', 'Ry'],[0,0],name='Zyl_geh_1_an_BP_3')",
"p=[R1*cos(phi_BP_1),R1*sin(phi_BP_1),0]) BP.addFrame(name='BP_Anlenkpunkt_2', p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################",
"see <http://www.gnu.org/licenses/>. Copyright 2011, 2012 <NAME>, <NAME>, <NAME>, <NAME> ''' ''' Created on",
"world.addVisualisation.Cylinder(Zyl_geh_2.Zyl_geh_2_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_3.Zyl_geh_3_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_4.Zyl_geh_4_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_5.Zyl_geh_5_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_geh_6.Zyl_geh_6_visual, R_Zyl_geh,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_1.Zyl_stange_1_visual, R_Zyl_stange,l_zyl) world.addVisualisation.Cylinder(Zyl_stange_2.Zyl_stange_2_visual,",
"pi = 3.1415926535897932384626433832795 ################################# # set up inertial frame # ################################# world=MbsSystem([0,0,-1]) #################################",
"Zyl_stange_3 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_3') Zyl_stange_3.addFrame('Zyl_stange_3_visual', p=[0,0,0],R=rotMat(pi/2,'y')*rotMat(pi/2,'x')) Zyl_stange_3.addFrame('Zyl_stange_3_cs', p=[0,0,0]) Zyl_stange_3.addFrame('Zyl_stange_3_cs_2', p=[0,0,0]) Zyl_stange_4 =",
"R_Zyl_geh=0.04 l_zyl=0.6 m_z_geh = 0.1 m_z_st = 0.1 c=world.addParam('c',10) c1=world.addParam('c1',5) m1=world.addParam('m1', 1.0) R1=world.addParam('R1',",
"world.addVisualisation.File(Zyl_geh_5.Zyl_geh_5_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_5') world.addVisualisation.File(Zyl_geh_6.Zyl_geh_6_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_geh_001.stl',1,name='Zylinder_geh_6') world.addVisualisation.File(Zyl_stange_1.Zyl_stange_1_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_1') world.addVisualisation.File(Zyl_stange_2.Zyl_stange_2_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_2') world.addVisualisation.File(Zyl_stange_3.Zyl_stange_3_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_3') world.addVisualisation.File(Zyl_stange_4.Zyl_stange_4_visual, 'C:\\\\Users\\JeSche\\Desktop\\Diplom_Arbeit\\Hexapod/zyl_stange_001.stl',1,name='Zylinder_stange_4') world.addVisualisation.File(Zyl_stange_5.Zyl_stange_5_visual,",
"p=[0,0,0]) Zyl_stange_5 = world.addBody( mass=m_Zyl_Stange,cg=[cg_Zyl_Stange_x,0,0], inertia=diag([I_Zyl_Stange_x,I_Zyl_Stange_y,I_Zyl_Stange_z]),name='Zyl_stange_5') Zyl_stange_5.addFrame('Zyl_stange_5_visual', p=[0,0,-l_zyl/2],R=rotMat(pi/2,'x')) Zyl_stange_5.addFrame('Zyl_stange_5_cs', p=[0,0,0]) Zyl_stange_5.addFrame('Zyl_stange_5_cs_2', p=[0,0,0]) Zyl_stange_6",
"################################# from PyMbs.Input import * from PyMbs.Symbolics import Matrix,cos,sin pi = 3.1415926535897932384626433832795 #################################",
"phi_AP_6 = phi_AP_4 + 2*pi/3 ################ # Hexapod # ################ ################################# # Bodies",
"= world.addBody( mass=m_Zyl_Geh,cg=[cg_Zyl_Geh_x,0,0], inertia=diag([I_Zyl_Geh_x,I_Zyl_Geh_y,I_Zyl_Geh_z]),name='Zyl_geh_2') Zyl_geh_2.addFrame('Zyl_geh_2_visual', p=[0,0,l_zyl/2],R=rotMat(pi/2,'x')) Zyl_geh_2.addFrame('Zyl_geh_2_cs', p=[0,0,0]) Zyl_geh_2.addFrame('Zyl_geh_2_cs_2', p=[0,0,0]) Zyl_geh_3 = world.addBody(",
"p=[R1*cos(phi_BP_2),R1*sin(phi_BP_2),0]) BP.addFrame(name='BP_Anlenkpunkt_3', p=[R1*cos(phi_BP_3),R1*sin(phi_BP_3),0]) BP.addFrame(name='BP_Anlenkpunkt_4', p=[R1*cos(phi_BP_4),R1*sin(phi_BP_4),0]) BP.addFrame(name='BP_Anlenkpunkt_5', p=[R1*cos(phi_BP_5),R1*sin(phi_BP_5),0]) BP.addFrame(name='BP_Anlenkpunkt_6', p=[R1*cos(phi_BP_6),R1*sin(phi_BP_6),0]) BP.addFrame(name='BP_Feder',p=[0,0,1.1]) ################################################################################ AP =",
"phi_BP_6 = phi_BP_4 + 2*pi/3 phi_AP_1 = pi/6+pi/18 phi_AP_2 = phi_AP_1 + 2*pi/3-pi/9",
"= 3.1415926535897932384626433832795 ################################# # set up inertial frame # ################################# world=MbsSystem([0,0,-1]) ################################# #"
] |
[
"this world wr = width/3.0 # wr width of reward area wwalls =",
"/ Sorbonne Université 02/2018 This file allows to build worlds TODO : replace",
"square world \"\"\" ## first build default world texture_paths, world_info = _build_square_default_world(model, texture,",
"if distractors: # add visual distractors on the groud and inner faces of",
"(0, 2)) STONE = round_bot_model.Block.tex_coords((2, 1), (2, 1), (2, 1)) STONE2 = round_bot_model.Block.tex_coords((1,",
"import os def _texture_path(texture_bricks_name): \"\"\" Parameter --------- texture_bricks_name : str name of the",
"file allows to build worlds TODO : replace this file by a .json",
"0.0), texture=STONE2, block_type='brick', collision_reward = wall_reward) #left wall left_wall_block = model.add_block( (-nd, hwalls/2,",
"(string) paths for texture image of bricks, robot and visualisation - wall_reward :",
"build_square_world(model, texture, robot_diameter=2 ,width=45, depth=45, hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False,",
"trigger a change in the environment (change to be defined) Returns ------- world",
"back_wall_block = model.add_block( (0, hwalls/2, -nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=BRICK,",
"width # get texture paths in current directory brick_texture_path = os.path.dirname(__file__) + texture_bricks",
"components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox =",
"of the texture for the bricks - width : (int) width of the",
"components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox =",
"0), (1, 0), (1, 0)) model.add_block( (0, 0.3, 0, nw/3, 0.2, nw/3, 0.0,",
"- texture_bricks, texture_robot, texture_visualisation : (string) paths for texture image of bricks, robot",
"goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds the square world \"\"\" ##",
"linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor',",
"(0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0, 0.0, 0.0), texture=START, block_type='start') return texture_paths,",
"round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) n = width/2.0 # 1/2 width and",
"round_bot_model.Block.tex_coords((0, 2), (0, 2), (0, 2)) STONE = round_bot_model.Block.tex_coords((2, 1), (2, 1), (2,",
"0)) model.add_block( (0, 0.3, 0, nw/3, 0.2, nw/3, 0.0, 0.0, 0.0), BUTTON, block_type='trigger_button')",
"0.0), texture=START, block_type='start') return texture_paths, world_info def build_square_1wall_world(model, texture, robot_diameter=2, width=45, depth=45, hwalls=2,",
"1), (1, 1)) n = width/2.0 # 1/2 width and depth of world",
"elif texture_bricks_name == 'colours': return '/textures/texture_colours.png' else : raise ValueError('Unknown texture name '+",
"0), (1, 0)) model.add_block( (0, 0.3, 0, nw/3, 0.2, nw/3, 0.0, 0.0, 0.0),",
"doesn't work for the moment from gym_round_bot.envs import round_bot_model # create textures coordinates",
"Build gound block ground_block = model.add_block( (0, -3, 0, 2*nd, 6, 2*nw, 0.0,",
"wwalls = width # get texture paths in current directory brick_texture_path = os.path.dirname(__file__)",
"texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor,",
"depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ## then add specs from",
"hwalls, wwalls, 0.0, 0.0, 0.0), texture=BRICK2, block_type='brick', collision_reward = wall_reward) if distractors: #",
"0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) # wall",
"corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward',",
"= wall_reward) #left wall left_wall_block = model.add_block( (-nd, hwalls/2, 0, dwalls, hwalls, wwalls,",
"# distractor left_wall inner face block left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0), (0.0,",
"nw/2, 0.0, 0.0, 0.0), SAND, block_type='sandbox') if trigger_button : # add a trigger",
"2)) BUTTON = round_bot_model.Block.tex_coords((2, 2), (2, 2), (2, 2)) DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t)",
"= wall_reward) if distractors: # add visual distractors on the groud and inner",
"round_bot_model.Block.tex_coords((2, 1), (2, 1), (2, 1)) STONE2 = round_bot_model.Block.tex_coords((1, 2), (1, 2), (1,",
"1 wall in the middle \"\"\" ## first build default world texture_paths, world_info",
"in - texture_bricks_name : (str) name of the texture for the bricks -",
"add starting areas (the height=0 of block does not matter here, only area",
"robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # middle wall model.add_block( (n/2,",
"without \"from\" but doesn't work for the moment from gym_round_bot.envs import round_bot_model #",
"texture_paths, world_info = _build_square_default_world(model, texture, width=width, depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes,",
"wall_reward) if distractors: # add visual distractors on the groud and inner faces",
"of this world nd = depth/2.0 # 1/2 depth of this world wwalls",
"WARNING : don't fo (from round_bot_py import round_bot_model) here to avoid mutual imports",
"change in the environment (change to be defined) Returns ------- world information \"\"\"",
"# wall distractors : width_wall_distractors = wwalls/2 height_wall_distractors = hwalls*2/3 # distractor back_wall",
"\"\"\" Builds a simple rectangle planar world with walls around Parameters ---------- -",
"robot_texture_path = os.path.dirname(__file__) + texture_robot visualisation_texture_path = os.path.dirname(__file__) + texture_visualisation distractors_texture_path = os.path.dirname(__file__)",
"(0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0,",
"inner face block right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0,",
"to avoid mutual imports ! import os def _texture_path(texture_bricks_name): \"\"\" Parameter --------- texture_bricks_name",
"SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) n = width/2.0 # 1/2",
"world texture_paths, world_info = _build_square_default_world(model, texture, width=width, depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed,",
"0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed)",
"0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[2],",
"of this world nd = depth/2.0 # 1/2 depth of this world wr",
"} # Build gound block ground_block = model.add_block( (0, -3, 0, 2*nd, 6,",
"dwalls, 0.0, 0.0, 0.0), texture=STONE2, block_type='brick', collision_reward = wall_reward) #left wall left_wall_block =",
"(1, 1), (1, 1)) n = width/2.0 # 1/2 width and depth of",
"button that will trigger a change in the environment (change to be defined)",
"(1, 2)) BUTTON = round_bot_model.Block.tex_coords((2, 2), (2, 2), (2, 2)) DISTRACTORS = [",
"this world nd = depth/2.0 # 1/2 depth of this world wr =",
": raised if texture_bricks_name is unkwnonw \"\"\" if texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png'",
"#front wall back_wall_block = model.add_block( (0, hwalls/2, -nw, depth, hwalls, dwalls, 0.0, 0.0,",
"width of reward area wwalls = width # get texture paths in current",
"the bricks - width : (int) width of the world - depth :",
"0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) nw = width/2.0 #",
"block does not matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4,",
"replace this file by a .json loader and code worlds in .json \"\"\"",
"'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name == 'colours': return '/textures/texture_colours.png' else : raise ValueError('Unknown",
"distractors_texture_path = os.path.dirname(__file__) + texture_distractors texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } #",
"# add a trigger button that will trigger a change in the world",
"walls - texture_bricks, texture_robot, texture_visualisation : (string) paths for texture image of bricks,",
"wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0,",
"sandboxes=sandboxes, trigger_button=trigger_button,) ## then add specs from gym_round_bot.envs import round_bot_model BOT = round_bot_model.Block.tex_coords((0,",
"area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0, 0.0, 0.0),",
"raised if texture_bricks_name is unkwnonw \"\"\" if texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png' elif",
"round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) BRICK = round_bot_model.Block.tex_coords((2, 0), (2, 0), (2,",
"components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox =",
"raise ValueError('Unknown texture name '+ texture_bricks_name + ' in loading world') def _build_square_default_world(model,",
"distractor back_wall inner face block back_wall_bb = round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors,",
"world when crossed ON / OFF #TRIGGER = round_bot_model.Block.tex_coords((1, 0), (1, 0), (1,",
"+ ' in loading world') def _build_square_default_world(model, texture_bricks_name, width=45, depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png',",
"width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox = left_wall_bb, speed=distractors_speed) # distractor right_wall",
"the texture_bricks_name Raises ------ ValueError : raised if texture_bricks_name is unkwnonw \"\"\" if",
"texture name '+ texture_bricks_name + ' in loading world') def _build_square_default_world(model, texture_bricks_name, width=45,",
"# -*- coding: utf-8 -*- \"\"\" <NAME> ISIR - CNRS / Sorbonne Université",
"#left wall left_wall_block = model.add_block( (-nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0,",
"add specs from gym_round_bot.envs import round_bot_model BOT = round_bot_model.Block.tex_coords((0, 0), (0, 1), (0,",
"speed=distractors_speed) if sandboxes : # add sandboxes ont the ground if asked (slowing",
"0.0), texture=REWARD, block_type='reward', collision_reward = 1, visible_reward=visible_reward) # Build robot block, set initial",
"for the bricks - width : (int) width of the world - depth",
"(0, 0.3, 0, nd/2, 0, nw/2, 0.0, 0.0, 0.0), SAND, block_type='sandbox') if trigger_button",
"2)) DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t) for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw = width/2.0",
"add a trigger button that will trigger a change in the environment (change",
"(1, 2), (1, 2)) BUTTON = round_bot_model.Block.tex_coords((2, 2), (2, 2), (2, 2)) DISTRACTORS",
"model.add_block( (nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=BRICK2, block_type='brick', collision_reward",
"block_type='brick', collision_reward = -1) # Build reward block in the corner model.add_block( (n-(wr/2+dwalls/2),",
"trigger_button (Bool) : add a trigger button that will trigger a change in",
"wall_reward : (float) reward for wall collision - distractors (Bool) : add visual",
"model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox",
"Return ------ texture_path: (str) path corresponding to the texture_bricks_name Raises ------ ValueError :",
"texture_bricks_name : str name of the world main texture Return ------ texture_path: (str)",
"{'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } # Build gound block ground_block = model.add_block( (0,",
"2*nd, 6, 2*nw, 0.0, 0.0, 0.0), GRASS, block_type='brick') # Build wall blocks with",
"(-nd+dwalls/2+0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0,",
"front_wall inner face block front_wall_bb = round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0),",
"texture=REWARD, block_type='reward', collision_reward = goal_reward, visible=visible_reward) # Build robot block, set initial height",
"hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=BRICK2, block_type='brick', collision_reward = wall_reward)",
"nd/2, 0, nw/2, 0.0, 0.0, 0.0), SAND, block_type='sandbox') if trigger_button : # add",
"block_type='brick', collision_reward = wall_reward) #right wall right_wall_block = model.add_block( (nd, hwalls/2, 0, dwalls,",
"distractors: # add visual distractors on the groud and inner faces of walls",
"if texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png' elif",
"size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) model.add_block( components=(0, 0,",
"0.0, 0.0), SAND, block_type='sandbox') if trigger_button : # add a trigger button that",
"(float) reward for wall collision - distractors (Bool) : add visual distractors on",
"0.0), BUTTON, block_type='trigger_button') world_info = { 'width' : 2*nw, 'depth' : 2*nd, }",
"0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox = back_wall_bb,",
"BRICK2 = round_bot_model.Block.tex_coords((0, 2), (0, 2), (0, 2)) STONE = round_bot_model.Block.tex_coords((2, 1), (2,",
"0.1, 0), (2*n, 0, 2*n), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0,",
"'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name == 'colours':",
"DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t) for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw = width/2.0 #",
"import would be global and without \"from\" but doesn't work for the moment",
"initial height to bot_heigh/2 + small offset to avoid ground collision model.add_block( (0,",
"build_square_1wall_world(model, texture, robot_diameter=2, width=45, depth=45, hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False,",
"texture=BOT, block_type='robot') # add starting areas (the height=0 of block does not matter",
"texture_robot, texture_visualisation : (string) paths for texture image of bricks, robot and visualisation",
"(float) : speed of visual distractors displacement - sandboxes (Bool) : add sandboxes",
"round_bot_model.Block.tex_coords((1, 0), (1, 0), (1, 0)) model.add_block( (0, 0.3, 0, nw/3, 0.2, nw/3,",
"defined) Returns ------- world information \"\"\" texture_bricks = _texture_path(texture_bricks_name) # TODO : better",
"round_bot_model.Block.tex_coords((1, 2), (1, 2), (1, 2)) BUTTON = round_bot_model.Block.tex_coords((2, 2), (2, 2), (2,",
"right_wall_block = model.add_block( (nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=BRICK2,",
"-*- \"\"\" <NAME> ISIR - CNRS / Sorbonne Université 02/2018 This file allows",
"name of the texture for the bricks - width : (int) width of",
"main texture Return ------ texture_path: (str) path corresponding to the texture_bricks_name Raises ------",
": better import would be global and without \"from\" but doesn't work for",
"0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = 1, visible_reward=visible_reward) # Build robot block, set",
"the corner rew = model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0,",
"round_bot_model.Block.tex_coords((0, 0), (0, 1), (0, 1)) START = round_bot_model.Block.tex_coords((0, 0), (0, 0), (0,",
"= width # get texture paths in current directory brick_texture_path = os.path.dirname(__file__) +",
"not matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1,",
"1/2 width and depth of world wwalls = 2*n # width of walls",
"2*bot_radius, 0.0, 0.0, 0.0), texture=BOT, block_type='robot') # add starting areas (the height=0 of",
"0.0, 0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox = front_wall_bb, speed=distractors_speed) # distractor left_wall inner",
"' in loading world') def _build_square_default_world(model, texture_bricks_name, width=45, depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png',",
"# get texture paths in current directory brick_texture_path = os.path.dirname(__file__) + texture_bricks robot_texture_path",
"inner face block back_wall_bb = round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0), (0.0,",
"if trigger_button : # add a trigger button that will trigger a change",
"set initial height to bot_heigh/2 + small offset to avoid ground collision model.add_block(",
"# Build reward block in the corner rew = model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2),",
": add visual distractors on walls and ground - distractors_speed (float) : speed",
"coordinates GRASS = round_bot_model.Block.tex_coords((1, 0), (0, 1), (0, 0)) SAND = round_bot_model.Block.tex_coords((1, 1),",
"components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox =",
"distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ## then add specs from gym_round_bot.envs import round_bot_model BOT =",
"area # set robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # middle",
"depth of world wwalls = 2*n # width of walls wr = width/4.0",
"# Build reward block in the corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0,",
"hwalls, dwalls, 0.0, 0.0, 0.0), texture=STONE2, block_type='brick', collision_reward = wall_reward) #left wall left_wall_block",
"# 1/2 width of this world nd = depth/2.0 # 1/2 depth of",
"the robot when crossed) - trigger_button (Bool) : add a trigger button that",
"bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = 1,",
"0.0), SAND, block_type='brick', collision_reward = -1) # Build reward block in the corner",
"0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox = back_wall_bb, speed=distractors_speed) # distractor front_wall inner face block",
"texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox = left_wall_bb, speed=distractors_speed) # distractor right_wall inner face block right_wall_bb",
"= depth/2.0 # 1/2 depth of this world wr = width/3.0 # wr",
"nw/3, 0.2, nw/3, 0.0, 0.0, 0.0), BUTTON, block_type='trigger_button') world_info = { 'width' :",
"wr width of reward area # set robot specifications bot_radius = robot_diameter/2.0 bot_height",
"elif texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name == 'colours': return '/textures/texture_colours.png' else",
"(1, 0)) model.add_block( (0, 0.3, 0, nw/3, 0.2, nw/3, 0.0, 0.0, 0.0), BUTTON,",
"bot_radius = robot_diameter/2.0 bot_height = bot_radius # Build reward block in the corner",
"ON / OFF #TRIGGER = round_bot_model.Block.tex_coords((1, 0), (1, 0), (1, 0)) model.add_block( (0,",
"block, set initial height to bot_heigh/2 + small offset to avoid ground collision",
"only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0, 0.0,",
"world with walls around, and 1 wall in the middle \"\"\" ## first",
"distractors displacement - sandboxes (Bool) : add sandboxes ont the ground (slowing down",
"(0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') model.add_block( (",
"path corresponding to the texture_bricks_name Raises ------ ValueError : raised if texture_bricks_name is",
"of block does not matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1,",
"# add visual distractors on the groud and inner faces of walls if",
"wwalls/2 height_wall_distractors = hwalls*2/3 # distractor back_wall inner face block back_wall_bb = round_bot_model.BoundingBoxBlock(",
"= os.path.dirname(__file__) + texture_bricks robot_texture_path = os.path.dirname(__file__) + texture_robot visualisation_texture_path = os.path.dirname(__file__) +",
"height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0,",
"[ round_bot_model.Block.tex_coords(t,t,t) for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw = width/2.0 # 1/2 width",
"1), (0, 1)) nw = width/2.0 # 1/2 width of this world nd",
"visible_reward=visible_reward) # Build robot block, set initial height to bot_heigh/2 + small offset",
"this world nd = depth/2.0 # 1/2 depth of this world wwalls =",
"texture, robot_diameter=2 ,width=45, depth=45, hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False):",
"brick_texture_path = os.path.dirname(__file__) + texture_bricks robot_texture_path = os.path.dirname(__file__) + texture_robot visualisation_texture_path = os.path.dirname(__file__)",
"CNRS / Sorbonne Université 02/2018 This file allows to build worlds TODO :",
"world - depth : (int) depth of the world - hwalls : (int)",
"the groud and inner faces of walls if asked # distractor ground block",
"trigger button that will trigger a change in the environment (change to be",
"width # width of walls wr = width/4.0 # wr width of reward",
"texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, ): \"\"\" Builds a simple rectangle",
"= 2*n # width of walls wr = width/4.0 # wr width of",
"width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox = back_wall_bb, speed=distractors_speed) #",
"(n/2, hwalls/2, -n/4, wwalls/2, hwalls, dwalls, 0.0, 0.0, 0.0), SAND, block_type='brick', collision_reward =",
"distractor ground block size_ground_distractor = n = min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock( (0, 0.1,",
"texture image of bricks, robot and visualisation - wall_reward : (float) reward for",
"in the corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0),",
"0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox = left_wall_bb, speed=distractors_speed) #",
"reward for wall collision - distractors (Bool) : add visual distractors on walls",
"a trigger button that will trigger a change in the environment (change to",
"wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4,",
"'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } # Build gound block ground_block = model.add_block( (0, -3, 0,",
"\"\"\" Parameter --------- texture_bricks_name : str name of the world main texture Return",
"0.0, 0.0, 0.0), texture=BRICK, block_type='brick', collision_reward = wall_reward) #back wall front_wall_block = model.add_block(",
"that will trigger a change in the world when crossed ON / OFF",
"0.0), texture=START, block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0,",
"0.0, 0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox = back_wall_bb, speed=distractors_speed) # distractor front_wall inner",
": 2*nd, } return texture_paths, world_info def build_square_world(model, texture, robot_diameter=2 ,width=45, depth=45, hwalls=4,",
"matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2,",
"trigger button that will trigger a change in the world when crossed ON",
"wall collision - distractors (Bool) : add visual distractors on walls and ground",
"block_type='brick', collision_reward = wall_reward) #left wall left_wall_block = model.add_block( (-nd, hwalls/2, 0, dwalls,",
"visual distractors on the groud and inner faces of walls if asked #",
"model.add_block( (0, -3, 0, 2*nd, 6, 2*nw, 0.0, 0.0, 0.0), GRASS, block_type='brick') #",
"\"\"\" ## first build default world texture_paths, world_info = _build_square_default_world(model, texture, width=width, depth=depth,",
"= robot_diameter/2.0 bot_height = bot_radius # middle wall model.add_block( (n/2, hwalls/2, -n/4, wwalls/2,",
"# width of walls wr = width/4.0 # wr width of reward area",
"ground - distractors_speed (float) : speed of visual distractors displacement - sandboxes (Bool)",
"1), (2, 1), (2, 1)) STONE2 = round_bot_model.Block.tex_coords((1, 2), (1, 2), (1, 2))",
"(Bool) : add sandboxes ont the ground (slowing down the robot when crossed)",
"front_wall_block = model.add_block( (0, hwalls/2, nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=STONE2,",
"wall model.add_block( (n/2, hwalls/2, -n/4, wwalls/2, hwalls, dwalls, 0.0, 0.0, 0.0), SAND, block_type='brick',",
"current directory brick_texture_path = os.path.dirname(__file__) + texture_bricks robot_texture_path = os.path.dirname(__file__) + texture_robot visualisation_texture_path",
"world main texture Return ------ texture_path: (str) path corresponding to the texture_bricks_name Raises",
"block front_wall_bb = round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0),",
"= os.path.dirname(__file__) + texture_distractors texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } # Build",
"depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=BRICK, block_type='brick', collision_reward = wall_reward) #back wall",
"import round_bot_model BOT = round_bot_model.Block.tex_coords((0, 0), (0, 1), (0, 1)) START = round_bot_model.Block.tex_coords((0,",
"visual distractors displacement - sandboxes (Bool) : add sandboxes ont the ground (slowing",
"return '/textures/texture_graffiti.png' elif texture_bricks_name == 'colours': return '/textures/texture_colours.png' else : raise ValueError('Unknown texture",
"(0, 1), (0, 0)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) BRICK",
"(wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1,",
"work for the moment from gym_round_bot.envs import round_bot_model # create textures coordinates GRASS",
"0.0, 0.0), GRASS, block_type='brick') # Build wall blocks with negative reward on collision",
"model.add_block( (0, 0.3, 0, nd/2, 0, nw/2, 0.0, 0.0, 0.0), SAND, block_type='sandbox') if",
"0.0, 0.0, 0.0), texture=BOT, block_type='robot') # add starting areas (the height=0 of block",
"size_ground_distractor = n = min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock( (0, 0.1, 0), (2*n, 0,",
"world - hwalls : (int) heigh of walls - dwalls: (int) depth of",
"inner face block front_wall_bb = round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0), (0.0,",
"# distractor back_wall inner face block back_wall_bb = round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1), (wwalls,",
"world nd = depth/2.0 # 1/2 depth of this world wr = width/3.0",
"don't fo (from round_bot_py import round_bot_model) here to avoid mutual imports ! import",
"0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox = back_wall_bb, speed=distractors_speed)",
"1), (1, 1)) BRICK = round_bot_model.Block.tex_coords((2, 0), (2, 0), (2, 0)) BRICK2 =",
"build default world texture_paths, world_info = _build_square_default_world(model, texture, width=width, depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward,",
"hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=STONE, block_type='brick', collision_reward = wall_reward)",
"world information \"\"\" texture_bricks = _texture_path(texture_bricks_name) # TODO : better import would be",
"texture_path: (str) path corresponding to the texture_bricks_name Raises ------ ValueError : raised if",
"= round_bot_model.Block.tex_coords((0, 0), (0, 1), (0, 1)) START = round_bot_model.Block.tex_coords((0, 0), (0, 0),",
"(0, 1)) START = round_bot_model.Block.tex_coords((0, 0), (0, 0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0,",
"dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=BRICK2, block_type='brick', collision_reward = wall_reward) if distractors:",
"wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, ): \"\"\" Builds a simple rectangle planar world",
"- CNRS / Sorbonne Université 02/2018 This file allows to build worlds TODO",
": width_wall_distractors = wwalls/2 height_wall_distractors = hwalls*2/3 # distractor back_wall inner face block",
"change in the world when crossed ON / OFF #TRIGGER = round_bot_model.Block.tex_coords((1, 0),",
"model.add_block( (-nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=STONE, block_type='brick', collision_reward",
"matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls,",
"# distractor front_wall inner face block front_wall_bb = round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1), (wwalls,",
"= hwalls*2/3 # distractor back_wall inner face block back_wall_bb = round_bot_model.BoundingBoxBlock( (0, hwalls/2,",
"0.0, 0.0), texture=STONE, block_type='brick', collision_reward = wall_reward) #right wall right_wall_block = model.add_block( (nd,",
"round_bot_model BOT = round_bot_model.Block.tex_coords((0, 0), (0, 1), (0, 1)) START = round_bot_model.Block.tex_coords((0, 0),",
"= min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock( (0, 0.1, 0), (2*n, 0, 2*n), (0.0, 0.0,",
"# middle wall model.add_block( (n/2, hwalls/2, -n/4, wwalls/2, hwalls, dwalls, 0.0, 0.0, 0.0),",
"the ground if asked (slowing down the robot when crossed) model.add_block( (0, 0.3,",
"width_wall_distractors = wwalls/2 height_wall_distractors = hwalls*2/3 # distractor back_wall inner face block back_wall_bb",
"Builds a simple rectangle planar world with walls around, and 1 wall in",
"is unkwnonw \"\"\" if texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti':",
"'/textures/texture_colours.png' else : raise ValueError('Unknown texture name '+ texture_bricks_name + ' in loading",
"- wall_reward : (float) reward for wall collision - distractors (Bool) : add",
"the environment (change to be defined) Returns ------- world information \"\"\" texture_bricks =",
"# Build gound block ground_block = model.add_block( (0, -3, 0, 2*nd, 6, 2*nw,",
"hwalls/2, -nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=BRICK, block_type='brick', collision_reward = wall_reward)",
"bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0, 0.0, 0.0), texture=START, block_type='start') return texture_paths, world_info",
"back_wall inner face block back_wall_bb = round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0),",
"hwalls, dwalls, 0.0, 0.0, 0.0), SAND, block_type='brick', collision_reward = -1) # Build reward",
"distractors_speed=0.1, sandboxes=False, trigger_button=False, ): \"\"\" Builds a simple rectangle planar world with walls",
"0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = goal_reward, visible=visible_reward) # Build robot block, set",
"round_bot_model) here to avoid mutual imports ! import os def _texture_path(texture_bricks_name): \"\"\" Parameter",
"bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = goal_reward,",
"def build_square_world(model, texture, robot_diameter=2 ,width=45, depth=45, hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False,",
": # add sandboxes ont the ground if asked (slowing down the robot",
"0.0), texture=BOT, block_type='robot') # add starting areas (the height=0 of block does not",
"texture_bricks, texture_robot, texture_visualisation : (string) paths for texture image of bricks, robot and",
": raise ValueError('Unknown texture name '+ texture_bricks_name + ' in loading world') def",
"-*- coding: utf-8 -*- \"\"\" <NAME> ISIR - CNRS / Sorbonne Université 02/2018",
"# Build wall blocks with negative reward on collision #front wall back_wall_block =",
"0)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) BRICK = round_bot_model.Block.tex_coords((2, 0),",
"ground (slowing down the robot when crossed) - trigger_button (Bool) : add a",
"(2, 2), (2, 2)) DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t) for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ]",
"0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = 1, visible_reward=visible_reward) # Build robot block,",
"0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox = front_wall_bb, speed=distractors_speed)",
"ground_bb, speed=distractors_speed) # wall distractors : width_wall_distractors = wwalls/2 height_wall_distractors = hwalls*2/3 #",
"0.0), texture=STONE, block_type='brick', collision_reward = wall_reward) #right wall right_wall_block = model.add_block( (nd, hwalls/2,",
"0.0, 0.0), texture=BRICK2, block_type='brick', collision_reward = wall_reward) if distractors: # add visual distractors",
"distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds the square world \"\"\" ## first",
"1/2 depth of this world wwalls = width # width of walls wr",
"#right wall right_wall_block = model.add_block( (nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0,",
"boundingBox = ground_bb, speed=distractors_speed) # wall distractors : width_wall_distractors = wwalls/2 height_wall_distractors =",
"wwalls, 0.0, 0.0, 0.0), texture=BRICK2, block_type='brick', collision_reward = wall_reward) if distractors: # add",
"robot_diameter/2.0 bot_height = bot_radius # middle wall model.add_block( (n/2, hwalls/2, -n/4, wwalls/2, hwalls,",
"visualisation - wall_reward : (float) reward for wall collision - distractors (Bool) :",
"texture_bricks robot_texture_path = os.path.dirname(__file__) + texture_robot visualisation_texture_path = os.path.dirname(__file__) + texture_visualisation distractors_texture_path =",
"# create textures coordinates GRASS = round_bot_model.Block.tex_coords((1, 0), (0, 1), (0, 0)) SAND",
"speed=distractors_speed) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor',",
"width=width, depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ## then add specs",
"START = round_bot_model.Block.tex_coords((0, 0), (0, 0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0,",
"width/2.0 # 1/2 width and depth of world wwalls = 2*n # width",
"in the environment (change to be defined) Returns ------- world information \"\"\" texture_bricks",
"of walls - dwalls: (int) depth of walls - texture_bricks, texture_robot, texture_visualisation :",
",width=45, depth=45, hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds",
"bot_height = bot_radius # middle wall model.add_block( (n/2, hwalls/2, -n/4, wwalls/2, hwalls, dwalls,",
"(int) depth of the world - hwalls : (int) heigh of walls -",
"depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=STONE2, block_type='brick', collision_reward = wall_reward) #left wall",
"walls around, and 1 wall in the middle \"\"\" ## first build default",
"block_type='reward', collision_reward = goal_reward, visible=visible_reward) # Build robot block, set initial height to",
"1)) n = width/2.0 # 1/2 width and depth of world wwalls =",
"0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) nw =",
"(0, bot_height/2.0+0.1, 0, 2*bot_radius, bot_height, 2*bot_radius, 0.0, 0.0, 0.0), texture=BOT, block_type='robot') # add",
"model.add_block( (0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0, 0.0, 0.0), texture=START, block_type='start') return",
"trigger_button=False, visible_reward=False): \"\"\" Builds the square world \"\"\" ## first build default world",
"model : (round_bot_model.Model) model to load world in - texture_bricks_name : (str) name",
"= round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) BRICK = round_bot_model.Block.tex_coords((2, 0), (2, 0),",
"small offset to avoid ground collision model.add_block( (0, bot_height/2.0+0.1, 0, 2*bot_radius, bot_height, 2*bot_radius,",
"0.0, 0.0, 0.0), BUTTON, block_type='trigger_button') world_info = { 'width' : 2*nw, 'depth' :",
"bricks, robot and visualisation - wall_reward : (float) reward for wall collision -",
"distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds the square world \"\"\" ## first build",
"2)) STONE = round_bot_model.Block.tex_coords((2, 1), (2, 1), (2, 1)) STONE2 = round_bot_model.Block.tex_coords((1, 2),",
"height_wall_distractors = hwalls*2/3 # distractor back_wall inner face block back_wall_bb = round_bot_model.BoundingBoxBlock( (0,",
"0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) SAND =",
"0.2, nw/3, 0.0, 0.0, 0.0), BUTTON, block_type='trigger_button') world_info = { 'width' : 2*nw,",
"(nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward =",
"0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) # wall distractors :",
"(0, 0.1, 0), (2*n, 0, 2*n), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0,",
"= width/2.0 # 1/2 width of this world nd = depth/2.0 # 1/2",
"round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0,",
"linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor',",
"# 1/2 depth of this world wwalls = width # width of walls",
"worlds in .json \"\"\" # WARNING : don't fo (from round_bot_py import round_bot_model)",
"add sandboxes ont the ground (slowing down the robot when crossed) - trigger_button",
"(round_bot_model.Model) model to load world in - texture_bricks_name : (str) name of the",
"0, nd/2, 0, nw/2, 0.0, 0.0, 0.0), SAND, block_type='sandbox') if trigger_button : #",
"hwalls, dwalls, 0.0, 0.0, 0.0), texture=BRICK, block_type='brick', collision_reward = wall_reward) #back wall front_wall_block",
"bot_radius # Build reward block in the corner rew = model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0,",
"-n/4, wwalls/2, hwalls, dwalls, 0.0, 0.0, 0.0), SAND, block_type='brick', collision_reward = -1) #",
"the world main texture Return ------ texture_path: (str) path corresponding to the texture_bricks_name",
"0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0,",
"0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox = left_wall_bb, speed=distractors_speed) # distractor right_wall inner face block",
"if sandboxes : # add sandboxes ont the ground if asked (slowing down",
"== 'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name ==",
"distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, ): \"\"\" Builds a simple rectangle planar world with",
"information \"\"\" texture_bricks = _texture_path(texture_bricks_name) # TODO : better import would be global",
"= _build_square_default_world(model, texture, width=width, depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ##",
"hwalls*2/3 # distractor back_wall inner face block back_wall_bb = round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1),",
"(0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0,",
"(2, 1)) STONE2 = round_bot_model.Block.tex_coords((1, 2), (1, 2), (1, 2)) BUTTON = round_bot_model.Block.tex_coords((2,",
"environment (change to be defined) Returns ------- world information \"\"\" texture_bricks = _texture_path(texture_bricks_name)",
"better import would be global and without \"from\" but doesn't work for the",
"will trigger a change in the environment (change to be defined) Returns -------",
"1, visible_reward=visible_reward) # Build robot block, set initial height to bot_heigh/2 + small",
"= model.add_block( (0, hwalls/2, -nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=BRICK, block_type='brick',",
"Returns ------- world information \"\"\" texture_bricks = _texture_path(texture_bricks_name) # TODO : better import",
"walls - dwalls: (int) depth of walls - texture_bricks, texture_robot, texture_visualisation : (string)",
"(0, 0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) SAND",
": don't fo (from round_bot_py import round_bot_model) here to avoid mutual imports !",
"planar world with walls around Parameters ---------- - model : (round_bot_model.Model) model to",
"(1, 0), (1, 0)) model.add_block( (0, 0.3, 0, nw/3, 0.2, nw/3, 0.0, 0.0,",
"here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0,",
"wall left_wall_block = model.add_block( (-nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0),",
"- trigger_button (Bool) : add a trigger button that will trigger a change",
"height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox = right_wall_bb, speed=distractors_speed) if sandboxes",
"2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0, 0.0, 0.0), texture=START, block_type='start') return texture_paths, world_info def build_square_1wall_world(model,",
"(1, 1)) BRICK = round_bot_model.Block.tex_coords((2, 0), (2, 0), (2, 0)) BRICK2 = round_bot_model.Block.tex_coords((0,",
"(change to be defined) Returns ------- world information \"\"\" texture_bricks = _texture_path(texture_bricks_name) #",
"= _texture_path(texture_bricks_name) # TODO : better import would be global and without \"from\"",
"block_type='brick', collision_reward = wall_reward) #back wall front_wall_block = model.add_block( (0, hwalls/2, nw, depth,",
"the square world \"\"\" ## first build default world texture_paths, world_info = _build_square_default_world(model,",
"wwalls = width # width of walls wr = width/4.0 # wr width",
"): \"\"\" Builds a simple rectangle planar world with walls around Parameters ----------",
"0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox = front_wall_bb,",
"(hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start')",
"rectangle planar world with walls around, and 1 wall in the middle \"\"\"",
"block in the corner rew = model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr,",
"speed of visual distractors displacement - sandboxes (Bool) : add sandboxes ont the",
"sandboxes (Bool) : add sandboxes ont the ground (slowing down the robot when",
"add sandboxes ont the ground if asked (slowing down the robot when crossed)",
"0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2,",
"_texture_path(texture_bricks_name): \"\"\" Parameter --------- texture_bricks_name : str name of the world main texture",
"(Bool) : add visual distractors on walls and ground - distractors_speed (float) :",
"if asked (slowing down the robot when crossed) model.add_block( (0, 0.3, 0, nd/2,",
"in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw = width/2.0 # 1/2 width of this world nd",
"0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=STONE, block_type='brick', collision_reward = wall_reward) #right",
"model.add_block( (n/2, hwalls/2, -n/4, wwalls/2, hwalls, dwalls, 0.0, 0.0, 0.0), SAND, block_type='brick', collision_reward",
"left_wall_bb, speed=distractors_speed) # distractor right_wall inner face block right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2,",
"on walls and ground - distractors_speed (float) : speed of visual distractors displacement",
"block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0,",
"block_type='brick') # Build wall blocks with negative reward on collision #front wall back_wall_block",
"corresponding to the texture_bricks_name Raises ------ ValueError : raised if texture_bricks_name is unkwnonw",
"0.0, 0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox = right_wall_bb, speed=distractors_speed) if sandboxes : #",
"SAND, block_type='sandbox') if trigger_button : # add a trigger button that will trigger",
"STONE2 = round_bot_model.Block.tex_coords((1, 2), (1, 2), (1, 2)) BUTTON = round_bot_model.Block.tex_coords((2, 2), (2,",
"distractor front_wall inner face block front_wall_bb = round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors,",
"0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox = left_wall_bb,",
"= round_bot_model.Block.tex_coords((0, 0), (0, 0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1),",
"will trigger a change in the world when crossed ON / OFF #TRIGGER",
"1)) nw = width/2.0 # 1/2 width of this world nd = depth/2.0",
"texture=BRICK2, block_type='brick', collision_reward = wall_reward) if distractors: # add visual distractors on the",
"collision - distractors (Bool) : add visual distractors on walls and ground -",
"width of walls wr = width/4.0 # wr width of reward area #",
"# add starting areas (the height=0 of block does not matter here, only",
"def build_square_1wall_world(model, texture, robot_diameter=2, width=45, depth=45, hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False,",
"\"\"\" Builds a simple rectangle planar world with walls around, and 1 wall",
"model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') model.add_block(",
"\"\"\" texture_bricks = _texture_path(texture_bricks_name) # TODO : better import would be global and",
"ISIR - CNRS / Sorbonne Université 02/2018 This file allows to build worlds",
"a .json loader and code worlds in .json \"\"\" # WARNING : don't",
"heigh of walls - dwalls: (int) depth of walls - texture_bricks, texture_robot, texture_visualisation",
"-3, 0, 2*nd, 6, 2*nw, 0.0, 0.0, 0.0), GRASS, block_type='brick') # Build wall",
"robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # Build reward block in",
"bot_height = bot_radius # Build reward block in the corner rew = model.add_block(",
"simple rectangle planar world with walls around, and 1 wall in the middle",
"bot_height, 2*bot_radius, 0.0, 0.0, 0.0), texture=BOT, block_type='robot') # add starting areas (the height=0",
"(0, 1), (0, 1)) nw = width/2.0 # 1/2 width of this world",
"-n+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = 1, visible_reward=visible_reward)",
"linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor',",
"gound block ground_block = model.add_block( (0, -3, 0, 2*nd, 6, 2*nw, 0.0, 0.0,",
"round_bot_model.Block.tex_coords((2, 2), (2, 2), (2, 2)) DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t) for t in",
"(Bool) : add a trigger button that will trigger a change in the",
"return '/textures/texture_colours.png' else : raise ValueError('Unknown texture name '+ texture_bricks_name + ' in",
"model.add_block( (0, 0.3, 0, nw/3, 0.2, nw/3, 0.0, 0.0, 0.0), BUTTON, block_type='trigger_button') world_info",
"os.path.dirname(__file__) + texture_robot visualisation_texture_path = os.path.dirname(__file__) + texture_visualisation distractors_texture_path = os.path.dirname(__file__) + texture_distractors",
"== 'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name == 'colours': return '/textures/texture_colours.png' else : raise",
"first build default world texture_paths, world_info = _build_square_default_world(model, texture, width=width, depth=depth, hwalls=hwalls, dwalls=dwalls,",
"Build wall blocks with negative reward on collision #front wall back_wall_block = model.add_block(",
"0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0),",
"down the robot when crossed) - trigger_button (Bool) : add a trigger button",
"(2, 0)) BRICK2 = round_bot_model.Block.tex_coords((0, 2), (0, 2), (0, 2)) STONE = round_bot_model.Block.tex_coords((2,",
"collision_reward = wall_reward) #left wall left_wall_block = model.add_block( (-nd, hwalls/2, 0, dwalls, hwalls,",
"displacement - sandboxes (Bool) : add sandboxes ont the ground (slowing down the",
"to the texture_bricks_name Raises ------ ValueError : raised if texture_bricks_name is unkwnonw \"\"\"",
"world_info def build_square_1wall_world(model, texture, robot_diameter=2, width=45, depth=45, hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1,",
"= 1, visible_reward=visible_reward) # Build robot block, set initial height to bot_heigh/2 +",
"wr = width/3.0 # wr width of reward area wwalls = width #",
"robot when crossed) - trigger_button (Bool) : add a trigger button that will",
"= model.add_block( (0, hwalls/2, nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=STONE2, block_type='brick',",
"Raises ------ ValueError : raised if texture_bricks_name is unkwnonw \"\"\" if texture_bricks_name ==",
"= wall_reward) #right wall right_wall_block = model.add_block( (nd, hwalls/2, 0, dwalls, hwalls, wwalls,",
"wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds the square world \"\"\"",
"hwalls/2, nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=STONE2, block_type='brick', collision_reward = wall_reward)",
"model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox",
"_build_square_default_world(model, texture, width=width, depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ## then",
"robot and visualisation - wall_reward : (float) reward for wall collision - distractors",
"sandboxes ont the ground if asked (slowing down the robot when crossed) model.add_block(",
"'/textures/texture_graffiti.png' elif texture_bricks_name == 'colours': return '/textures/texture_colours.png' else : raise ValueError('Unknown texture name",
"0), (2, 0), (2, 0)) BRICK2 = round_bot_model.Block.tex_coords((0, 2), (0, 2), (0, 2))",
"wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = 1, visible_reward=visible_reward) #",
"hwalls, wwalls, 0.0, 0.0, 0.0), texture=STONE, block_type='brick', collision_reward = wall_reward) #right wall right_wall_block",
"(0, 0.3, 0, nw/3, 0.2, nw/3, 0.0, 0.0, 0.0), BUTTON, block_type='trigger_button') world_info =",
"------ texture_path: (str) path corresponding to the texture_bricks_name Raises ------ ValueError : raised",
"wall_reward) #right wall right_wall_block = model.add_block( (nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0,",
"-nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = goal_reward, visible=visible_reward)",
": replace this file by a .json loader and code worlds in .json",
"bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') return texture_paths, world_info",
"(hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0, 0.0, 0.0), texture=START, block_type='start')",
"= {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } # Build gound block ground_block = model.add_block(",
"a change in the world when crossed ON / OFF #TRIGGER = round_bot_model.Block.tex_coords((1,",
"0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) model.add_block( components=(0, 0, 0,",
"= round_bot_model.Block.tex_coords((1, 0), (1, 0), (1, 0)) model.add_block( (0, 0.3, 0, nw/3, 0.2,",
"of reward area # set robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius",
"# 1/2 depth of this world wr = width/3.0 # wr width of",
"height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox = left_wall_bb, speed=distractors_speed) # distractor",
"size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) model.add_block(",
"of bricks, robot and visualisation - wall_reward : (float) reward for wall collision",
"width/2.0 # 1/2 width of this world nd = depth/2.0 # 1/2 depth",
"= bot_radius # middle wall model.add_block( (n/2, hwalls/2, -n/4, wwalls/2, hwalls, dwalls, 0.0,",
"# distractor ground block size_ground_distractor = n = min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock( (0,",
": (int) width of the world - depth : (int) depth of the",
"os.path.dirname(__file__) + texture_distractors texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } # Build gound",
"model.add_block( (0, bot_height/2.0+0.1, 0, 2*bot_radius, bot_height, 2*bot_radius, 0.0, 0.0, 0.0), texture=BOT, block_type='robot') #",
"0.0, 0.0), BUTTON, block_type='trigger_button') world_info = { 'width' : 2*nw, 'depth' : 2*nd,",
"1)) START = round_bot_model.Block.tex_coords((0, 0), (0, 0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1),",
"(2, 2)) DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t) for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw =",
"directory brick_texture_path = os.path.dirname(__file__) + texture_bricks robot_texture_path = os.path.dirname(__file__) + texture_robot visualisation_texture_path =",
"world_info = _build_square_default_world(model, texture, width=width, depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,)",
"to load world in - texture_bricks_name : (str) name of the texture for",
"dwalls: (int) depth of walls - texture_bricks, texture_robot, texture_visualisation : (string) paths for",
"-1) # Build reward block in the corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr,",
"= ground_bb, speed=distractors_speed) # wall distractors : width_wall_distractors = wwalls/2 height_wall_distractors = hwalls*2/3",
"_texture_path(texture_bricks_name) # TODO : better import would be global and without \"from\" but",
"0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb,",
"back_wall_bb, speed=distractors_speed) # distractor front_wall inner face block front_wall_bb = round_bot_model.BoundingBoxBlock(( 0, hwalls/2,",
"hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0,",
"robot_diameter/2.0 bot_height = bot_radius # Build reward block in the corner rew =",
"hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0,",
"with walls around, and 1 wall in the middle \"\"\" ## first build",
"0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) # wall distractors : width_wall_distractors =",
"1), (2, 1)) STONE2 = round_bot_model.Block.tex_coords((1, 2), (1, 2), (1, 2)) BUTTON =",
"= right_wall_bb, speed=distractors_speed) if sandboxes : # add sandboxes ont the ground if",
"texture_robot visualisation_texture_path = os.path.dirname(__file__) + texture_visualisation distractors_texture_path = os.path.dirname(__file__) + texture_distractors texture_paths =",
"width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox = front_wall_bb, speed=distractors_speed) #",
"round_bot_model # create textures coordinates GRASS = round_bot_model.Block.tex_coords((1, 0), (0, 1), (0, 0))",
"utf-8 -*- \"\"\" <NAME> ISIR - CNRS / Sorbonne Université 02/2018 This file",
"0.0), SAND, block_type='sandbox') if trigger_button : # add a trigger button that will",
"wr = width/4.0 # wr width of reward area # set robot specifications",
"to avoid ground collision model.add_block( (0, bot_height/2.0+0.1, 0, 2*bot_radius, bot_height, 2*bot_radius, 0.0, 0.0,",
"(0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) SAND = round_bot_model.Block.tex_coords((1,",
": 2*nw, 'depth' : 2*nd, } return texture_paths, world_info def build_square_world(model, texture, robot_diameter=2",
"ground_block = model.add_block( (0, -3, 0, 2*nd, 6, 2*nw, 0.0, 0.0, 0.0), GRASS,",
"in current directory brick_texture_path = os.path.dirname(__file__) + texture_bricks robot_texture_path = os.path.dirname(__file__) + texture_robot",
"= -1) # Build reward block in the corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2),",
"width=45, depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, ):",
"wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = goal_reward, visible=visible_reward) # Build robot",
"reward block in the corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0,",
"distractor left_wall inner face block left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0), (0.0, height_wall_distractors,",
"(0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0,",
"Build reward block in the corner rew = model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr,",
"distractors_speed (float) : speed of visual distractors displacement - sandboxes (Bool) : add",
"dwalls, 0.0, 0.0, 0.0), SAND, block_type='brick', collision_reward = -1) # Build reward block",
"specs from gym_round_bot.envs import round_bot_model BOT = round_bot_model.Block.tex_coords((0, 0), (0, 1), (0, 1))",
"(1, 1)) n = width/2.0 # 1/2 width and depth of world wwalls",
"file by a .json loader and code worlds in .json \"\"\" # WARNING",
"= [ round_bot_model.Block.tex_coords(t,t,t) for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw = width/2.0 # 1/2",
"'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } # Build gound block ground_block = model.add_block( (0, -3,",
"texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox = back_wall_bb, speed=distractors_speed) # distractor front_wall inner face block front_wall_bb",
"--------- texture_bricks_name : str name of the world main texture Return ------ texture_path:",
"else : raise ValueError('Unknown texture name '+ texture_bricks_name + ' in loading world')",
"1/2 depth of this world wr = width/3.0 # wr width of reward",
"visual distractors on walls and ground - distractors_speed (float) : speed of visual",
"collision_reward = wall_reward) #back wall front_wall_block = model.add_block( (0, hwalls/2, nw, depth, hwalls,",
"block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) # wall distractors : width_wall_distractors = wwalls/2 height_wall_distractors",
"area # set robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # Build",
"(-nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=STONE, block_type='brick', collision_reward =",
"face block back_wall_bb = round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0,",
"0, nw/2, 0.0, 0.0, 0.0), SAND, block_type='sandbox') if trigger_button : # add a",
"to be defined) Returns ------- world information \"\"\" texture_bricks = _texture_path(texture_bricks_name) # TODO",
"right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block)",
"ground collision model.add_block( (0, bot_height/2.0+0.1, 0, 2*bot_radius, bot_height, 2*bot_radius, 0.0, 0.0, 0.0), texture=BOT,",
": add sandboxes ont the ground (slowing down the robot when crossed) -",
"0, 2*bot_radius, bot_height, 2*bot_radius, 0.0, 0.0, 0.0), texture=BOT, block_type='robot') # add starting areas",
"'+ texture_bricks_name + ' in loading world') def _build_square_default_world(model, texture_bricks_name, width=45, depth=45, hwalls=4,",
"model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward",
"return texture_paths, world_info def build_square_1wall_world(model, texture, robot_diameter=2, width=45, depth=45, hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10,",
"= { 'width' : 2*nw, 'depth' : 2*nd, } return texture_paths, world_info def",
"left_wall_block = model.add_block( (-nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=STONE,",
"block right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0),",
"boundingBox = front_wall_bb, speed=distractors_speed) # distractor left_wall inner face block left_wall_bb = round_bot_model.BoundingBoxBlock(",
"around, and 1 wall in the middle \"\"\" ## first build default world",
"from gym_round_bot.envs import round_bot_model # create textures coordinates GRASS = round_bot_model.Block.tex_coords((1, 0), (0,",
"str name of the world main texture Return ------ texture_path: (str) path corresponding",
"and code worlds in .json \"\"\" # WARNING : don't fo (from round_bot_py",
"texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name",
"= round_bot_model.BoundingBoxBlock( (0, 0.1, 0), (2*n, 0, 2*n), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block(",
"BOT = round_bot_model.Block.tex_coords((0, 0), (0, 1), (0, 1)) START = round_bot_model.Block.tex_coords((0, 0), (0,",
"nw = width/2.0 # 1/2 width of this world nd = depth/2.0 #",
"in loading world') def _build_square_default_world(model, texture_bricks_name, width=45, depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png',",
"texture, width=width, depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ## then add",
"avoid ground collision model.add_block( (0, bot_height/2.0+0.1, 0, 2*bot_radius, bot_height, 2*bot_radius, 0.0, 0.0, 0.0),",
"# TODO : better import would be global and without \"from\" but doesn't",
"would be global and without \"from\" but doesn't work for the moment from",
"texture_paths, world_info def build_square_world(model, texture, robot_diameter=2 ,width=45, depth=45, hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10, distractors=False,",
": (int) depth of the world - hwalls : (int) heigh of walls",
"height to bot_heigh/2 + small offset to avoid ground collision model.add_block( (0, bot_height/2.0+0.1,",
"set robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # middle wall model.add_block(",
"this file by a .json loader and code worlds in .json \"\"\" #",
"code worlds in .json \"\"\" # WARNING : don't fo (from round_bot_py import",
"(str) path corresponding to the texture_bricks_name Raises ------ ValueError : raised if texture_bricks_name",
"bot_heigh/2 + small offset to avoid ground collision model.add_block( (0, bot_height/2.0+0.1, 0, 2*bot_radius,",
"mutual imports ! import os def _texture_path(texture_bricks_name): \"\"\" Parameter --------- texture_bricks_name : str",
"wall in the middle \"\"\" ## first build default world texture_paths, world_info =",
"face block left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0,",
"1), (0, 1)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) n =",
"bot_radius = robot_diameter/2.0 bot_height = bot_radius # middle wall model.add_block( (n/2, hwalls/2, -n/4,",
"bricks - width : (int) width of the world - depth : (int)",
"distractors on the groud and inner faces of walls if asked # distractor",
"size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) #",
"wall_reward) #back wall front_wall_block = model.add_block( (0, hwalls/2, nw, depth, hwalls, dwalls, 0.0,",
"crossed) model.add_block( (0, 0.3, 0, nd/2, 0, nw/2, 0.0, 0.0, 0.0), SAND, block_type='sandbox')",
"0.0, 0.0, 0.0), texture=BRICK2, block_type='brick', collision_reward = wall_reward) if distractors: # add visual",
"model to load world in - texture_bricks_name : (str) name of the texture",
"image of bricks, robot and visualisation - wall_reward : (float) reward for wall",
"dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ## then add specs from gym_round_bot.envs import",
"of this world wwalls = width # width of walls wr = width/4.0",
"a simple rectangle planar world with walls around, and 1 wall in the",
"of world wwalls = 2*n # width of walls wr = width/4.0 #",
"(nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=BRICK2, block_type='brick', collision_reward =",
"= left_wall_bb, speed=distractors_speed) # distractor right_wall inner face block right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1,",
"dwalls=2, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds a simple rectangle",
"n = min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock( (0, 0.1, 0), (2*n, 0, 2*n), (0.0,",
"= round_bot_model.Block.tex_coords((2, 2), (2, 2), (2, 2)) DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t) for t",
"(2*n, 0, 2*n), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0,",
"0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[3],",
"- dwalls: (int) depth of walls - texture_bricks, texture_robot, texture_visualisation : (string) paths",
"+ texture_distractors texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } # Build gound block",
"depth/2.0 # 1/2 depth of this world wwalls = width # width of",
"for the moment from gym_round_bot.envs import round_bot_model # create textures coordinates GRASS =",
"0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox = right_wall_bb,",
"speed=distractors_speed) # distractor right_wall inner face block right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0),",
"of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0, 0.0, 0.0), texture=START,",
"middle \"\"\" ## first build default world texture_paths, world_info = _build_square_default_world(model, texture, width=width,",
"collision_reward = wall_reward) if distractors: # add visual distractors on the groud and",
"offset to avoid ground collision model.add_block( (0, bot_height/2.0+0.1, 0, 2*bot_radius, bot_height, 2*bot_radius, 0.0,",
": str name of the world main texture Return ------ texture_path: (str) path",
"rectangle planar world with walls around Parameters ---------- - model : (round_bot_model.Model) model",
"negative reward on collision #front wall back_wall_block = model.add_block( (0, hwalls/2, -nw, depth,",
"but doesn't work for the moment from gym_round_bot.envs import round_bot_model # create textures",
"sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds a simple rectangle planar world with walls around,",
"2), (2, 2)) DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t) for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw",
"# set robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # middle wall",
"0.0, 0.0), texture=START, block_type='start') return texture_paths, world_info def build_square_1wall_world(model, texture, robot_diameter=2, width=45, depth=45,",
"bot_radius # middle wall model.add_block( (n/2, hwalls/2, -n/4, wwalls/2, hwalls, dwalls, 0.0, 0.0,",
"2), (2, 2), (2, 2)) DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t) for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)]",
"with walls around Parameters ---------- - model : (round_bot_model.Model) model to load world",
"# wr width of reward area # set robot specifications bot_radius = robot_diameter/2.0",
"if asked # distractor ground block size_ground_distractor = n = min(nw,nd) ground_bb =",
"0, 2*n), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor,",
"0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0),",
"in .json \"\"\" # WARNING : don't fo (from round_bot_py import round_bot_model) here",
"0.0, 0.0, 0.0), texture=STONE2, block_type='brick', collision_reward = wall_reward) #left wall left_wall_block = model.add_block(",
"( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') return",
": (string) paths for texture image of bricks, robot and visualisation - wall_reward",
"nw/3, 0.0, 0.0, 0.0), BUTTON, block_type='trigger_button') world_info = { 'width' : 2*nw, 'depth'",
"by a .json loader and code worlds in .json \"\"\" # WARNING :",
"back_wall_bb = round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block)",
"texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox = front_wall_bb, speed=distractors_speed) # distractor left_wall inner face block left_wall_bb",
"depth=45, hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds the",
"width=45, depth=45, hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds",
"and depth of world wwalls = 2*n # width of walls wr =",
"load world in - texture_bricks_name : (str) name of the texture for the",
"= model.add_block( (nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=BRICK2, block_type='brick',",
"walls if asked # distractor ground block size_ground_distractor = n = min(nw,nd) ground_bb",
"0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox = right_wall_bb, speed=distractors_speed) if",
"in the world when crossed ON / OFF #TRIGGER = round_bot_model.Block.tex_coords((1, 0), (1,",
"0.0, 0.0), texture=START, block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1, (wwalls-2*dwalls)/2, 0.0,",
"button that will trigger a change in the world when crossed ON /",
"and inner faces of walls if asked # distractor ground block size_ground_distractor =",
"simple rectangle planar world with walls around Parameters ---------- - model : (round_bot_model.Model)",
"Université 02/2018 This file allows to build worlds TODO : replace this file",
"trigger_button=False, visible_reward=False): \"\"\" Builds a simple rectangle planar world with walls around, and",
"2), (1, 2), (1, 2)) BUTTON = round_bot_model.Block.tex_coords((2, 2), (2, 2), (2, 2))",
"height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox = back_wall_bb, speed=distractors_speed) # distractor",
"left_wall inner face block left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls),",
"------ ValueError : raised if texture_bricks_name is unkwnonw \"\"\" if texture_bricks_name == 'minecraft':",
"loading world') def _build_square_default_world(model, texture_bricks_name, width=45, depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1,",
"#back wall front_wall_block = model.add_block( (0, hwalls/2, nw, depth, hwalls, dwalls, 0.0, 0.0,",
"height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox = front_wall_bb, speed=distractors_speed) # distractor",
"0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox = right_wall_bb, speed=distractors_speed)",
"Builds a simple rectangle planar world with walls around Parameters ---------- - model",
"# wr width of reward area wwalls = width # get texture paths",
"when crossed) model.add_block( (0, 0.3, 0, nd/2, 0, nw/2, 0.0, 0.0, 0.0), SAND,",
"= wall_reward) #back wall front_wall_block = model.add_block( (0, hwalls/2, nw, depth, hwalls, dwalls,",
"(0, 1), (0, 1)) START = round_bot_model.Block.tex_coords((0, 0), (0, 0), (0, 0)) REWARD",
"width/4.0 # wr width of reward area # set robot specifications bot_radius =",
"block_type='flat_distractor', boundingBox = right_wall_bb, speed=distractors_speed) if sandboxes : # add sandboxes ont the",
"\"from\" but doesn't work for the moment from gym_round_bot.envs import round_bot_model # create",
"0), (2, 0)) BRICK2 = round_bot_model.Block.tex_coords((0, 2), (0, 2), (0, 2)) STONE =",
"texture=BRICK, block_type='brick', collision_reward = wall_reward) #back wall front_wall_block = model.add_block( (0, hwalls/2, nw,",
"robot_diameter=2, width=45, depth=45, hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\"",
"walls and ground - distractors_speed (float) : speed of visual distractors displacement -",
"02/2018 This file allows to build worlds TODO : replace this file by",
"= robot_diameter/2.0 bot_height = bot_radius # Build reward block in the corner rew",
"faces of walls if asked # distractor ground block size_ground_distractor = n =",
"in the corner rew = model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0,",
"sandboxes : # add sandboxes ont the ground if asked (slowing down the",
"texture_visualisation distractors_texture_path = os.path.dirname(__file__) + texture_distractors texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, }",
"(2, 0), (2, 0)) BRICK2 = round_bot_model.Block.tex_coords((0, 2), (0, 2), (0, 2)) STONE",
"(int) heigh of walls - dwalls: (int) depth of walls - texture_bricks, texture_robot,",
"0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0, 0.0, 0.0), texture=START, block_type='start') return texture_paths, world_info def",
"2*nd, } return texture_paths, world_info def build_square_world(model, texture, robot_diameter=2 ,width=45, depth=45, hwalls=4, dwalls=1,",
"0.0, 0.0), SAND, block_type='brick', collision_reward = -1) # Build reward block in the",
"does not matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls,",
"height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors,",
"= depth/2.0 # 1/2 depth of this world wwalls = width # width",
"block size_ground_distractor = n = min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock( (0, 0.1, 0), (2*n,",
"(int) depth of walls - texture_bricks, texture_robot, texture_visualisation : (string) paths for texture",
"paths in current directory brick_texture_path = os.path.dirname(__file__) + texture_bricks robot_texture_path = os.path.dirname(__file__) +",
"- width : (int) width of the world - depth : (int) depth",
"- sandboxes (Bool) : add sandboxes ont the ground (slowing down the robot",
"block ground_block = model.add_block( (0, -3, 0, 2*nd, 6, 2*nw, 0.0, 0.0, 0.0),",
"hwalls : (int) heigh of walls - dwalls: (int) depth of walls -",
"0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox = front_wall_bb, speed=distractors_speed) # distractor left_wall",
"texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name == 'colours': return '/textures/texture_colours.png' else :",
"wall distractors : width_wall_distractors = wwalls/2 height_wall_distractors = hwalls*2/3 # distractor back_wall inner",
"= round_bot_model.Block.tex_coords((2, 0), (2, 0), (2, 0)) BRICK2 = round_bot_model.Block.tex_coords((0, 2), (0, 2),",
"- model : (round_bot_model.Model) model to load world in - texture_bricks_name : (str)",
"0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox = back_wall_bb, speed=distractors_speed) # distractor front_wall",
"= round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block(",
"trigger_button : # add a trigger button that will trigger a change in",
"block back_wall_bb = round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0),",
"nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=STONE2, block_type='brick', collision_reward = wall_reward) #left",
"face block right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0,",
"of the world - depth : (int) depth of the world - hwalls",
"of reward area wwalls = width # get texture paths in current directory",
"\"\"\" <NAME> ISIR - CNRS / Sorbonne Université 02/2018 This file allows to",
"texture_distractors texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } # Build gound block ground_block",
"wall front_wall_block = model.add_block( (0, hwalls/2, nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0),",
"width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox = right_wall_bb, speed=distractors_speed) if sandboxes :",
"to build worlds TODO : replace this file by a .json loader and",
"= width/4.0 # wr width of reward area # set robot specifications bot_radius",
"os def _texture_path(texture_bricks_name): \"\"\" Parameter --------- texture_bricks_name : str name of the world",
"add visual distractors on walls and ground - distractors_speed (float) : speed of",
"1)) BRICK = round_bot_model.Block.tex_coords((2, 0), (2, 0), (2, 0)) BRICK2 = round_bot_model.Block.tex_coords((0, 2),",
"for texture image of bricks, robot and visualisation - wall_reward : (float) reward",
"model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox",
"= round_bot_model.Block.tex_coords((0, 2), (0, 2), (0, 2)) STONE = round_bot_model.Block.tex_coords((2, 1), (2, 1),",
"0.0, 0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox = right_wall_bb, speed=distractors_speed) if sandboxes : # add",
"speed=distractors_speed) # distractor left_wall inner face block left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0),",
"boundingBox = right_wall_bb, speed=distractors_speed) if sandboxes : # add sandboxes ont the ground",
"hwalls/2, -n/4, wwalls/2, hwalls, dwalls, 0.0, 0.0, 0.0), SAND, block_type='brick', collision_reward = -1)",
"= model.add_block( (-nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=STONE, block_type='brick',",
"block_type='trigger_button') world_info = { 'width' : 2*nw, 'depth' : 2*nd, } return texture_paths,",
"block in the corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0,",
"{ 'width' : 2*nw, 'depth' : 2*nd, } return texture_paths, world_info def build_square_world(model,",
"collision_reward = wall_reward) #right wall right_wall_block = model.add_block( (nd, hwalls/2, 0, dwalls, hwalls,",
"inner faces of walls if asked # distractor ground block size_ground_distractor = n",
"wall back_wall_block = model.add_block( (0, hwalls/2, -nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0),",
"t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw = width/2.0 # 1/2 width of this world",
"boundingBox = back_wall_bb, speed=distractors_speed) # distractor front_wall inner face block front_wall_bb = round_bot_model.BoundingBoxBlock((",
"block left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0),",
"= bot_radius # Build reward block in the corner rew = model.add_block( (nd-(wr/2+dwalls/2),",
"linked_block=ground_block) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor',",
"0.1, 2*nw-2*dwalls, 0.0, 0.0, 0.0), texture=START, block_type='start') return texture_paths, world_info def build_square_1wall_world(model, texture,",
"of the world - hwalls : (int) heigh of walls - dwalls: (int)",
"texture_bricks = _texture_path(texture_bricks_name) # TODO : better import would be global and without",
"for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw = width/2.0 # 1/2 width of this",
"does not matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls,",
"SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) BRICK = round_bot_model.Block.tex_coords((2, 0), (2,",
"depth=45, hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds a",
"(n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward =",
"(0, 1), (0, 1)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) n",
"- distractors (Bool) : add visual distractors on walls and ground - distractors_speed",
"2), (0, 2)) STONE = round_bot_model.Block.tex_coords((2, 1), (2, 1), (2, 1)) STONE2 =",
"min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock( (0, 0.1, 0), (2*n, 0, 2*n), (0.0, 0.0, 0.0),",
"ValueError : raised if texture_bricks_name is unkwnonw \"\"\" if texture_bricks_name == 'minecraft': return",
"TODO : replace this file by a .json loader and code worlds in",
"world in - texture_bricks_name : (str) name of the texture for the bricks",
"(0, 2), (0, 2)) STONE = round_bot_model.Block.tex_coords((2, 1), (2, 1), (2, 1)) STONE2",
"2*nw, 'depth' : 2*nd, } return texture_paths, world_info def build_square_world(model, texture, robot_diameter=2 ,width=45,",
"of walls wr = width/4.0 # wr width of reward area # set",
"ValueError('Unknown texture name '+ texture_bricks_name + ' in loading world') def _build_square_default_world(model, texture_bricks_name,",
"textures coordinates GRASS = round_bot_model.Block.tex_coords((1, 0), (0, 1), (0, 0)) SAND = round_bot_model.Block.tex_coords((1,",
"+ texture_robot visualisation_texture_path = os.path.dirname(__file__) + texture_visualisation distractors_texture_path = os.path.dirname(__file__) + texture_distractors texture_paths",
"'distractors':distractors_texture_path, } # Build gound block ground_block = model.add_block( (0, -3, 0, 2*nd,",
"width and depth of world wwalls = 2*n # width of walls wr",
"reward on collision #front wall back_wall_block = model.add_block( (0, hwalls/2, -nw, depth, hwalls,",
"texture=REWARD, block_type='reward', collision_reward = 1, visible_reward=visible_reward) # Build robot block, set initial height",
"1), (0, 1), (0, 1)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1))",
"around Parameters ---------- - model : (round_bot_model.Model) model to load world in -",
"robot block, set initial height to bot_heigh/2 + small offset to avoid ground",
"#!/usr/bin/python # -*- coding: utf-8 -*- \"\"\" <NAME> ISIR - CNRS / Sorbonne",
"GRASS = round_bot_model.Block.tex_coords((1, 0), (0, 1), (0, 0)) SAND = round_bot_model.Block.tex_coords((1, 1), (1,",
": add a trigger button that will trigger a change in the environment",
"hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ## then add specs from gym_round_bot.envs",
"bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = 1, visible_reward=visible_reward) # Build",
"walls around Parameters ---------- - model : (round_bot_model.Model) model to load world in",
"the texture for the bricks - width : (int) width of the world",
"block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START,",
"of the world main texture Return ------ texture_path: (str) path corresponding to the",
"= back_wall_bb, speed=distractors_speed) # distractor front_wall inner face block front_wall_bb = round_bot_model.BoundingBoxBlock(( 0,",
"1), (0, 1)) START = round_bot_model.Block.tex_coords((0, 0), (0, 0), (0, 0)) REWARD =",
"when crossed ON / OFF #TRIGGER = round_bot_model.Block.tex_coords((1, 0), (1, 0), (1, 0))",
"= round_bot_model.Block.tex_coords((1, 2), (1, 2), (1, 2)) BUTTON = round_bot_model.Block.tex_coords((2, 2), (2, 2),",
"== 'colours': return '/textures/texture_colours.png' else : raise ValueError('Unknown texture name '+ texture_bricks_name +",
": (round_bot_model.Model) model to load world in - texture_bricks_name : (str) name of",
"0.0), texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox = right_wall_bb, speed=distractors_speed) if sandboxes : # add sandboxes",
"sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds the square world \"\"\" ## first build default",
"0.0, 0.0, 0.0), GRASS, block_type='brick') # Build wall blocks with negative reward on",
"world wr = width/3.0 # wr width of reward area wwalls = width",
"! import os def _texture_path(texture_bricks_name): \"\"\" Parameter --------- texture_bricks_name : str name of",
"0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) SAND = round_bot_model.Block.tex_coords((1, 1),",
"= round_bot_model.Block.tex_coords((2, 1), (2, 1), (2, 1)) STONE2 = round_bot_model.Block.tex_coords((1, 2), (1, 2),",
"visible_reward=False): \"\"\" Builds the square world \"\"\" ## first build default world texture_paths,",
"width of the world - depth : (int) depth of the world -",
"area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0),",
"_build_square_default_world(model, texture_bricks_name, width=45, depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False,",
"'width' : 2*nw, 'depth' : 2*nd, } return texture_paths, world_info def build_square_world(model, texture,",
"(int) width of the world - depth : (int) depth of the world",
"reward area wwalls = width # get texture paths in current directory brick_texture_path",
"0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0),",
"1), (0, 1), (0, 1)) nw = width/2.0 # 1/2 width of this",
"depth : (int) depth of the world - hwalls : (int) heigh of",
"depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, ): \"\"\"",
"(1, 1), (1, 1)) BRICK = round_bot_model.Block.tex_coords((2, 0), (2, 0), (2, 0)) BRICK2",
"world \"\"\" ## first build default world texture_paths, world_info = _build_square_default_world(model, texture, width=width,",
"if texture_bricks_name is unkwnonw \"\"\" if texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name",
"0.0), texture=REWARD, block_type='reward', collision_reward = goal_reward, visible=visible_reward) # Build robot block, set initial",
"1), (0, 0)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) BRICK =",
"width/3.0 # wr width of reward area wwalls = width # get texture",
"0, nw/3, 0.2, nw/3, 0.0, 0.0, 0.0), BUTTON, block_type='trigger_button') world_info = { 'width'",
"round_bot_py import round_bot_model) here to avoid mutual imports ! import os def _texture_path(texture_bricks_name):",
"speed=distractors_speed) # distractor front_wall inner face block front_wall_bb = round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1),",
"GRASS, block_type='brick') # Build wall blocks with negative reward on collision #front wall",
"texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path, } # Build gound block ground_block =",
"= goal_reward, visible=visible_reward) # Build robot block, set initial height to bot_heigh/2 +",
".json loader and code worlds in .json \"\"\" # WARNING : don't fo",
"texture_bricks_name == 'colours': return '/textures/texture_colours.png' else : raise ValueError('Unknown texture name '+ texture_bricks_name",
"visible=visible_reward) # Build robot block, set initial height to bot_heigh/2 + small offset",
"to bot_heigh/2 + small offset to avoid ground collision model.add_block( (0, bot_height/2.0+0.1, 0,",
"round_bot_model.Block.tex_coords((1, 0), (0, 1), (0, 0)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1,",
"OFF #TRIGGER = round_bot_model.Block.tex_coords((1, 0), (1, 0), (1, 0)) model.add_block( (0, 0.3, 0,",
"texture_visualisation : (string) paths for texture image of bricks, robot and visualisation -",
"2), (1, 2)) BUTTON = round_bot_model.Block.tex_coords((2, 2), (2, 2), (2, 2)) DISTRACTORS =",
"name of the world main texture Return ------ texture_path: (str) path corresponding to",
"def _build_square_default_world(model, texture_bricks_name, width=45, depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1,",
"return texture_paths, world_info def build_square_world(model, texture, robot_diameter=2 ,width=45, depth=45, hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10,",
"def _texture_path(texture_bricks_name): \"\"\" Parameter --------- texture_bricks_name : str name of the world main",
"model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox",
"} return texture_paths, world_info def build_square_world(model, texture, robot_diameter=2 ,width=45, depth=45, hwalls=4, dwalls=1, wall_reward=-1,",
"trigger_button=trigger_button,) ## then add specs from gym_round_bot.envs import round_bot_model BOT = round_bot_model.Block.tex_coords((0, 0),",
"2*n # width of walls wr = width/4.0 # wr width of reward",
"'depth' : 2*nd, } return texture_paths, world_info def build_square_world(model, texture, robot_diameter=2 ,width=45, depth=45,",
"model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward",
"(0, hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0,",
".json \"\"\" # WARNING : don't fo (from round_bot_py import round_bot_model) here to",
"block_type='flat_distractor', boundingBox = left_wall_bb, speed=distractors_speed) # distractor right_wall inner face block right_wall_bb =",
"texture=STONE, block_type='brick', collision_reward = wall_reward) #right wall right_wall_block = model.add_block( (nd, hwalls/2, 0,",
"0), (0, 1), (0, 1)) START = round_bot_model.Block.tex_coords((0, 0), (0, 0), (0, 0))",
"------- world information \"\"\" texture_bricks = _texture_path(texture_bricks_name) # TODO : better import would",
"wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds a simple rectangle planar",
"ont the ground (slowing down the robot when crossed) - trigger_button (Bool) :",
"the ground (slowing down the robot when crossed) - trigger_button (Bool) : add",
"= n = min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock( (0, 0.1, 0), (2*n, 0, 2*n),",
"a simple rectangle planar world with walls around Parameters ---------- - model :",
"name '+ texture_bricks_name + ' in loading world') def _build_square_default_world(model, texture_bricks_name, width=45, depth=45,",
"dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=STONE, block_type='brick', collision_reward = wall_reward) #right wall",
"wall right_wall_block = model.add_block( (nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0),",
"round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0,",
"import round_bot_model) here to avoid mutual imports ! import os def _texture_path(texture_bricks_name): \"\"\"",
"0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox = left_wall_bb, speed=distractors_speed)",
"# Build robot block, set initial height to bot_heigh/2 + small offset to",
"SAND, block_type='brick', collision_reward = -1) # Build reward block in the corner model.add_block(",
"0.3, 0, nd/2, 0, nw/2, 0.0, 0.0, 0.0), SAND, block_type='sandbox') if trigger_button :",
"world wwalls = width # width of walls wr = width/4.0 # wr",
"(wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors,",
"worlds TODO : replace this file by a .json loader and code worlds",
"Sorbonne Université 02/2018 This file allows to build worlds TODO : replace this",
"the world - depth : (int) depth of the world - hwalls :",
"n = width/2.0 # 1/2 width and depth of world wwalls = 2*n",
"this world wwalls = width # width of walls wr = width/4.0 #",
"and visualisation - wall_reward : (float) reward for wall collision - distractors (Bool)",
"width : (int) width of the world - depth : (int) depth of",
"the world - hwalls : (int) heigh of walls - dwalls: (int) depth",
"texture=STONE2, block_type='brick', collision_reward = wall_reward) #left wall left_wall_block = model.add_block( (-nd, hwalls/2, 0,",
"default world texture_paths, world_info = _build_square_default_world(model, texture, width=width, depth=depth, hwalls=hwalls, dwalls=dwalls, wall_reward=wall_reward, distractors=distractors,",
"distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds a simple rectangle planar world with",
"middle wall model.add_block( (n/2, hwalls/2, -n/4, wwalls/2, hwalls, dwalls, 0.0, 0.0, 0.0), SAND,",
"and without \"from\" but doesn't work for the moment from gym_round_bot.envs import round_bot_model",
"os.path.dirname(__file__) + texture_visualisation distractors_texture_path = os.path.dirname(__file__) + texture_distractors texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path,",
"6, 2*nw, 0.0, 0.0, 0.0), GRASS, block_type='brick') # Build wall blocks with negative",
"round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0,",
"blocks with negative reward on collision #front wall back_wall_block = model.add_block( (0, hwalls/2,",
"goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds a simple rectangle planar world",
"trigger a change in the world when crossed ON / OFF #TRIGGER =",
"asked (slowing down the robot when crossed) model.add_block( (0, 0.3, 0, nd/2, 0,",
"add a trigger button that will trigger a change in the world when",
"wr width of reward area wwalls = width # get texture paths in",
"block_type='brick', collision_reward = wall_reward) if distractors: # add visual distractors on the groud",
"texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, ): \"\"\" Builds a simple rectangle planar",
"0), (0, 1), (0, 0)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1))",
"texture=START, block_type='start') return texture_paths, world_info def build_square_1wall_world(model, texture, robot_diameter=2, width=45, depth=45, hwalls=2, dwalls=2,",
"= width/2.0 # 1/2 width and depth of world wwalls = 2*n #",
"not matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1,",
"depth of the world - hwalls : (int) heigh of walls - dwalls:",
"round_bot_model.Block.tex_coords((2, 0), (2, 0), (2, 0)) BRICK2 = round_bot_model.Block.tex_coords((0, 2), (0, 2), (0,",
"nd = depth/2.0 # 1/2 depth of this world wr = width/3.0 #",
"= model.add_block( (0, -3, 0, 2*nd, 6, 2*nw, 0.0, 0.0, 0.0), GRASS, block_type='brick')",
"distractors : width_wall_distractors = wwalls/2 height_wall_distractors = hwalls*2/3 # distractor back_wall inner face",
"= round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1),",
"2*nw, 0.0, 0.0, 0.0), GRASS, block_type='brick') # Build wall blocks with negative reward",
"0.0), texture=BRICK, block_type='brick', collision_reward = wall_reward) #back wall front_wall_block = model.add_block( (0, hwalls/2,",
"asked # distractor ground block size_ground_distractor = n = min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock(",
"collision_reward = goal_reward, visible=visible_reward) # Build robot block, set initial height to bot_heigh/2",
"BRICK = round_bot_model.Block.tex_coords((2, 0), (2, 0), (2, 0)) BRICK2 = round_bot_model.Block.tex_coords((0, 2), (0,",
"1/2 width of this world nd = depth/2.0 # 1/2 depth of this",
"specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # Build reward block in the",
"here to avoid mutual imports ! import os def _texture_path(texture_bricks_name): \"\"\" Parameter ---------",
"round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1,",
"speed=distractors_speed) # wall distractors : width_wall_distractors = wwalls/2 height_wall_distractors = hwalls*2/3 # distractor",
"ground if asked (slowing down the robot when crossed) model.add_block( (0, 0.3, 0,",
"'/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name == 'colours': return '/textures/texture_colours.png'",
"round_bot_model.BoundingBoxBlock( (0, 0.1, 0), (2*n, 0, 2*n), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0,",
"\"\"\" # WARNING : don't fo (from round_bot_py import round_bot_model) here to avoid",
"down the robot when crossed) model.add_block( (0, 0.3, 0, nd/2, 0, nw/2, 0.0,",
"wwalls, 0.0, 0.0, 0.0), texture=STONE, block_type='brick', collision_reward = wall_reward) #right wall right_wall_block =",
"texture_bricks_name Raises ------ ValueError : raised if texture_bricks_name is unkwnonw \"\"\" if texture_bricks_name",
"collision #front wall back_wall_block = model.add_block( (0, hwalls/2, -nw, depth, hwalls, dwalls, 0.0,",
"ont the ground if asked (slowing down the robot when crossed) model.add_block( (0,",
"width of reward area # set robot specifications bot_radius = robot_diameter/2.0 bot_height =",
"0.0, 0.0), texture=BRICK, block_type='brick', collision_reward = wall_reward) #back wall front_wall_block = model.add_block( (0,",
"= round_bot_model.BoundingBoxBlock( (0, hwalls/2, -nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block(",
"+ texture_bricks robot_texture_path = os.path.dirname(__file__) + texture_robot visualisation_texture_path = os.path.dirname(__file__) + texture_visualisation distractors_texture_path",
"0, dwalls, hwalls, wwalls, 0.0, 0.0, 0.0), texture=BRICK2, block_type='brick', collision_reward = wall_reward) if",
"0.0, 0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox = front_wall_bb, speed=distractors_speed) # distractor left_wall inner face",
"texture_bricks_name, width=45, depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False,",
"gym_round_bot.envs import round_bot_model # create textures coordinates GRASS = round_bot_model.Block.tex_coords((1, 0), (0, 1),",
"(0, -3, 0, 2*nd, 6, 2*nw, 0.0, 0.0, 0.0), GRASS, block_type='brick') # Build",
"crossed ON / OFF #TRIGGER = round_bot_model.Block.tex_coords((1, 0), (1, 0), (1, 0)) model.add_block(",
"= model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward',",
"-nw+dwalls/2+0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors,",
"block_type='robot') # add starting areas (the height=0 of block does not matter here,",
"0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox = left_wall_bb, speed=distractors_speed) # distractor right_wall inner face",
"right_wall inner face block right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls),",
"block_type='reward', collision_reward = 1, visible_reward=visible_reward) # Build robot block, set initial height to",
"gym_round_bot.envs import round_bot_model BOT = round_bot_model.Block.tex_coords((0, 0), (0, 1), (0, 1)) START =",
"ground_bb = round_bot_model.BoundingBoxBlock( (0, 0.1, 0), (2*n, 0, 2*n), (0.0, 0.0, 0.0), linked_block=ground_block)",
"a trigger button that will trigger a change in the world when crossed",
"avoid mutual imports ! import os def _texture_path(texture_bricks_name): \"\"\" Parameter --------- texture_bricks_name :",
"<NAME> ISIR - CNRS / Sorbonne Université 02/2018 This file allows to build",
": (str) name of the texture for the bricks - width : (int)",
"world') def _build_square_default_world(model, texture_bricks_name, width=45, depth=45, hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False,",
"0.0, 0.0, 0.0), texture=START, block_type='start') return texture_paths, world_info def build_square_1wall_world(model, texture, robot_diameter=2, width=45,",
"= round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block(",
"(2, 1), (2, 1)) STONE2 = round_bot_model.Block.tex_coords((1, 2), (1, 2), (1, 2)) BUTTON",
"texture=DISTRACTORS[4], block_type='flat_distractor', boundingBox = right_wall_bb, speed=distractors_speed) if sandboxes : # add sandboxes ont",
"0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) model.add_block( components=(0, 0, 0, size_ground_distractor,",
"rew = model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD,",
"from gym_round_bot.envs import round_bot_model BOT = round_bot_model.Block.tex_coords((0, 0), (0, 1), (0, 1)) START",
"- distractors_speed (float) : speed of visual distractors displacement - sandboxes (Bool) :",
"1)) STONE2 = round_bot_model.Block.tex_coords((1, 2), (1, 2), (1, 2)) BUTTON = round_bot_model.Block.tex_coords((2, 2),",
"the robot when crossed) model.add_block( (0, 0.3, 0, nd/2, 0, nw/2, 0.0, 0.0,",
"0.0, 0.0), texture=BOT, block_type='robot') # add starting areas (the height=0 of block does",
"0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = goal_reward, visible=visible_reward) # Build robot block,",
"block_type='sandbox') if trigger_button : # add a trigger button that will trigger a",
"bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4,",
"wall_reward) #left wall left_wall_block = model.add_block( (-nd, hwalls/2, 0, dwalls, hwalls, wwalls, 0.0,",
"(0, 0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) nw",
"reward area # set robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius #",
"wall_reward=wall_reward, distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ## then add specs from gym_round_bot.envs import round_bot_model",
"wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = 1, visible_reward=visible_reward) # Build robot",
"# WARNING : don't fo (from round_bot_py import round_bot_model) here to avoid mutual",
"hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds the square",
"hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0,",
"hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds a simple",
"area wwalls = width # get texture paths in current directory brick_texture_path =",
"nd-dwalls/2-0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0,",
"create textures coordinates GRASS = round_bot_model.Block.tex_coords((1, 0), (0, 1), (0, 0)) SAND =",
"0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0],",
"texture_paths, world_info def build_square_1wall_world(model, texture, robot_diameter=2, width=45, depth=45, hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10, distractors=False,",
"loader and code worlds in .json \"\"\" # WARNING : don't fo (from",
"world with walls around Parameters ---------- - model : (round_bot_model.Model) model to load",
"[(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw = width/2.0 # 1/2 width of this world nd =",
"= round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block(",
"be defined) Returns ------- world information \"\"\" texture_bricks = _texture_path(texture_bricks_name) # TODO :",
"that will trigger a change in the environment (change to be defined) Returns",
"# add sandboxes ont the ground if asked (slowing down the robot when",
"world_info = { 'width' : 2*nw, 'depth' : 2*nd, } return texture_paths, world_info",
"a change in the environment (change to be defined) Returns ------- world information",
"reward block in the corner rew = model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0,",
"components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox =",
"#TRIGGER = round_bot_model.Block.tex_coords((1, 0), (1, 0), (1, 0)) model.add_block( (0, 0.3, 0, nw/3,",
"2*bot_radius, bot_height, 2*bot_radius, 0.0, 0.0, 0.0), texture=BOT, block_type='robot') # add starting areas (the",
"the middle \"\"\" ## first build default world texture_paths, world_info = _build_square_default_world(model, texture,",
"REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) nw = width/2.0 # 1/2",
"texture for the bricks - width : (int) width of the world -",
"walls wr = width/4.0 # wr width of reward area # set robot",
"texture_bricks_name is unkwnonw \"\"\" if texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name ==",
"(0, hwalls/2, nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=STONE2, block_type='brick', collision_reward =",
"bot_height/2.0+0.1, 0, 2*bot_radius, bot_height, 2*bot_radius, 0.0, 0.0, 0.0), texture=BOT, block_type='robot') # add starting",
"(0, 1)) nw = width/2.0 # 1/2 width of this world nd =",
"BUTTON = round_bot_model.Block.tex_coords((2, 2), (2, 2), (2, 2)) DISTRACTORS = [ round_bot_model.Block.tex_coords(t,t,t) for",
"-(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') return texture_paths,",
"hwalls=4, dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, ): \"\"\" Builds",
"import round_bot_model # create textures coordinates GRASS = round_bot_model.Block.tex_coords((1, 0), (0, 1), (0,",
"(from round_bot_py import round_bot_model) here to avoid mutual imports ! import os def",
"= wwalls/2 height_wall_distractors = hwalls*2/3 # distractor back_wall inner face block back_wall_bb =",
"0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[4],",
"distractors (Bool) : add visual distractors on walls and ground - distractors_speed (float)",
"allows to build worlds TODO : replace this file by a .json loader",
"\"\"\" Builds the square world \"\"\" ## first build default world texture_paths, world_info",
"depth of this world wwalls = width # width of walls wr =",
"0, hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0,",
"corner rew = model.add_block( (nd-(wr/2+dwalls/2), bot_height/2.0, -nw+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0),",
"= round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) n = width/2.0 # 1/2 width",
"Build reward block in the corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0, wr,",
"0.0), texture=DISTRACTORS[2], block_type='flat_distractor', boundingBox = front_wall_bb, speed=distractors_speed) # distractor left_wall inner face block",
"on the groud and inner faces of walls if asked # distractor ground",
"and 1 wall in the middle \"\"\" ## first build default world texture_paths,",
"of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START,",
"0.0, 0.0, 0.0), texture=STONE, block_type='brick', collision_reward = wall_reward) #right wall right_wall_block = model.add_block(",
"= round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) nw = width/2.0 # 1/2 width",
"texture, robot_diameter=2, width=45, depth=45, hwalls=2, dwalls=2, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False):",
": (float) reward for wall collision - distractors (Bool) : add visual distractors",
"sandboxes ont the ground (slowing down the robot when crossed) - trigger_button (Bool)",
"crossed) - trigger_button (Bool) : add a trigger button that will trigger a",
"dwalls, 0.0, 0.0, 0.0), texture=BRICK, block_type='brick', collision_reward = wall_reward) #back wall front_wall_block =",
"(str) name of the texture for the bricks - width : (int) width",
"wwalls = 2*n # width of walls wr = width/4.0 # wr width",
"the world when crossed ON / OFF #TRIGGER = round_bot_model.Block.tex_coords((1, 0), (1, 0),",
"0), (0, 0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1))",
"bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = goal_reward, visible=visible_reward) # Build",
"size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) # wall distractors",
"(0, hwalls/2, -nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=BRICK, block_type='brick', collision_reward =",
"coding: utf-8 -*- \"\"\" <NAME> ISIR - CNRS / Sorbonne Université 02/2018 This",
"0.0, 0.0), texture=STONE2, block_type='brick', collision_reward = wall_reward) #left wall left_wall_block = model.add_block( (-nd,",
"groud and inner faces of walls if asked # distractor ground block size_ground_distractor",
"collision model.add_block( (0, bot_height/2.0+0.1, 0, 2*bot_radius, bot_height, 2*bot_radius, 0.0, 0.0, 0.0), texture=BOT, block_type='robot')",
"Parameter --------- texture_bricks_name : str name of the world main texture Return ------",
"round_bot_model.Block.tex_coords((0, 0), (0, 0), (0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0,",
"world nd = depth/2.0 # 1/2 depth of this world wwalls = width",
"texture=START, block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0),",
"with negative reward on collision #front wall back_wall_block = model.add_block( (0, hwalls/2, -nw,",
"2*nw-2*dwalls, 0.0, 0.0, 0.0), texture=START, block_type='start') return texture_paths, world_info def build_square_1wall_world(model, texture, robot_diameter=2,",
"of visual distractors displacement - sandboxes (Bool) : add sandboxes ont the ground",
"visualisation_texture_path = os.path.dirname(__file__) + texture_visualisation distractors_texture_path = os.path.dirname(__file__) + texture_distractors texture_paths = {'brick':brick_texture_path,",
"= os.path.dirname(__file__) + texture_visualisation distractors_texture_path = os.path.dirname(__file__) + texture_distractors texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path,",
"(0, 0)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) BRICK = round_bot_model.Block.tex_coords((2,",
"global and without \"from\" but doesn't work for the moment from gym_round_bot.envs import",
"+ texture_visualisation distractors_texture_path = os.path.dirname(__file__) + texture_distractors texture_paths = {'brick':brick_texture_path, 'robot':robot_texture_path, 'visualisation':visualisation_texture_path, 'distractors':distractors_texture_path,",
"planar world with walls around, and 1 wall in the middle \"\"\" ##",
"/ OFF #TRIGGER = round_bot_model.Block.tex_coords((1, 0), (1, 0), (1, 0)) model.add_block( (0, 0.3,",
"0, 2*nd, 6, 2*nw, 0.0, 0.0, 0.0), GRASS, block_type='brick') # Build wall blocks",
"then add specs from gym_round_bot.envs import round_bot_model BOT = round_bot_model.Block.tex_coords((0, 0), (0, 1),",
"# distractor right_wall inner face block right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0), (0.0,",
"Builds the square world \"\"\" ## first build default world texture_paths, world_info =",
"# 1/2 width and depth of world wwalls = 2*n # width of",
"distractors=distractors, distractors_speed=distractors_speed, sandboxes=sandboxes, trigger_button=trigger_button,) ## then add specs from gym_round_bot.envs import round_bot_model BOT",
"width of this world nd = depth/2.0 # 1/2 depth of this world",
"(wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1,",
"(slowing down the robot when crossed) - trigger_button (Bool) : add a trigger",
"- depth : (int) depth of the world - hwalls : (int) heigh",
"depth of this world wr = width/3.0 # wr width of reward area",
"boundingBox = left_wall_bb, speed=distractors_speed) # distractor right_wall inner face block right_wall_bb = round_bot_model.BoundingBoxBlock((",
"1), (1, 1), (1, 1)) n = width/2.0 # 1/2 width and depth",
"collision_reward = 1, visible_reward=visible_reward) # Build robot block, set initial height to bot_heigh/2",
"world_info def build_square_world(model, texture, robot_diameter=2 ,width=45, depth=45, hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1,",
"dwalls=1, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds the square world",
"Parameters ---------- - model : (round_bot_model.Model) model to load world in - texture_bricks_name",
"-nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=BRICK, block_type='brick', collision_reward = wall_reward) #back",
"= round_bot_model.Block.tex_coords((1, 0), (0, 1), (0, 0)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1),",
"left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block)",
"paths for texture image of bricks, robot and visualisation - wall_reward : (float)",
"on collision #front wall back_wall_block = model.add_block( (0, hwalls/2, -nw, depth, hwalls, dwalls,",
"block does not matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, 0,",
"- hwalls : (int) heigh of walls - dwalls: (int) depth of walls",
": # add a trigger button that will trigger a change in the",
"in the middle \"\"\" ## first build default world texture_paths, world_info = _build_square_default_world(model,",
"\"\"\" if texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png'",
"0.3, 0, nw/3, 0.2, nw/3, 0.0, 0.0, 0.0), BUTTON, block_type='trigger_button') world_info = {",
"+ small offset to avoid ground collision model.add_block( (0, bot_height/2.0+0.1, 0, 2*bot_radius, bot_height,",
": speed of visual distractors displacement - sandboxes (Bool) : add sandboxes ont",
"ground_bb, speed=distractors_speed) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0],",
"face block front_wall_bb = round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0,",
"(0, 0)) REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) nw = width/2.0",
"0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) # wall distractors : width_wall_distractors",
"2*n), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0,",
"sandboxes=False, trigger_button=False, ): \"\"\" Builds a simple rectangle planar world with walls around",
"TODO : better import would be global and without \"from\" but doesn't work",
"linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor',",
"## first build default world texture_paths, world_info = _build_square_default_world(model, texture, width=width, depth=depth, hwalls=hwalls,",
"Build robot block, set initial height to bot_heigh/2 + small offset to avoid",
"collision_reward = -1) # Build reward block in the corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0,",
"This file allows to build worlds TODO : replace this file by a",
"texture paths in current directory brick_texture_path = os.path.dirname(__file__) + texture_bricks robot_texture_path = os.path.dirname(__file__)",
"block_type='flat_distractor', boundingBox = front_wall_bb, speed=distractors_speed) # distractor left_wall inner face block left_wall_bb =",
"## then add specs from gym_round_bot.envs import round_bot_model BOT = round_bot_model.Block.tex_coords((0, 0), (0,",
"nd = depth/2.0 # 1/2 depth of this world wwalls = width #",
"build worlds TODO : replace this file by a .json loader and code",
"when crossed) - trigger_button (Bool) : add a trigger button that will trigger",
"---------- - model : (round_bot_model.Model) model to load world in - texture_bricks_name :",
"return '/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name == 'colours': return",
"starting areas (the height=0 of block does not matter here, only area of",
"here, only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, 0, 2*nd-2*dwalls, 0.1, 2*nw-2*dwalls, 0.0,",
"specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # middle wall model.add_block( (n/2, hwalls/2,",
"inner face block left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0,",
"be global and without \"from\" but doesn't work for the moment from gym_round_bot.envs",
"and ground - distractors_speed (float) : speed of visual distractors displacement - sandboxes",
"0.0), GRASS, block_type='brick') # Build wall blocks with negative reward on collision #front",
"wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD, block_type='reward', collision_reward = goal_reward, visible=visible_reward) #",
"# set robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # Build reward",
"robot_diameter=2 ,width=45, depth=45, hwalls=4, dwalls=1, wall_reward=-1, goal_reward=10, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\"",
"for wall collision - distractors (Bool) : add visual distractors on walls and",
"the moment from gym_round_bot.envs import round_bot_model # create textures coordinates GRASS = round_bot_model.Block.tex_coords((1,",
"= os.path.dirname(__file__) + texture_robot visualisation_texture_path = os.path.dirname(__file__) + texture_visualisation distractors_texture_path = os.path.dirname(__file__) +",
"model.add_block( (0, hwalls/2, -nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=BRICK, block_type='brick', collision_reward",
"= width/3.0 # wr width of reward area wwalls = width # get",
"ground block size_ground_distractor = n = min(nw,nd) ground_bb = round_bot_model.BoundingBoxBlock( (0, 0.1, 0),",
"(slowing down the robot when crossed) model.add_block( (0, 0.3, 0, nd/2, 0, nw/2,",
"1)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) n = width/2.0 #",
"texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) # wall distractors : width_wall_distractors = wwalls/2",
"add visual distractors on the groud and inner faces of walls if asked",
"0.0, size_ground_distractor, 0.0, 0.0, 0.0), texture=DISTRACTORS[0], block_type='flat_distractor', boundingBox = ground_bb, speed=distractors_speed) model.add_block( components=(0,",
": (int) heigh of walls - dwalls: (int) depth of walls - texture_bricks,",
"distractor right_wall inner face block right_wall_bb = round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0), (0.0, height_wall_distractors,",
"round_bot_model.Block.tex_coords(t,t,t) for t in [(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(2,0)] ] nw = width/2.0 # 1/2 width of",
"unkwnonw \"\"\" if texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti': return",
"dwalls=1, texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, ): \"\"\" Builds a",
"block_type='start') return texture_paths, world_info def build_square_1wall_world(model, texture, robot_diameter=2, width=45, depth=45, hwalls=2, dwalls=2, wall_reward=-1,",
"0), (2*n, 0, 2*n), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, size_ground_distractor,",
"0.0, 0.0, 0.0), SAND, block_type='sandbox') if trigger_button : # add a trigger button",
"BUTTON, block_type='trigger_button') world_info = { 'width' : 2*nw, 'depth' : 2*nd, } return",
"of walls - texture_bricks, texture_robot, texture_visualisation : (string) paths for texture image of",
"0.0, 0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox = left_wall_bb, speed=distractors_speed) # distractor right_wall inner",
"moment from gym_round_bot.envs import round_bot_model # create textures coordinates GRASS = round_bot_model.Block.tex_coords((1, 0),",
"2), (0, 2), (0, 2)) STONE = round_bot_model.Block.tex_coords((2, 1), (2, 1), (2, 1))",
"'colours': return '/textures/texture_colours.png' else : raise ValueError('Unknown texture name '+ texture_bricks_name + '",
"world wwalls = 2*n # width of walls wr = width/4.0 # wr",
"(0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors,",
"model.add_block( components=(0, 0, 0, 0.0, height_wall_distractors, width_wall_distractors, 0.0, 0.0, 0.0), texture=DISTRACTORS[3], block_type='flat_distractor', boundingBox",
"fo (from round_bot_py import round_bot_model) here to avoid mutual imports ! import os",
"texture Return ------ texture_path: (str) path corresponding to the texture_bricks_name Raises ------ ValueError",
"round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) nw = width/2.0 # 1/2 width of",
"= width # width of walls wr = width/4.0 # wr width of",
"height=0 of block does not matter here, only area of (hwalls-2*dwalls)^2) model.add_block( (0,",
"areas (the height=0 of block does not matter here, only area of (hwalls-2*dwalls)^2)",
"robot when crossed) model.add_block( (0, 0.3, 0, nd/2, 0, nw/2, 0.0, 0.0, 0.0),",
"texture_bricks_name : (str) name of the texture for the bricks - width :",
"0)) BRICK2 = round_bot_model.Block.tex_coords((0, 2), (0, 2), (0, 2)) STONE = round_bot_model.Block.tex_coords((2, 1),",
"0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0,",
"front_wall_bb = round_bot_model.BoundingBoxBlock(( 0, hwalls/2, nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block)",
"os.path.dirname(__file__) + texture_bricks robot_texture_path = os.path.dirname(__file__) + texture_robot visualisation_texture_path = os.path.dirname(__file__) + texture_visualisation",
"imports ! import os def _texture_path(texture_bricks_name): \"\"\" Parameter --------- texture_bricks_name : str name",
"trigger_button=False, ): \"\"\" Builds a simple rectangle planar world with walls around Parameters",
"get texture paths in current directory brick_texture_path = os.path.dirname(__file__) + texture_bricks robot_texture_path =",
"distractors_speed=0.1, sandboxes=False, trigger_button=False, visible_reward=False): \"\"\" Builds a simple rectangle planar world with walls",
"0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors, height_wall_distractors, 0.0, 0.0, 0.0, 0.0), texture=DISTRACTORS[1],",
"front_wall_bb, speed=distractors_speed) # distractor left_wall inner face block left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1, hwalls/2,",
"(0, 1)) SAND = round_bot_model.Block.tex_coords((1, 1), (1, 1), (1, 1)) n = width/2.0",
"model.add_block( (0, hwalls/2, nw, depth, hwalls, dwalls, 0.0, 0.0, 0.0), texture=STONE2, block_type='brick', collision_reward",
"- texture_bricks_name : (str) name of the texture for the bricks - width",
"distractors on walls and ground - distractors_speed (float) : speed of visual distractors",
"round_bot_model.BoundingBoxBlock(( nd-dwalls/2-0.1, hwalls/2, 0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0,",
"only area of (hwalls-2*dwalls)^2) model.add_block( (0, bot_height/2.0+0.1, (wwalls-2*dwalls)/4, wwalls-2*dwalls, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0,",
"texture_robot='/textures/robot.png', texture_visualisation='/textures/visualisation.png', texture_distractors='/textures/texture_distractors.png', wall_reward=-1, distractors=False, distractors_speed=0.1, sandboxes=False, trigger_button=False, ): \"\"\" Builds a simple",
"visible_reward=False): \"\"\" Builds a simple rectangle planar world with walls around, and 1",
"the corner model.add_block( (n-(wr/2+dwalls/2), bot_height/2.0, -n+(wr/2+dwalls/2), wr, bot_height/3.0, wr, 0.0, 0.0, 0.0), texture=REWARD,",
"depth/2.0 # 1/2 depth of this world wr = width/3.0 # wr width",
"model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1, (wwalls-2*dwalls)/2, 0.0, 0.0, 0.0), texture=START, block_type='start')",
"] nw = width/2.0 # 1/2 width of this world nd = depth/2.0",
"depth of walls - texture_bricks, texture_robot, texture_visualisation : (string) paths for texture image",
"= front_wall_bb, speed=distractors_speed) # distractor left_wall inner face block left_wall_bb = round_bot_model.BoundingBoxBlock( (-nd+dwalls/2+0.1,",
"texture_bricks_name + ' in loading world') def _build_square_default_world(model, texture_bricks_name, width=45, depth=45, hwalls=4, dwalls=1,",
"0.0, 0.0, 0.0), SAND, block_type='brick', collision_reward = -1) # Build reward block in",
"right_wall_bb, speed=distractors_speed) if sandboxes : # add sandboxes ont the ground if asked",
"set robot specifications bot_radius = robot_diameter/2.0 bot_height = bot_radius # Build reward block",
"0.0, 0.0, 0.0), texture=START, block_type='start') model.add_block( ( -(wwalls-2*dwalls)/4, bot_height/2.0+0.1, -(wwalls-2*dwalls)/4, (wwalls-2*dwalls)/2, 0.1, (wwalls-2*dwalls)/2,",
"0.0), texture=BRICK2, block_type='brick', collision_reward = wall_reward) if distractors: # add visual distractors on",
"goal_reward, visible=visible_reward) # Build robot block, set initial height to bot_heigh/2 + small",
"0.0, 0.0), texture=DISTRACTORS[1], block_type='flat_distractor', boundingBox = back_wall_bb, speed=distractors_speed) # distractor front_wall inner face",
"nw-dwalls/2-0.1), (wwalls, height_wall_distractors, 0.0), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, width_wall_distractors,",
"1), (1, 1), (1, 1)) BRICK = round_bot_model.Block.tex_coords((2, 0), (2, 0), (2, 0))",
"STONE = round_bot_model.Block.tex_coords((2, 1), (2, 1), (2, 1)) STONE2 = round_bot_model.Block.tex_coords((1, 2), (1,",
"wall blocks with negative reward on collision #front wall back_wall_block = model.add_block( (0,",
"of walls if asked # distractor ground block size_ground_distractor = n = min(nw,nd)",
"boundingBox = ground_bb, speed=distractors_speed) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0,",
"= ground_bb, speed=distractors_speed) model.add_block( components=(0, 0, 0, size_ground_distractor, 0.0, size_ground_distractor, 0.0, 0.0, 0.0),",
"block_type='flat_distractor', boundingBox = back_wall_bb, speed=distractors_speed) # distractor front_wall inner face block front_wall_bb =",
"0), (0.0, height_wall_distractors, wwalls), (0.0, 0.0, 0.0), linked_block=ground_block) model.add_block( components=(0, 0, 0, 0.0,",
"REWARD = round_bot_model.Block.tex_coords((0, 1), (0, 1), (0, 1)) SAND = round_bot_model.Block.tex_coords((1, 1), (1,",
"(the height=0 of block does not matter here, only area of (hwalls-2*dwalls)^2) model.add_block(",
"wwalls/2, hwalls, dwalls, 0.0, 0.0, 0.0), SAND, block_type='brick', collision_reward = -1) # Build",
"of this world wr = width/3.0 # wr width of reward area wwalls"
] |
[
"supplied cache type name cannot be found. \"\"\" def get_cache(cfg): \"\"\" Attempt to",
"implement correctly. __slots__ = (\"cache\", \"max_age\", \"max_size\", \"queue\") clock = staticmethod(time.time) def __init__(self,",
"if cache_name == \"null\": logger.info(\"Caching deactivated\") return None for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if",
"The eviction queue contains # 2-tuples consisting of the time the item was",
"get(self, key): \"\"\" Pull a value from the cache corresponding to the key.",
"return None _, value = self.cache[key] # Force this onto the top of",
"cache. \"\"\" cutoff = self.clock() - self.max_age while len(self.queue) > 0: ts, key",
"None: response = whois_func(query) cache.set(query, response) else: logger.info(\"Cache hit for '%s'\", query) return",
"parameters %r\", cache_name, cfg) cache_type = ep.load() return cache_type(**cfg) raise UnknownCache(cache_name) def wrap_whois(cache,",
"the top of the queue. self.set(key, value) return value def set(self, key, value):",
"import time import pkg_resources logger = logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\" The supplied cache",
"Add `value` to the cache, to be referenced by `key`. \"\"\" if len(self.queue)",
"`value` to the cache, to be referenced by `key`. \"\"\" if len(self.queue) ==",
"= self.cache[key] else: counter = 0 self.cache[key] = (counter + 1, value) self.queue.append((self.clock(),",
"cache is somewhat more # awkward and involved to implement correctly. __slots__ =",
"value = self.cache[key] # Force this onto the top of the queue. self.set(key,",
"len(self.queue) > 0: ts, key = self.queue.popleft() if ts > cutoff: self.queue.appendleft((ts, key))",
"= cache.get(query) if response is None: response = whois_func(query) cache.set(query, response) else: logger.info(\"Cache",
"\"\"\" Attempt to remove the named item from the cache. \"\"\" counter, value",
"the eviction cache. \"\"\" _, key = self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self, key): \"\"\"",
"cache is None: return whois_func def wrapped(query): response = cache.get(query) if response is",
"\"\"\" _, key = self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self, key): \"\"\" Attempt to remove",
"cannot be found. \"\"\" def get_cache(cfg): \"\"\" Attempt to load the configured cache.",
"cache_name = cfg.pop(\"type\", \"null\") if cache_name == \"null\": logger.info(\"Caching deactivated\") return None for",
"is None: response = whois_func(query) cache.set(query, response) else: logger.info(\"Cache hit for '%s'\", query)",
"a value from the cache corresponding to the key. If no value exists,",
"= int(max_age) def evict_one(self): \"\"\" Remove the item at the head of the",
"time import pkg_resources logger = logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\" The supplied cache type",
"item at the head of the eviction cache. \"\"\" _, key = self.queue.popleft()",
"logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\" The supplied cache type name cannot be found. \"\"\"",
"Force this onto the top of the queue. self.set(key, value) return value def",
"this onto the top of the queue. self.set(key, value) return value def set(self,",
"self.clock() - self.max_age while len(self.queue) > 0: ts, key = self.queue.popleft() if ts",
"logger.info(\"Caching deactivated\") return None for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name == cache_name: logger.info(\"Using",
"return whois_func def wrapped(query): response = cache.get(query) if response is None: response =",
"\"max_size\", \"queue\") clock = staticmethod(time.time) def __init__(self, max_size=256, max_age=300): \"\"\" Create a new",
"wrap_whois(cache, whois_func): \"\"\" Wrap a WHOIS query function with a cache. \"\"\" if",
"cache if it turns out that's # more apt, but I haven't went",
"def evict_expired(self): \"\"\" Evict any items older than the maximum age from the",
"giving the number of times this item occurs on the eviction queue #",
"max_size int: Maximum number of entries the cache can contain. :param max_age int:",
"contains # 2-tuples consisting of the time the item was put into the",
"max_age int: Maximum number of seconds to consider an entry live. \"\"\" super(LFU,",
"no value exists, `None` is returned. \"\"\" self.evict_expired() if key not in self.cache:",
"be referenced by `key`. \"\"\" if len(self.queue) == self.max_size: self.evict_one() if key in",
"item occurs on the eviction queue # and the value. # # I",
"to remove the named item from the cache. \"\"\" counter, value = self.cache[key]",
"be found. \"\"\" def get_cache(cfg): \"\"\" Attempt to load the configured cache. \"\"\"",
"remove the named item from the cache. \"\"\" counter, value = self.cache[key] counter",
"whois_func def wrapped(query): response = cache.get(query) if response is None: response = whois_func(query)",
"if ts > cutoff: self.queue.appendleft((ts, key)) break self.attempt_eviction(key) def get(self, key): \"\"\" Pull",
"the named item from the cache. \"\"\" counter, value = self.cache[key] counter -=",
"\"\"\" cutoff = self.clock() - self.max_age while len(self.queue) > 0: ts, key =",
"is implemented as an LFU cache. The eviction queue contains # 2-tuples consisting",
"simple LFU cache. \"\"\" # This is implemented as an LFU cache. The",
"self.set(key, value) return value def set(self, key, value): \"\"\" Add `value` to the",
"%r\", cache_name, cfg) cache_type = ep.load() return cache_type(**cfg) raise UnknownCache(cache_name) def wrap_whois(cache, whois_func):",
"\"\"\" Pull a value from the cache corresponding to the key. If no",
"\"null\": logger.info(\"Caching deactivated\") return None for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name == cache_name:",
"LRU cache if it turns out that's # more apt, but I haven't",
"_, value = self.cache[key] # Force this onto the top of the queue.",
"in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name == cache_name: logger.info(\"Using cache '%s' with the parameters %r\",",
"self.evict_expired() if key not in self.cache: return None _, value = self.cache[key] #",
"the parameters %r\", cache_name, cfg) cache_type = ep.load() return cache_type(**cfg) raise UnknownCache(cache_name) def",
"class LFU(object): \"\"\" A simple LFU cache. \"\"\" # This is implemented as",
"# This is implemented as an LFU cache. The eviction queue contains #",
"an entry live. \"\"\" super(LFU, self).__init__() self.cache = {} self.queue = collections.deque() self.max_size",
"collections.deque() self.max_size = int(max_size) self.max_age = int(max_age) def evict_one(self): \"\"\" Remove the item",
"set(self, key, value): \"\"\" Add `value` to the cache, to be referenced by",
"Evict any items older than the maximum age from the cache. \"\"\" cutoff",
"a new LFU cache. :param max_size int: Maximum number of entries the cache",
"key. If no value exists, `None` is returned. \"\"\" self.evict_expired() if key not",
"counter, value = self.cache[key] counter -= 1 if counter == 0: del self.cache[key]",
"\"\"\" cache_name = cfg.pop(\"type\", \"null\") if cache_name == \"null\": logger.info(\"Caching deactivated\") return None",
"key)) break self.attempt_eviction(key) def get(self, key): \"\"\" Pull a value from the cache",
"key): \"\"\" Pull a value from the cache corresponding to the key. If",
"put into the cache and the # cache key. The cache maps cache",
"response is None: response = whois_func(query) cache.set(query, response) else: logger.info(\"Cache hit for '%s'\",",
"involved to implement correctly. __slots__ = (\"cache\", \"max_age\", \"max_size\", \"queue\") clock = staticmethod(time.time)",
"# awkward and involved to implement correctly. __slots__ = (\"cache\", \"max_age\", \"max_size\", \"queue\")",
"onto the top of the queue. self.set(key, value) return value def set(self, key,",
"eviction queue # and the value. # # I may end up reimplementing",
"Maximum number of seconds to consider an entry live. \"\"\" super(LFU, self).__init__() self.cache",
"'%s' with the parameters %r\", cache_name, cfg) cache_type = ep.load() return cache_type(**cfg) raise",
"attempt_eviction(self, key): \"\"\" Attempt to remove the named item from the cache. \"\"\"",
"self.cache[key] else: counter = 0 self.cache[key] = (counter + 1, value) self.queue.append((self.clock(), key))",
"from the cache. \"\"\" cutoff = self.clock() - self.max_age while len(self.queue) > 0:",
"not in self.cache: return None _, value = self.cache[key] # Force this onto",
"evict_expired(self): \"\"\" Evict any items older than the maximum age from the cache.",
"self.max_size = int(max_size) self.max_age = int(max_age) def evict_one(self): \"\"\" Remove the item at",
"logger = logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\" The supplied cache type name cannot be",
"cache type name cannot be found. \"\"\" def get_cache(cfg): \"\"\" Attempt to load",
"\"\"\" Create a new LFU cache. :param max_size int: Maximum number of entries",
"_ = self.cache[key] else: counter = 0 self.cache[key] = (counter + 1, value)",
"the value. # # I may end up reimplementing this as an LRU",
"(counter, value) def evict_expired(self): \"\"\" Evict any items older than the maximum age",
"_, key = self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self, key): \"\"\" Attempt to remove the",
"number of seconds to consider an entry live. \"\"\" super(LFU, self).__init__() self.cache =",
"-= 1 if counter == 0: del self.cache[key] else: self.cache[key] = (counter, value)",
"UnknownCache(cache_name) def wrap_whois(cache, whois_func): \"\"\" Wrap a WHOIS query function with a cache.",
"number of entries the cache can contain. :param max_age int: Maximum number of",
":param max_age int: Maximum number of seconds to consider an entry live. \"\"\"",
"logging import time import pkg_resources logger = logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\" The supplied",
"return wrapped # pylint: disable-msg=R0924 class LFU(object): \"\"\" A simple LFU cache. \"\"\"",
"wrapped(query): response = cache.get(query) if response is None: response = whois_func(query) cache.set(query, response)",
"evict_one(self): \"\"\" Remove the item at the head of the eviction cache. \"\"\"",
"is returned. \"\"\" self.evict_expired() if key not in self.cache: return None _, value",
"self.cache: return None _, value = self.cache[key] # Force this onto the top",
"A simple LFU cache. \"\"\" # This is implemented as an LFU cache.",
"cache keys onto 2-tuples consisting of a # counter giving the number of",
"number of times this item occurs on the eviction queue # and the",
"to load the configured cache. \"\"\" cache_name = cfg.pop(\"type\", \"null\") if cache_name ==",
"the head of the eviction cache. \"\"\" _, key = self.queue.popleft() self.attempt_eviction(key) def",
"name cannot be found. \"\"\" def get_cache(cfg): \"\"\" Attempt to load the configured",
"consisting of the time the item was put into the cache and the",
"from the cache. \"\"\" counter, value = self.cache[key] counter -= 1 if counter",
"ep.name == cache_name: logger.info(\"Using cache '%s' with the parameters %r\", cache_name, cfg) cache_type",
"item was put into the cache and the # cache key. The cache",
"a cache. \"\"\" if cache is None: return whois_func def wrapped(query): response =",
"response = whois_func(query) cache.set(query, response) else: logger.info(\"Cache hit for '%s'\", query) return response",
"with the parameters %r\", cache_name, cfg) cache_type = ep.load() return cache_type(**cfg) raise UnknownCache(cache_name)",
"= int(max_size) self.max_age = int(max_age) def evict_one(self): \"\"\" Remove the item at the",
"if counter == 0: del self.cache[key] else: self.cache[key] = (counter, value) def evict_expired(self):",
"is None: return whois_func def wrapped(query): response = cache.get(query) if response is None:",
"counter -= 1 if counter == 0: del self.cache[key] else: self.cache[key] = (counter,",
"raise UnknownCache(cache_name) def wrap_whois(cache, whois_func): \"\"\" Wrap a WHOIS query function with a",
"value. # # I may end up reimplementing this as an LRU cache",
"def attempt_eviction(self, key): \"\"\" Attempt to remove the named item from the cache.",
"LFU cache. :param max_size int: Maximum number of entries the cache can contain.",
"int(max_age) def evict_one(self): \"\"\" Remove the item at the head of the eviction",
"self.cache[key] # Force this onto the top of the queue. self.set(key, value) return",
"if ep.name == cache_name: logger.info(\"Using cache '%s' with the parameters %r\", cache_name, cfg)",
"key in self.cache: counter, _ = self.cache[key] else: counter = 0 self.cache[key] =",
"def wrapped(query): response = cache.get(query) if response is None: response = whois_func(query) cache.set(query,",
"\"\"\" def get_cache(cfg): \"\"\" Attempt to load the configured cache. \"\"\" cache_name =",
"ep.load() return cache_type(**cfg) raise UnknownCache(cache_name) def wrap_whois(cache, whois_func): \"\"\" Wrap a WHOIS query",
"> 0: ts, key = self.queue.popleft() if ts > cutoff: self.queue.appendleft((ts, key)) break",
"as an LFU cache. The eviction queue contains # 2-tuples consisting of the",
"cache_name == \"null\": logger.info(\"Caching deactivated\") return None for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name",
"was put into the cache and the # cache key. The cache maps",
"\"\"\" Caching support. \"\"\" import collections import logging import time import pkg_resources logger",
"query function with a cache. \"\"\" if cache is None: return whois_func def",
"LFU cache. \"\"\" # This is implemented as an LFU cache. The eviction",
"the cache. \"\"\" counter, value = self.cache[key] counter -= 1 if counter ==",
"whois_func(query) cache.set(query, response) else: logger.info(\"Cache hit for '%s'\", query) return response return wrapped",
"eviction cache. \"\"\" _, key = self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self, key): \"\"\" Attempt",
"but I haven't went that route as an LRU cache is somewhat more",
"\"\"\" Evict any items older than the maximum age from the cache. \"\"\"",
"__slots__ = (\"cache\", \"max_age\", \"max_size\", \"queue\") clock = staticmethod(time.time) def __init__(self, max_size=256, max_age=300):",
"onto 2-tuples consisting of a # counter giving the number of times this",
"If no value exists, `None` is returned. \"\"\" self.evict_expired() if key not in",
"top of the queue. self.set(key, value) return value def set(self, key, value): \"\"\"",
"\"\"\" if cache is None: return whois_func def wrapped(query): response = cache.get(query) if",
"== self.max_size: self.evict_one() if key in self.cache: counter, _ = self.cache[key] else: counter",
"The cache maps cache keys onto 2-tuples consisting of a # counter giving",
"self.queue.popleft() if ts > cutoff: self.queue.appendleft((ts, key)) break self.attempt_eviction(key) def get(self, key): \"\"\"",
"turns out that's # more apt, but I haven't went that route as",
"counter giving the number of times this item occurs on the eviction queue",
"\"max_age\", \"max_size\", \"queue\") clock = staticmethod(time.time) def __init__(self, max_size=256, max_age=300): \"\"\" Create a",
"response = cache.get(query) if response is None: response = whois_func(query) cache.set(query, response) else:",
"key. The cache maps cache keys onto 2-tuples consisting of a # counter",
"{} self.queue = collections.deque() self.max_size = int(max_size) self.max_age = int(max_age) def evict_one(self): \"\"\"",
"# Force this onto the top of the queue. self.set(key, value) return value",
"def get(self, key): \"\"\" Pull a value from the cache corresponding to the",
"item from the cache. \"\"\" counter, value = self.cache[key] counter -= 1 if",
"\"\"\" Attempt to load the configured cache. \"\"\" cache_name = cfg.pop(\"type\", \"null\") if",
"out that's # more apt, but I haven't went that route as an",
"cache maps cache keys onto 2-tuples consisting of a # counter giving the",
"value) return value def set(self, key, value): \"\"\" Add `value` to the cache,",
"more apt, but I haven't went that route as an LRU cache is",
"the number of times this item occurs on the eviction queue # and",
"# counter giving the number of times this item occurs on the eviction",
"Maximum number of entries the cache can contain. :param max_age int: Maximum number",
"the time the item was put into the cache and the # cache",
"<gh_stars>10-100 \"\"\" Caching support. \"\"\" import collections import logging import time import pkg_resources",
"cutoff: self.queue.appendleft((ts, key)) break self.attempt_eviction(key) def get(self, key): \"\"\" Pull a value from",
"in self.cache: counter, _ = self.cache[key] else: counter = 0 self.cache[key] = (counter",
"= {} self.queue = collections.deque() self.max_size = int(max_size) self.max_age = int(max_age) def evict_one(self):",
"older than the maximum age from the cache. \"\"\" cutoff = self.clock() -",
"== 0: del self.cache[key] else: self.cache[key] = (counter, value) def evict_expired(self): \"\"\" Evict",
"self.cache = {} self.queue = collections.deque() self.max_size = int(max_size) self.max_age = int(max_age) def",
"= cfg.pop(\"type\", \"null\") if cache_name == \"null\": logger.info(\"Caching deactivated\") return None for ep",
"time the item was put into the cache and the # cache key.",
"self.max_age = int(max_age) def evict_one(self): \"\"\" Remove the item at the head of",
":param max_size int: Maximum number of entries the cache can contain. :param max_age",
"and the # cache key. The cache maps cache keys onto 2-tuples consisting",
"'%s'\", query) return response return wrapped # pylint: disable-msg=R0924 class LFU(object): \"\"\" A",
"self.attempt_eviction(key) def get(self, key): \"\"\" Pull a value from the cache corresponding to",
"went that route as an LRU cache is somewhat more # awkward and",
"key = self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self, key): \"\"\" Attempt to remove the named",
"correctly. __slots__ = (\"cache\", \"max_age\", \"max_size\", \"queue\") clock = staticmethod(time.time) def __init__(self, max_size=256,",
"to consider an entry live. \"\"\" super(LFU, self).__init__() self.cache = {} self.queue =",
"0: del self.cache[key] else: self.cache[key] = (counter, value) def evict_expired(self): \"\"\" Evict any",
"\"\"\" super(LFU, self).__init__() self.cache = {} self.queue = collections.deque() self.max_size = int(max_size) self.max_age",
"collections import logging import time import pkg_resources logger = logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\"",
"the cache can contain. :param max_age int: Maximum number of seconds to consider",
"= self.cache[key] counter -= 1 if counter == 0: del self.cache[key] else: self.cache[key]",
"to implement correctly. __slots__ = (\"cache\", \"max_age\", \"max_size\", \"queue\") clock = staticmethod(time.time) def",
"at the head of the eviction cache. \"\"\" _, key = self.queue.popleft() self.attempt_eviction(key)",
"returned. \"\"\" self.evict_expired() if key not in self.cache: return None _, value =",
"None for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name == cache_name: logger.info(\"Using cache '%s' with",
"of the eviction cache. \"\"\" _, key = self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self, key):",
"to be referenced by `key`. \"\"\" if len(self.queue) == self.max_size: self.evict_one() if key",
"\"\"\" Wrap a WHOIS query function with a cache. \"\"\" if cache is",
"def set(self, key, value): \"\"\" Add `value` to the cache, to be referenced",
"an LFU cache. The eviction queue contains # 2-tuples consisting of the time",
"value = self.cache[key] counter -= 1 if counter == 0: del self.cache[key] else:",
"deactivated\") return None for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name == cache_name: logger.info(\"Using cache",
"LRU cache is somewhat more # awkward and involved to implement correctly. __slots__",
"ts, key = self.queue.popleft() if ts > cutoff: self.queue.appendleft((ts, key)) break self.attempt_eviction(key) def",
"- self.max_age while len(self.queue) > 0: ts, key = self.queue.popleft() if ts >",
"age from the cache. \"\"\" cutoff = self.clock() - self.max_age while len(self.queue) >",
"self.cache[key] else: self.cache[key] = (counter, value) def evict_expired(self): \"\"\" Evict any items older",
"cache. \"\"\" cache_name = cfg.pop(\"type\", \"null\") if cache_name == \"null\": logger.info(\"Caching deactivated\") return",
"self.cache[key] counter -= 1 if counter == 0: del self.cache[key] else: self.cache[key] =",
"the cache corresponding to the key. If no value exists, `None` is returned.",
"if key not in self.cache: return None _, value = self.cache[key] # Force",
"def wrap_whois(cache, whois_func): \"\"\" Wrap a WHOIS query function with a cache. \"\"\"",
"key = self.queue.popleft() if ts > cutoff: self.queue.appendleft((ts, key)) break self.attempt_eviction(key) def get(self,",
"if it turns out that's # more apt, but I haven't went that",
"# # I may end up reimplementing this as an LRU cache if",
"configured cache. \"\"\" cache_name = cfg.pop(\"type\", \"null\") if cache_name == \"null\": logger.info(\"Caching deactivated\")",
"cache, to be referenced by `key`. \"\"\" if len(self.queue) == self.max_size: self.evict_one() if",
"if len(self.queue) == self.max_size: self.evict_one() if key in self.cache: counter, _ = self.cache[key]",
"cache '%s' with the parameters %r\", cache_name, cfg) cache_type = ep.load() return cache_type(**cfg)",
"self.attempt_eviction(key) def attempt_eviction(self, key): \"\"\" Attempt to remove the named item from the",
"named item from the cache. \"\"\" counter, value = self.cache[key] counter -= 1",
"value def set(self, key, value): \"\"\" Add `value` to the cache, to be",
"\"\"\" Add `value` to the cache, to be referenced by `key`. \"\"\" if",
"1 if counter == 0: del self.cache[key] else: self.cache[key] = (counter, value) def",
"== \"null\": logger.info(\"Caching deactivated\") return None for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name ==",
"class UnknownCache(Exception): \"\"\" The supplied cache type name cannot be found. \"\"\" def",
"cutoff = self.clock() - self.max_age while len(self.queue) > 0: ts, key = self.queue.popleft()",
"disable-msg=R0924 class LFU(object): \"\"\" A simple LFU cache. \"\"\" # This is implemented",
"the maximum age from the cache. \"\"\" cutoff = self.clock() - self.max_age while",
"def __init__(self, max_size=256, max_age=300): \"\"\" Create a new LFU cache. :param max_size int:",
"found. \"\"\" def get_cache(cfg): \"\"\" Attempt to load the configured cache. \"\"\" cache_name",
"the item was put into the cache and the # cache key. The",
"pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name == cache_name: logger.info(\"Using cache '%s' with the parameters %r\", cache_name,",
"value): \"\"\" Add `value` to the cache, to be referenced by `key`. \"\"\"",
"live. \"\"\" super(LFU, self).__init__() self.cache = {} self.queue = collections.deque() self.max_size = int(max_size)",
"break self.attempt_eviction(key) def get(self, key): \"\"\" Pull a value from the cache corresponding",
"consisting of a # counter giving the number of times this item occurs",
"as an LRU cache if it turns out that's # more apt, but",
"Pull a value from the cache corresponding to the key. If no value",
"for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name == cache_name: logger.info(\"Using cache '%s' with the",
"this as an LRU cache if it turns out that's # more apt,",
"max_age=300): \"\"\" Create a new LFU cache. :param max_size int: Maximum number of",
"into the cache and the # cache key. The cache maps cache keys",
"self.cache[key] = (counter, value) def evict_expired(self): \"\"\" Evict any items older than the",
"more # awkward and involved to implement correctly. __slots__ = (\"cache\", \"max_age\", \"max_size\",",
"staticmethod(time.time) def __init__(self, max_size=256, max_age=300): \"\"\" Create a new LFU cache. :param max_size",
"with a cache. \"\"\" if cache is None: return whois_func def wrapped(query): response",
"get_cache(cfg): \"\"\" Attempt to load the configured cache. \"\"\" cache_name = cfg.pop(\"type\", \"null\")",
"wrapped # pylint: disable-msg=R0924 class LFU(object): \"\"\" A simple LFU cache. \"\"\" #",
"int: Maximum number of seconds to consider an entry live. \"\"\" super(LFU, self).__init__()",
"counter == 0: del self.cache[key] else: self.cache[key] = (counter, value) def evict_expired(self): \"\"\"",
"contain. :param max_age int: Maximum number of seconds to consider an entry live.",
"return value def set(self, key, value): \"\"\" Add `value` to the cache, to",
"super(LFU, self).__init__() self.cache = {} self.queue = collections.deque() self.max_size = int(max_size) self.max_age =",
"\"\"\" self.evict_expired() if key not in self.cache: return None _, value = self.cache[key]",
"than the maximum age from the cache. \"\"\" cutoff = self.clock() - self.max_age",
"None: return whois_func def wrapped(query): response = cache.get(query) if response is None: response",
"clock = staticmethod(time.time) def __init__(self, max_size=256, max_age=300): \"\"\" Create a new LFU cache.",
"up reimplementing this as an LRU cache if it turns out that's #",
"\"\"\" counter, value = self.cache[key] counter -= 1 if counter == 0: del",
"= self.cache[key] # Force this onto the top of the queue. self.set(key, value)",
"keys onto 2-tuples consisting of a # counter giving the number of times",
"of seconds to consider an entry live. \"\"\" super(LFU, self).__init__() self.cache = {}",
"that route as an LRU cache is somewhat more # awkward and involved",
"Caching support. \"\"\" import collections import logging import time import pkg_resources logger =",
"queue contains # 2-tuples consisting of the time the item was put into",
"value exists, `None` is returned. \"\"\" self.evict_expired() if key not in self.cache: return",
"# and the value. # # I may end up reimplementing this as",
"= (counter, value) def evict_expired(self): \"\"\" Evict any items older than the maximum",
"cache corresponding to the key. If no value exists, `None` is returned. \"\"\"",
"self.max_age while len(self.queue) > 0: ts, key = self.queue.popleft() if ts > cutoff:",
"query) return response return wrapped # pylint: disable-msg=R0924 class LFU(object): \"\"\" A simple",
"I haven't went that route as an LRU cache is somewhat more #",
"== cache_name: logger.info(\"Using cache '%s' with the parameters %r\", cache_name, cfg) cache_type =",
"whois_func): \"\"\" Wrap a WHOIS query function with a cache. \"\"\" if cache",
"self.queue = collections.deque() self.max_size = int(max_size) self.max_age = int(max_age) def evict_one(self): \"\"\" Remove",
"hit for '%s'\", query) return response return wrapped # pylint: disable-msg=R0924 class LFU(object):",
"# pylint: disable-msg=R0924 class LFU(object): \"\"\" A simple LFU cache. \"\"\" # This",
"len(self.queue) == self.max_size: self.evict_one() if key in self.cache: counter, _ = self.cache[key] else:",
"that's # more apt, but I haven't went that route as an LRU",
"and the value. # # I may end up reimplementing this as an",
"max_size=256, max_age=300): \"\"\" Create a new LFU cache. :param max_size int: Maximum number",
"self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self, key): \"\"\" Attempt to remove the named item from",
"cache. \"\"\" counter, value = self.cache[key] counter -= 1 if counter == 0:",
"cache. The eviction queue contains # 2-tuples consisting of the time the item",
"cache can contain. :param max_age int: Maximum number of seconds to consider an",
"= self.queue.popleft() if ts > cutoff: self.queue.appendleft((ts, key)) break self.attempt_eviction(key) def get(self, key):",
"an LRU cache is somewhat more # awkward and involved to implement correctly.",
"referenced by `key`. \"\"\" if len(self.queue) == self.max_size: self.evict_one() if key in self.cache:",
"exists, `None` is returned. \"\"\" self.evict_expired() if key not in self.cache: return None",
"haven't went that route as an LRU cache is somewhat more # awkward",
"cache. \"\"\" _, key = self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self, key): \"\"\" Attempt to",
"pkg_resources logger = logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\" The supplied cache type name cannot",
"while len(self.queue) > 0: ts, key = self.queue.popleft() if ts > cutoff: self.queue.appendleft((ts,",
"# more apt, but I haven't went that route as an LRU cache",
"items older than the maximum age from the cache. \"\"\" cutoff = self.clock()",
"Attempt to load the configured cache. \"\"\" cache_name = cfg.pop(\"type\", \"null\") if cache_name",
"value from the cache corresponding to the key. If no value exists, `None`",
"the key. If no value exists, `None` is returned. \"\"\" self.evict_expired() if key",
"the cache, to be referenced by `key`. \"\"\" if len(self.queue) == self.max_size: self.evict_one()",
"= collections.deque() self.max_size = int(max_size) self.max_age = int(max_age) def evict_one(self): \"\"\" Remove the",
"pylint: disable-msg=R0924 class LFU(object): \"\"\" A simple LFU cache. \"\"\" # This is",
"implemented as an LFU cache. The eviction queue contains # 2-tuples consisting of",
"LFU(object): \"\"\" A simple LFU cache. \"\"\" # This is implemented as an",
"cache_type = ep.load() return cache_type(**cfg) raise UnknownCache(cache_name) def wrap_whois(cache, whois_func): \"\"\" Wrap a",
"maps cache keys onto 2-tuples consisting of a # counter giving the number",
"cfg.pop(\"type\", \"null\") if cache_name == \"null\": logger.info(\"Caching deactivated\") return None for ep in",
"the item at the head of the eviction cache. \"\"\" _, key =",
"queue. self.set(key, value) return value def set(self, key, value): \"\"\" Add `value` to",
"self.evict_one() if key in self.cache: counter, _ = self.cache[key] else: counter = 0",
"UnknownCache(Exception): \"\"\" The supplied cache type name cannot be found. \"\"\" def get_cache(cfg):",
"key, value): \"\"\" Add `value` to the cache, to be referenced by `key`.",
"2-tuples consisting of the time the item was put into the cache and",
"any items older than the maximum age from the cache. \"\"\" cutoff =",
"The supplied cache type name cannot be found. \"\"\" def get_cache(cfg): \"\"\" Attempt",
"load the configured cache. \"\"\" cache_name = cfg.pop(\"type\", \"null\") if cache_name == \"null\":",
"of the queue. self.set(key, value) return value def set(self, key, value): \"\"\" Add",
"occurs on the eviction queue # and the value. # # I may",
"if response is None: response = whois_func(query) cache.set(query, response) else: logger.info(\"Cache hit for",
"= self.clock() - self.max_age while len(self.queue) > 0: ts, key = self.queue.popleft() if",
"by `key`. \"\"\" if len(self.queue) == self.max_size: self.evict_one() if key in self.cache: counter,",
"function with a cache. \"\"\" if cache is None: return whois_func def wrapped(query):",
"the cache and the # cache key. The cache maps cache keys onto",
"and involved to implement correctly. __slots__ = (\"cache\", \"max_age\", \"max_size\", \"queue\") clock =",
"cache.get(query) if response is None: response = whois_func(query) cache.set(query, response) else: logger.info(\"Cache hit",
"the queue. self.set(key, value) return value def set(self, key, value): \"\"\" Add `value`",
"cache. \"\"\" # This is implemented as an LFU cache. The eviction queue",
"consider an entry live. \"\"\" super(LFU, self).__init__() self.cache = {} self.queue = collections.deque()",
"cfg) cache_type = ep.load() return cache_type(**cfg) raise UnknownCache(cache_name) def wrap_whois(cache, whois_func): \"\"\" Wrap",
"def evict_one(self): \"\"\" Remove the item at the head of the eviction cache.",
"of entries the cache can contain. :param max_age int: Maximum number of seconds",
"Create a new LFU cache. :param max_size int: Maximum number of entries the",
"route as an LRU cache is somewhat more # awkward and involved to",
"None _, value = self.cache[key] # Force this onto the top of the",
"on the eviction queue # and the value. # # I may end",
"self.max_size: self.evict_one() if key in self.cache: counter, _ = self.cache[key] else: counter =",
"it turns out that's # more apt, but I haven't went that route",
"Wrap a WHOIS query function with a cache. \"\"\" if cache is None:",
"import logging import time import pkg_resources logger = logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\" The",
"# 2-tuples consisting of the time the item was put into the cache",
"corresponding to the key. If no value exists, `None` is returned. \"\"\" self.evict_expired()",
"end up reimplementing this as an LRU cache if it turns out that's",
"type name cannot be found. \"\"\" def get_cache(cfg): \"\"\" Attempt to load the",
"= ep.load() return cache_type(**cfg) raise UnknownCache(cache_name) def wrap_whois(cache, whois_func): \"\"\" Wrap a WHOIS",
"key): \"\"\" Attempt to remove the named item from the cache. \"\"\" counter,",
"awkward and involved to implement correctly. __slots__ = (\"cache\", \"max_age\", \"max_size\", \"queue\") clock",
"self.cache: counter, _ = self.cache[key] else: counter = 0 self.cache[key] = (counter +",
"a # counter giving the number of times this item occurs on the",
"self.queue.appendleft((ts, key)) break self.attempt_eviction(key) def get(self, key): \"\"\" Pull a value from the",
"I may end up reimplementing this as an LRU cache if it turns",
"may end up reimplementing this as an LRU cache if it turns out",
"= (\"cache\", \"max_age\", \"max_size\", \"queue\") clock = staticmethod(time.time) def __init__(self, max_size=256, max_age=300): \"\"\"",
"2-tuples consisting of a # counter giving the number of times this item",
"apt, but I haven't went that route as an LRU cache is somewhat",
"return response return wrapped # pylint: disable-msg=R0924 class LFU(object): \"\"\" A simple LFU",
"LFU cache. The eviction queue contains # 2-tuples consisting of the time the",
"= logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\" The supplied cache type name cannot be found.",
"this item occurs on the eviction queue # and the value. # #",
"somewhat more # awkward and involved to implement correctly. __slots__ = (\"cache\", \"max_age\",",
"0: ts, key = self.queue.popleft() if ts > cutoff: self.queue.appendleft((ts, key)) break self.attempt_eviction(key)",
"to the cache, to be referenced by `key`. \"\"\" if len(self.queue) == self.max_size:",
"if cache is None: return whois_func def wrapped(query): response = cache.get(query) if response",
"ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name == cache_name: logger.info(\"Using cache '%s' with the parameters",
"cache and the # cache key. The cache maps cache keys onto 2-tuples",
"logger.info(\"Using cache '%s' with the parameters %r\", cache_name, cfg) cache_type = ep.load() return",
"\"\"\" if len(self.queue) == self.max_size: self.evict_one() if key in self.cache: counter, _ =",
"Remove the item at the head of the eviction cache. \"\"\" _, key",
"\"\"\" Remove the item at the head of the eviction cache. \"\"\" _,",
"in self.cache: return None _, value = self.cache[key] # Force this onto the",
"`key`. \"\"\" if len(self.queue) == self.max_size: self.evict_one() if key in self.cache: counter, _",
"\"\"\" # This is implemented as an LFU cache. The eviction queue contains",
"cache. \"\"\" if cache is None: return whois_func def wrapped(query): response = cache.get(query)",
"else: logger.info(\"Cache hit for '%s'\", query) return response return wrapped # pylint: disable-msg=R0924",
"is somewhat more # awkward and involved to implement correctly. __slots__ = (\"cache\",",
"if key in self.cache: counter, _ = self.cache[key] else: counter = 0 self.cache[key]",
"cache_name: logger.info(\"Using cache '%s' with the parameters %r\", cache_name, cfg) cache_type = ep.load()",
"cache key. The cache maps cache keys onto 2-tuples consisting of a #",
"WHOIS query function with a cache. \"\"\" if cache is None: return whois_func",
"the # cache key. The cache maps cache keys onto 2-tuples consisting of",
"key not in self.cache: return None _, value = self.cache[key] # Force this",
"import collections import logging import time import pkg_resources logger = logging.getLogger(\"uwhoisd\") class UnknownCache(Exception):",
"an LRU cache if it turns out that's # more apt, but I",
"cache.set(query, response) else: logger.info(\"Cache hit for '%s'\", query) return response return wrapped #",
"reimplementing this as an LRU cache if it turns out that's # more",
"support. \"\"\" import collections import logging import time import pkg_resources logger = logging.getLogger(\"uwhoisd\")",
"__init__(self, max_size=256, max_age=300): \"\"\" Create a new LFU cache. :param max_size int: Maximum",
"counter, _ = self.cache[key] else: counter = 0 self.cache[key] = (counter + 1,",
"a WHOIS query function with a cache. \"\"\" if cache is None: return",
"This is implemented as an LFU cache. The eviction queue contains # 2-tuples",
"else: self.cache[key] = (counter, value) def evict_expired(self): \"\"\" Evict any items older than",
"cache_type(**cfg) raise UnknownCache(cache_name) def wrap_whois(cache, whois_func): \"\"\" Wrap a WHOIS query function with",
"(\"cache\", \"max_age\", \"max_size\", \"queue\") clock = staticmethod(time.time) def __init__(self, max_size=256, max_age=300): \"\"\" Create",
"times this item occurs on the eviction queue # and the value. #",
"`None` is returned. \"\"\" self.evict_expired() if key not in self.cache: return None _,",
"= whois_func(query) cache.set(query, response) else: logger.info(\"Cache hit for '%s'\", query) return response return",
"maximum age from the cache. \"\"\" cutoff = self.clock() - self.max_age while len(self.queue)",
"entry live. \"\"\" super(LFU, self).__init__() self.cache = {} self.queue = collections.deque() self.max_size =",
"head of the eviction cache. \"\"\" _, key = self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self,",
"= self.queue.popleft() self.attempt_eviction(key) def attempt_eviction(self, key): \"\"\" Attempt to remove the named item",
"of a # counter giving the number of times this item occurs on",
"\"\"\" import collections import logging import time import pkg_resources logger = logging.getLogger(\"uwhoisd\") class",
"# I may end up reimplementing this as an LRU cache if it",
"int(max_size) self.max_age = int(max_age) def evict_one(self): \"\"\" Remove the item at the head",
"entries the cache can contain. :param max_age int: Maximum number of seconds to",
"as an LRU cache is somewhat more # awkward and involved to implement",
"the eviction queue # and the value. # # I may end up",
"int: Maximum number of entries the cache can contain. :param max_age int: Maximum",
"queue # and the value. # # I may end up reimplementing this",
"the configured cache. \"\"\" cache_name = cfg.pop(\"type\", \"null\") if cache_name == \"null\": logger.info(\"Caching",
"return None for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"): if ep.name == cache_name: logger.info(\"Using cache '%s'",
"value) def evict_expired(self): \"\"\" Evict any items older than the maximum age from",
"response) else: logger.info(\"Cache hit for '%s'\", query) return response return wrapped # pylint:",
"new LFU cache. :param max_size int: Maximum number of entries the cache can",
"\"null\") if cache_name == \"null\": logger.info(\"Caching deactivated\") return None for ep in pkg_resources.iter_entry_points(\"uwhoisd.cache\"):",
"response return wrapped # pylint: disable-msg=R0924 class LFU(object): \"\"\" A simple LFU cache.",
"Attempt to remove the named item from the cache. \"\"\" counter, value =",
"# cache key. The cache maps cache keys onto 2-tuples consisting of a",
"\"\"\" A simple LFU cache. \"\"\" # This is implemented as an LFU",
"the cache. \"\"\" cutoff = self.clock() - self.max_age while len(self.queue) > 0: ts,",
"cache_name, cfg) cache_type = ep.load() return cache_type(**cfg) raise UnknownCache(cache_name) def wrap_whois(cache, whois_func): \"\"\"",
"\"queue\") clock = staticmethod(time.time) def __init__(self, max_size=256, max_age=300): \"\"\" Create a new LFU",
"del self.cache[key] else: self.cache[key] = (counter, value) def evict_expired(self): \"\"\" Evict any items",
"= staticmethod(time.time) def __init__(self, max_size=256, max_age=300): \"\"\" Create a new LFU cache. :param",
"for '%s'\", query) return response return wrapped # pylint: disable-msg=R0924 class LFU(object): \"\"\"",
"> cutoff: self.queue.appendleft((ts, key)) break self.attempt_eviction(key) def get(self, key): \"\"\" Pull a value",
"return cache_type(**cfg) raise UnknownCache(cache_name) def wrap_whois(cache, whois_func): \"\"\" Wrap a WHOIS query function",
"logger.info(\"Cache hit for '%s'\", query) return response return wrapped # pylint: disable-msg=R0924 class",
"from the cache corresponding to the key. If no value exists, `None` is",
"self).__init__() self.cache = {} self.queue = collections.deque() self.max_size = int(max_size) self.max_age = int(max_age)",
"seconds to consider an entry live. \"\"\" super(LFU, self).__init__() self.cache = {} self.queue",
"\"\"\" The supplied cache type name cannot be found. \"\"\" def get_cache(cfg): \"\"\"",
"of the time the item was put into the cache and the #",
"of times this item occurs on the eviction queue # and the value.",
"to the key. If no value exists, `None` is returned. \"\"\" self.evict_expired() if",
"eviction queue contains # 2-tuples consisting of the time the item was put",
"def get_cache(cfg): \"\"\" Attempt to load the configured cache. \"\"\" cache_name = cfg.pop(\"type\",",
"ts > cutoff: self.queue.appendleft((ts, key)) break self.attempt_eviction(key) def get(self, key): \"\"\" Pull a",
"cache. :param max_size int: Maximum number of entries the cache can contain. :param",
"import pkg_resources logger = logging.getLogger(\"uwhoisd\") class UnknownCache(Exception): \"\"\" The supplied cache type name",
"can contain. :param max_age int: Maximum number of seconds to consider an entry"
] |
[
"settings given some environment variables. :param monkeypatch: The pytest monkeypatch fixture \"\"\" settings",
") def test_full(settings_env_var_to_full): \"\"\"Test the source of effective settings given a full config.",
"given some cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True params = [\"images\",",
"deepcopy(NavigatorConfiguration) settings.internals.initializing = True _messages, _exit_messages = parse_and_update(params=[], args=settings) sources = to_sources(settings) for",
"== C.USER_CLI.value for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value,",
"source in sources.items(): if path.startswith(\"settings_file\"): continue assert source in [C.USER_CFG.value, C.AUTO.value], (path, source)",
"path, source, ) def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the source of effective settings given",
"= parse_and_update(params=[], args=settings) sources = to_sources(settings) for path, source in sources.items(): if path.startswith(\"settings_file\"):",
"_exit_messages sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert",
"\"\"\"Test the ability to produce a dictionary of effective sources.\"\"\" from copy import",
"source of effective settings given some cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing =",
"The pytest fixture to provide a full config \"\"\" # pylint: disable=unused-argument settings",
"the source of effective settings given a full config. :param settings_env_var_to_full: The pytest",
"def test_full(settings_env_var_to_full): \"\"\"Test the source of effective settings given a full config. :param",
"environment variables. :param monkeypatch: The pytest monkeypatch fixture \"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing",
"effective settings given some environment variables. :param monkeypatch: The pytest monkeypatch fixture \"\"\"",
"# pylint: disable=unused-argument settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True _messages, _exit_messages = parse_and_update(params=[],",
"used as a sample against the schema.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True",
"= deepcopy(NavigatorConfiguration) settings.internals.initializing = True prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix),",
"of effective sources.\"\"\" from copy import deepcopy import pytest from ansible_navigator.configuration_subsystem import Configurator",
"test_full(settings_env_var_to_full): \"\"\"Test the source of effective settings given a full config. :param settings_env_var_to_full:",
"as a sample against the schema.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True Configurator(params=[],",
"( path, source, ) def test_cli(): \"\"\"Test the source of effective settings given",
"[C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the",
"assert not _exit_messages sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") ==",
"sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\")",
"test_defaults(): \"\"\"Check the settings file used as a sample against the schema.\"\"\" settings",
"True Configurator(params=[], application_configuration=settings).configure() sources = to_sources(settings) for path, source in sources.items(): assert source",
"schema.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True Configurator(params=[], application_configuration=settings).configure() sources = to_sources(settings) for",
"_exit_messages = parse_and_update(params=[], args=settings) sources = to_sources(settings) for path, source in sources.items(): if",
"provide a full config \"\"\" # pylint: disable=unused-argument settings = deepcopy(NavigatorConfiguration) settings.internals.initializing =",
"[\"images\", \"--ll\", \"debug\", \"--la\", \"false\"] _messages, _exit_messages = parse_and_update(params=params, args=settings) sources = to_sources(settings)",
"application_configuration=settings).configure() sources = to_sources(settings) for path, source in sources.items(): assert source in [C.AUTO.value,",
"C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_full(settings_env_var_to_full): \"\"\"Test the source of effective",
"from copy import deepcopy import pytest from ansible_navigator.configuration_subsystem import Configurator from ansible_navigator.configuration_subsystem import",
"C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for path, source in",
"prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages = parse_and_update(params=[],",
"sources = to_sources(settings) for path, source in sources.items(): if path.startswith(\"settings_file\"): continue assert source",
"= to_sources(settings) for path, source in sources.items(): if path.startswith(\"settings_file\"): continue assert source in",
"[C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_cli(): \"\"\"Test the source",
"settings given some cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True params =",
"pytest fixture to provide a full config \"\"\" # pylint: disable=unused-argument settings =",
"pylint: disable=unused-argument settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True _messages, _exit_messages = parse_and_update(params=[], args=settings)",
"settings given a full config. :param settings_env_var_to_full: The pytest fixture to provide a",
"sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for path, source in sources.items(): assert",
"assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for",
"args=settings) assert not _exit_messages sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\")",
"of effective settings given some cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True",
"settings.internals.initializing = True _messages, _exit_messages = parse_and_update(params=[], args=settings) sources = to_sources(settings) for path,",
"settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True params = [\"images\", \"--ll\", \"debug\", \"--la\", \"false\"]",
"( path, source, ) def test_full(settings_env_var_to_full): \"\"\"Test the source of effective settings given",
"parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True params = [\"images\", \"--ll\", \"debug\", \"--la\",",
"= [\"images\", \"--ll\", \"debug\", \"--la\", \"false\"] _messages, _exit_messages = parse_and_update(params=params, args=settings) sources =",
"( path, source, ) def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the source of effective settings",
"source, ) def test_cli(): \"\"\"Test the source of effective settings given some cli",
"args=settings) sources = to_sources(settings) for path, source in sources.items(): if path.startswith(\"settings_file\"): continue assert",
"import to_sources from ansible_navigator.initialization import parse_and_update def test_defaults(): \"\"\"Check the settings file used",
"the ability to produce a dictionary of effective sources.\"\"\" from copy import deepcopy",
"path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path,",
"a full config. :param settings_env_var_to_full: The pytest fixture to provide a full config",
"\"\"\" # pylint: disable=unused-argument settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True _messages, _exit_messages =",
"<gh_stars>0 \"\"\"Test the ability to produce a dictionary of effective sources.\"\"\" from copy",
"import Constants as C from ansible_navigator.configuration_subsystem import NavigatorConfiguration from ansible_navigator.configuration_subsystem import to_sources from",
"ansible_navigator.configuration_subsystem import to_sources from ansible_navigator.initialization import parse_and_update def test_defaults(): \"\"\"Check the settings file",
"\"false\"] _messages, _exit_messages = parse_and_update(params=params, args=settings) sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value",
"_messages, _exit_messages = parse_and_update(params=params, args=settings) sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert",
"dictionary of effective sources.\"\"\" from copy import deepcopy import pytest from ansible_navigator.configuration_subsystem import",
"full config. :param settings_env_var_to_full: The pytest fixture to provide a full config \"\"\"",
"== C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for path, source in sources.items(): assert source",
"copy import deepcopy import pytest from ansible_navigator.configuration_subsystem import Configurator from ansible_navigator.configuration_subsystem import Constants",
"= to_sources(settings) for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value,",
"some environment variables. :param monkeypatch: The pytest monkeypatch fixture \"\"\" settings = deepcopy(NavigatorConfiguration)",
"Configurator from ansible_navigator.configuration_subsystem import Constants as C from ansible_navigator.configuration_subsystem import NavigatorConfiguration from ansible_navigator.configuration_subsystem",
"for path, source in sources.items(): if path.startswith(\"settings_file\"): continue assert source in [C.USER_CFG.value, C.AUTO.value],",
"= parse_and_update(params=[], args=settings) assert not _exit_messages sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value",
"to produce a dictionary of effective sources.\"\"\" from copy import deepcopy import pytest",
"import deepcopy import pytest from ansible_navigator.configuration_subsystem import Configurator from ansible_navigator.configuration_subsystem import Constants as",
"source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_cli(): \"\"\"Test",
"to_sources(settings) for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value],",
"NavigatorConfiguration from ansible_navigator.configuration_subsystem import to_sources from ansible_navigator.initialization import parse_and_update def test_defaults(): \"\"\"Check the",
"effective settings given some cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True params",
"\"--ll\", \"debug\", \"--la\", \"false\"] _messages, _exit_messages = parse_and_update(params=params, args=settings) sources = to_sources(settings) assert",
"source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source,",
"settings.internals.initializing = True params = [\"images\", \"--ll\", \"debug\", \"--la\", \"false\"] _messages, _exit_messages =",
"for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], (",
"_messages, _exit_messages = parse_and_update(params=[], args=settings) assert not _exit_messages sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\")",
"C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_cli(): \"\"\"Test the source of",
"in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_full(settings_env_var_to_full): \"\"\"Test the",
"from ansible_navigator.configuration_subsystem import to_sources from ansible_navigator.initialization import parse_and_update def test_defaults(): \"\"\"Check the settings",
"deepcopy(NavigatorConfiguration) settings.internals.initializing = True Configurator(params=[], application_configuration=settings).configure() sources = to_sources(settings) for path, source in",
"parse_and_update(params=[], args=settings) sources = to_sources(settings) for path, source in sources.items(): if path.startswith(\"settings_file\"): continue",
"C.NONE.value], ( path, source, ) def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the source of effective",
"= True _messages, _exit_messages = parse_and_update(params=[], args=settings) sources = to_sources(settings) for path, source",
"True params = [\"images\", \"--ll\", \"debug\", \"--la\", \"false\"] _messages, _exit_messages = parse_and_update(params=params, args=settings)",
"C.NONE.value], ( path, source, ) def test_cli(): \"\"\"Test the source of effective settings",
"deepcopy(NavigatorConfiguration) settings.internals.initializing = True params = [\"images\", \"--ll\", \"debug\", \"--la\", \"false\"] _messages, _exit_messages",
"pytest monkeypatch fixture \"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True prefix = settings.application_name",
"assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_env(monkeypatch:",
"pytest from ansible_navigator.configuration_subsystem import Configurator from ansible_navigator.configuration_subsystem import Constants as C from ansible_navigator.configuration_subsystem",
"source, ) def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the source of effective settings given some",
"of effective settings given some environment variables. :param monkeypatch: The pytest monkeypatch fixture",
"the settings file used as a sample against the schema.\"\"\" settings = deepcopy(NavigatorConfiguration)",
"not _exit_messages sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value",
"source, ) def test_full(settings_env_var_to_full): \"\"\"Test the source of effective settings given a full",
"\"debug\", \"--la\", \"false\"] _messages, _exit_messages = parse_and_update(params=params, args=settings) sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\")",
"C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the source",
"config \"\"\" # pylint: disable=unused-argument settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True _messages, _exit_messages",
"pytest.MonkeyPatch): \"\"\"Test the source of effective settings given some environment variables. :param monkeypatch:",
"args=settings) sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert",
"ansible_navigator.configuration_subsystem import NavigatorConfiguration from ansible_navigator.configuration_subsystem import to_sources from ansible_navigator.initialization import parse_and_update def test_defaults():",
"some cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True params = [\"images\", \"--ll\",",
"cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True params = [\"images\", \"--ll\", \"debug\",",
"test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the source of effective settings given some environment variables. :param",
"def test_defaults(): \"\"\"Check the settings file used as a sample against the schema.\"\"\"",
"= to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") ==",
"import NavigatorConfiguration from ansible_navigator.configuration_subsystem import to_sources from ansible_navigator.initialization import parse_and_update def test_defaults(): \"\"\"Check",
"settings file used as a sample against the schema.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing",
"path, source, ) def test_full(settings_env_var_to_full): \"\"\"Test the source of effective settings given a",
":param settings_env_var_to_full: The pytest fixture to provide a full config \"\"\" # pylint:",
"disable=unused-argument settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True _messages, _exit_messages = parse_and_update(params=[], args=settings) sources",
"_exit_messages = parse_and_update(params=params, args=settings) sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\")",
"parse_and_update(params=[], args=settings) assert not _exit_messages sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert",
"of effective settings given a full config. :param settings_env_var_to_full: The pytest fixture to",
"= True params = [\"images\", \"--ll\", \"debug\", \"--la\", \"false\"] _messages, _exit_messages = parse_and_update(params=params,",
"a full config \"\"\" # pylint: disable=unused-argument settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True",
"sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def",
"monkeypatch: The pytest monkeypatch fixture \"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True prefix",
"[C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_full(settings_env_var_to_full): \"\"\"Test the source",
"\"\"\"Check the settings file used as a sample against the schema.\"\"\" settings =",
"a sample against the schema.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True Configurator(params=[], application_configuration=settings).configure()",
"sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for path,",
"a dictionary of effective sources.\"\"\" from copy import deepcopy import pytest from ansible_navigator.configuration_subsystem",
"params = [\"images\", \"--ll\", \"debug\", \"--la\", \"false\"] _messages, _exit_messages = parse_and_update(params=params, args=settings) sources",
"C.USER_CLI.value for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value],",
"assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for path, source in sources.items(): assert source in [C.AUTO.value,",
"from ansible_navigator.configuration_subsystem import Constants as C from ansible_navigator.configuration_subsystem import NavigatorConfiguration from ansible_navigator.configuration_subsystem import",
"in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test",
"from ansible_navigator.configuration_subsystem import Configurator from ansible_navigator.configuration_subsystem import Constants as C from ansible_navigator.configuration_subsystem import",
"parse_and_update def test_defaults(): \"\"\"Check the settings file used as a sample against the",
"monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages = parse_and_update(params=[], args=settings) assert not _exit_messages sources",
"C from ansible_navigator.configuration_subsystem import NavigatorConfiguration from ansible_navigator.configuration_subsystem import to_sources from ansible_navigator.initialization import parse_and_update",
"C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_full(settings_env_var_to_full): \"\"\"Test the source of",
"config. :param settings_env_var_to_full: The pytest fixture to provide a full config \"\"\" #",
"monkeypatch fixture \"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix),",
"to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value",
"deepcopy import pytest from ansible_navigator.configuration_subsystem import Configurator from ansible_navigator.configuration_subsystem import Constants as C",
"sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\")",
"= deepcopy(NavigatorConfiguration) settings.internals.initializing = True params = [\"images\", \"--ll\", \"debug\", \"--la\", \"false\"] _messages,",
"_messages, _exit_messages = parse_and_update(params=[], args=settings) sources = to_sources(settings) for path, source in sources.items():",
"sample against the schema.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True Configurator(params=[], application_configuration=settings).configure() sources",
"sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for path,",
"parse_and_update(params=params, args=settings) sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value",
"C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for path, source in sources.items(): assert source in",
"fixture to provide a full config \"\"\" # pylint: disable=unused-argument settings = deepcopy(NavigatorConfiguration)",
") def test_cli(): \"\"\"Test the source of effective settings given some cli parameters.\"\"\"",
"def test_cli(): \"\"\"Test the source of effective settings given some cli parameters.\"\"\" settings",
"assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for path, source in sources.items():",
"settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages = parse_and_update(params=[], args=settings) assert",
"def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the source of effective settings given some environment variables.",
"from ansible_navigator.configuration_subsystem import NavigatorConfiguration from ansible_navigator.configuration_subsystem import to_sources from ansible_navigator.initialization import parse_and_update def",
"fixture \"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\")",
"full config \"\"\" # pylint: disable=unused-argument settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True _messages,",
"= settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages = parse_and_update(params=[], args=settings)",
"file used as a sample against the schema.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing =",
"variables. :param monkeypatch: The pytest monkeypatch fixture \"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing =",
"in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, )",
"ansible_navigator.configuration_subsystem import Constants as C from ansible_navigator.configuration_subsystem import NavigatorConfiguration from ansible_navigator.configuration_subsystem import to_sources",
"ansible_navigator.configuration_subsystem import Configurator from ansible_navigator.configuration_subsystem import Constants as C from ansible_navigator.configuration_subsystem import NavigatorConfiguration",
"ansible_navigator.initialization import parse_and_update def test_defaults(): \"\"\"Check the settings file used as a sample",
"import parse_and_update def test_defaults(): \"\"\"Check the settings file used as a sample against",
"= parse_and_update(params=params, args=settings) sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") ==",
"sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value,",
"C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the source of",
"to_sources from ansible_navigator.initialization import parse_and_update def test_defaults(): \"\"\"Check the settings file used as",
"assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for path, source in sources.items(): assert source in [C.AUTO.value,",
"source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_env(monkeypatch: pytest.MonkeyPatch):",
"== C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for path, source in sources.items(): assert source",
"Constants as C from ansible_navigator.configuration_subsystem import NavigatorConfiguration from ansible_navigator.configuration_subsystem import to_sources from ansible_navigator.initialization",
"ability to produce a dictionary of effective sources.\"\"\" from copy import deepcopy import",
"settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True Configurator(params=[], application_configuration=settings).configure() sources = to_sources(settings) for path,",
") def test_env(monkeypatch: pytest.MonkeyPatch): \"\"\"Test the source of effective settings given some environment",
"\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix),",
"assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for path, source in sources.items():",
"== C.ENVIRONMENT_VARIABLE.value for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value,",
"sources = to_sources(settings) for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value,",
"as C from ansible_navigator.configuration_subsystem import NavigatorConfiguration from ansible_navigator.configuration_subsystem import to_sources from ansible_navigator.initialization import",
"the source of effective settings given some cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing",
"effective settings given a full config. :param settings_env_var_to_full: The pytest fixture to provide",
"deepcopy(NavigatorConfiguration) settings.internals.initializing = True prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\")",
"against the schema.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True Configurator(params=[], application_configuration=settings).configure() sources =",
"\"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages = parse_and_update(params=[], args=settings) assert not _exit_messages",
"source of effective settings given some environment variables. :param monkeypatch: The pytest monkeypatch",
"C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_cli(): \"\"\"Test the source of effective",
"The pytest monkeypatch fixture \"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True prefix =",
"sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for path, source in sources.items(): assert",
"produce a dictionary of effective sources.\"\"\" from copy import deepcopy import pytest from",
"monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages = parse_and_update(params=[], args=settings) assert not _exit_messages sources = to_sources(settings)",
"\"\"\"Test the source of effective settings given some cli parameters.\"\"\" settings = deepcopy(NavigatorConfiguration)",
"= True prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages",
"source of effective settings given a full config. :param settings_env_var_to_full: The pytest fixture",
"path, source in sources.items(): if path.startswith(\"settings_file\"): continue assert source in [C.USER_CFG.value, C.AUTO.value], (path,",
"the source of effective settings given some environment variables. :param monkeypatch: The pytest",
"\"false\") _messages, _exit_messages = parse_and_update(params=[], args=settings) assert not _exit_messages sources = to_sources(settings) assert",
"settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\")",
"settings.internals.initializing = True Configurator(params=[], application_configuration=settings).configure() sources = to_sources(settings) for path, source in sources.items():",
"_exit_messages = parse_and_update(params=[], args=settings) assert not _exit_messages sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") ==",
"in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_cli(): \"\"\"Test the",
"test_cli(): \"\"\"Test the source of effective settings given some cli parameters.\"\"\" settings =",
"C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for path, source in",
"True prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages =",
"source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_full(settings_env_var_to_full): \"\"\"Test",
"sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value,",
"settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True _messages, _exit_messages = parse_and_update(params=[], args=settings) sources =",
"to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value",
"to_sources(settings) for path, source in sources.items(): if path.startswith(\"settings_file\"): continue assert source in [C.USER_CFG.value,",
"monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages = parse_and_update(params=[], args=settings) assert not",
"\"\"\"Test the source of effective settings given some environment variables. :param monkeypatch: The",
"\"--la\", \"false\"] _messages, _exit_messages = parse_and_update(params=params, args=settings) sources = to_sources(settings) assert sources.pop(\"ansible-navigator.app\") ==",
"sources.\"\"\" from copy import deepcopy import pytest from ansible_navigator.configuration_subsystem import Configurator from ansible_navigator.configuration_subsystem",
"effective sources.\"\"\" from copy import deepcopy import pytest from ansible_navigator.configuration_subsystem import Configurator from",
"Configurator(params=[], application_configuration=settings).configure() sources = to_sources(settings) for path, source in sources.items(): assert source in",
"assert sources.pop(\"ansible-navigator.app\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for",
"\"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages, _exit_messages = parse_and_update(params=[], args=settings) assert not _exit_messages sources =",
"given some environment variables. :param monkeypatch: The pytest monkeypatch fixture \"\"\" settings =",
"C.ENVIRONMENT_VARIABLE.value for path, source in sources.items(): assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value],",
"True _messages, _exit_messages = parse_and_update(params=[], args=settings) sources = to_sources(settings) for path, source in",
"settings.internals.initializing = True prefix = settings.application_name monkeypatch.setenv(settings.entry(\"app\").environment_variable(prefix), \"images\") monkeypatch.setenv(settings.entry(\"log_level\").environment_variable(prefix), \"debug\") monkeypatch.setenv(settings.entry(\"log_append\").environment_variable(prefix), \"false\") _messages,",
"= deepcopy(NavigatorConfiguration) settings.internals.initializing = True Configurator(params=[], application_configuration=settings).configure() sources = to_sources(settings) for path, source",
"from ansible_navigator.initialization import parse_and_update def test_defaults(): \"\"\"Check the settings file used as a",
"\"\"\"Test the source of effective settings given a full config. :param settings_env_var_to_full: The",
"the schema.\"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True Configurator(params=[], application_configuration=settings).configure() sources = to_sources(settings)",
"to provide a full config \"\"\" # pylint: disable=unused-argument settings = deepcopy(NavigatorConfiguration) settings.internals.initializing",
"== C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.level\") == C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for path, source",
"given a full config. :param settings_env_var_to_full: The pytest fixture to provide a full",
"C.NONE.value], ( path, source, ) def test_full(settings_env_var_to_full): \"\"\"Test the source of effective settings",
"assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_cli():",
"settings_env_var_to_full: The pytest fixture to provide a full config \"\"\" # pylint: disable=unused-argument",
"import pytest from ansible_navigator.configuration_subsystem import Configurator from ansible_navigator.configuration_subsystem import Constants as C from",
"= True Configurator(params=[], application_configuration=settings).configure() sources = to_sources(settings) for path, source in sources.items(): assert",
"= to_sources(settings) assert sources.pop(\"ansible-navigator.app\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") ==",
"import Configurator from ansible_navigator.configuration_subsystem import Constants as C from ansible_navigator.configuration_subsystem import NavigatorConfiguration from",
":param monkeypatch: The pytest monkeypatch fixture \"\"\" settings = deepcopy(NavigatorConfiguration) settings.internals.initializing = True",
"== C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.level\") == C.ENVIRONMENT_VARIABLE.value assert sources.pop(\"ansible-navigator.logging.append\") == C.ENVIRONMENT_VARIABLE.value for path, source",
"path, source, ) def test_cli(): \"\"\"Test the source of effective settings given some",
"C.USER_CLI.value assert sources.pop(\"ansible-navigator.logging.append\") == C.USER_CLI.value for path, source in sources.items(): assert source in",
"assert source in [C.AUTO.value, C.DEFAULT_CFG.value, C.NOT_SET.value, C.NONE.value], ( path, source, ) def test_full(settings_env_var_to_full):",
"= deepcopy(NavigatorConfiguration) settings.internals.initializing = True _messages, _exit_messages = parse_and_update(params=[], args=settings) sources = to_sources(settings)"
] |
[
"def validate_user(self): if True: self.auth = True if __name__ == '__main__': app =",
"if True: self.auth = True if __name__ == '__main__': app = QApplication(sys.argv) w",
"import os, sys sys.path.append(os.getcwd()) from PyQt5.QtWidgets import QApplication from src.view.widgets.buttons_cch import ButtonsCCHView from",
"Base class ButtonsCCHController: def __init__(self, force_show=False): print('C botoes') self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if",
"self.view def on_bt_confirmare(self): print(10) def validate_user(self): if True: self.auth = True if __name__",
"ButtonsCCHView from src.controller.base import Base class ButtonsCCHController: def __init__(self, force_show=False): print('C botoes') self.view",
"ButtonsCCHController: def __init__(self, force_show=False): print('C botoes') self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show()",
"show(self): return self.view def on_bt_confirmare(self): print(10) def validate_user(self): if True: self.auth = True",
"src.view.widgets.buttons_cch import ButtonsCCHView from src.controller.base import Base class ButtonsCCHController: def __init__(self, force_show=False): print('C",
"class ButtonsCCHController: def __init__(self, force_show=False): print('C botoes') self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show:",
"force_show=False): print('C botoes') self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show() def show(self): return",
"sys sys.path.append(os.getcwd()) from PyQt5.QtWidgets import QApplication from src.view.widgets.buttons_cch import ButtonsCCHView from src.controller.base import",
"validate_user(self): if True: self.auth = True if __name__ == '__main__': app = QApplication(sys.argv)",
"__init__(self, force_show=False): print('C botoes') self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show() def show(self):",
"from src.view.widgets.buttons_cch import ButtonsCCHView from src.controller.base import Base class ButtonsCCHController: def __init__(self, force_show=False):",
"= True if __name__ == '__main__': app = QApplication(sys.argv) w = ButtonsCCHController(True) sys.exit(app.exec_())",
"print(10) def validate_user(self): if True: self.auth = True if __name__ == '__main__': app",
"def on_bt_confirmare(self): print(10) def validate_user(self): if True: self.auth = True if __name__ ==",
"botoes') self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show() def show(self): return self.view def",
"PyQt5.QtWidgets import QApplication from src.view.widgets.buttons_cch import ButtonsCCHView from src.controller.base import Base class ButtonsCCHController:",
"print('C botoes') self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show() def show(self): return self.view",
"return self.view def on_bt_confirmare(self): print(10) def validate_user(self): if True: self.auth = True if",
"ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show() def show(self): return self.view def on_bt_confirmare(self): print(10) def",
"self.view.show() def show(self): return self.view def on_bt_confirmare(self): print(10) def validate_user(self): if True: self.auth",
"sys.path.append(os.getcwd()) from PyQt5.QtWidgets import QApplication from src.view.widgets.buttons_cch import ButtonsCCHView from src.controller.base import Base",
"self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show() def show(self): return self.view def on_bt_confirmare(self): print(10) def validate_user(self):",
"= ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show() def show(self): return self.view def on_bt_confirmare(self): print(10)",
"import QApplication from src.view.widgets.buttons_cch import ButtonsCCHView from src.controller.base import Base class ButtonsCCHController: def",
"import Base class ButtonsCCHController: def __init__(self, force_show=False): print('C botoes') self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare)",
"from src.controller.base import Base class ButtonsCCHController: def __init__(self, force_show=False): print('C botoes') self.view =",
"def show(self): return self.view def on_bt_confirmare(self): print(10) def validate_user(self): if True: self.auth =",
"from PyQt5.QtWidgets import QApplication from src.view.widgets.buttons_cch import ButtonsCCHView from src.controller.base import Base class",
"force_show: self.view.show() def show(self): return self.view def on_bt_confirmare(self): print(10) def validate_user(self): if True:",
"QApplication from src.view.widgets.buttons_cch import ButtonsCCHView from src.controller.base import Base class ButtonsCCHController: def __init__(self,",
"import ButtonsCCHView from src.controller.base import Base class ButtonsCCHController: def __init__(self, force_show=False): print('C botoes')",
"self.auth = True if __name__ == '__main__': app = QApplication(sys.argv) w = ButtonsCCHController(True)",
"True: self.auth = True if __name__ == '__main__': app = QApplication(sys.argv) w =",
"if force_show: self.view.show() def show(self): return self.view def on_bt_confirmare(self): print(10) def validate_user(self): if",
"on_bt_confirmare(self): print(10) def validate_user(self): if True: self.auth = True if __name__ == '__main__':",
"self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show() def show(self): return self.view def on_bt_confirmare(self):",
"src.controller.base import Base class ButtonsCCHController: def __init__(self, force_show=False): print('C botoes') self.view = ButtonsCCHView()",
"os, sys sys.path.append(os.getcwd()) from PyQt5.QtWidgets import QApplication from src.view.widgets.buttons_cch import ButtonsCCHView from src.controller.base",
"def __init__(self, force_show=False): print('C botoes') self.view = ButtonsCCHView() self.view.bt_confirmar.clicked.connect(self.on_bt_confirmare) if force_show: self.view.show() def"
] |
[
"The preprocessor module. ''' # CS 267 specific imports from preprocessor.build_tables import read_input_files",
"the words extracted from the PDFs. The preprocessor module. ''' # CS 267",
"imports from preprocessor.build_tables import read_input_files from preprocessor.build_tables import determine_word_positions from preprocessor.build_tables import determine_doc_frequency",
"to build the reverse-indices for the words extracted from the PDFs. The preprocessor",
"@Last Modified by: <NAME> # @Last Modified time: 2017-04-05 23:13:28 ''' Houses the",
"read_input_files from preprocessor.build_tables import determine_word_positions from preprocessor.build_tables import determine_doc_frequency __all__ = ['read_input_files', 'determine_word_positions',",
"the core logic used to build the reverse-indices for the words extracted from",
"23:13:28 ''' Houses the core logic used to build the reverse-indices for the",
"build the reverse-indices for the words extracted from the PDFs. The preprocessor module.",
"for the words extracted from the PDFs. The preprocessor module. ''' # CS",
"# CS 267 specific imports from preprocessor.build_tables import read_input_files from preprocessor.build_tables import determine_word_positions",
"core logic used to build the reverse-indices for the words extracted from the",
"Modified time: 2017-04-05 23:13:28 ''' Houses the core logic used to build the",
"from the PDFs. The preprocessor module. ''' # CS 267 specific imports from",
"# -*- coding: utf-8 -*- # @Author: <NAME> # @Date: 2017-04-05 20:29:06 #",
"Houses the core logic used to build the reverse-indices for the words extracted",
"the reverse-indices for the words extracted from the PDFs. The preprocessor module. '''",
"-*- # @Author: <NAME> # @Date: 2017-04-05 20:29:06 # @Last Modified by: <NAME>",
"from preprocessor.build_tables import read_input_files from preprocessor.build_tables import determine_word_positions from preprocessor.build_tables import determine_doc_frequency __all__",
"preprocessor.build_tables import read_input_files from preprocessor.build_tables import determine_word_positions from preprocessor.build_tables import determine_doc_frequency __all__ =",
"used to build the reverse-indices for the words extracted from the PDFs. The",
"__init__.py # -*- coding: utf-8 -*- # @Author: <NAME> # @Date: 2017-04-05 20:29:06",
"specific imports from preprocessor.build_tables import read_input_files from preprocessor.build_tables import determine_word_positions from preprocessor.build_tables import",
"import read_input_files from preprocessor.build_tables import determine_word_positions from preprocessor.build_tables import determine_doc_frequency __all__ = ['read_input_files',",
"from preprocessor.build_tables import determine_word_positions from preprocessor.build_tables import determine_doc_frequency __all__ = ['read_input_files', 'determine_word_positions', 'determine_doc_frequency']",
"reverse-indices for the words extracted from the PDFs. The preprocessor module. ''' #",
"<NAME> # @Last Modified time: 2017-04-05 23:13:28 ''' Houses the core logic used",
"logic used to build the reverse-indices for the words extracted from the PDFs.",
"Modified by: <NAME> # @Last Modified time: 2017-04-05 23:13:28 ''' Houses the core",
"# @Date: 2017-04-05 20:29:06 # @Last Modified by: <NAME> # @Last Modified time:",
"the PDFs. The preprocessor module. ''' # CS 267 specific imports from preprocessor.build_tables",
"time: 2017-04-05 23:13:28 ''' Houses the core logic used to build the reverse-indices",
"words extracted from the PDFs. The preprocessor module. ''' # CS 267 specific",
"# @Last Modified time: 2017-04-05 23:13:28 ''' Houses the core logic used to",
"2017-04-05 23:13:28 ''' Houses the core logic used to build the reverse-indices for",
"@Author: <NAME> # @Date: 2017-04-05 20:29:06 # @Last Modified by: <NAME> # @Last",
"by: <NAME> # @Last Modified time: 2017-04-05 23:13:28 ''' Houses the core logic",
"@Last Modified time: 2017-04-05 23:13:28 ''' Houses the core logic used to build",
"# @Author: <NAME> # @Date: 2017-04-05 20:29:06 # @Last Modified by: <NAME> #",
"CS 267 specific imports from preprocessor.build_tables import read_input_files from preprocessor.build_tables import determine_word_positions from",
"PDFs. The preprocessor module. ''' # CS 267 specific imports from preprocessor.build_tables import",
"extracted from the PDFs. The preprocessor module. ''' # CS 267 specific imports",
"preprocessor module. ''' # CS 267 specific imports from preprocessor.build_tables import read_input_files from",
"# __init__.py # -*- coding: utf-8 -*- # @Author: <NAME> # @Date: 2017-04-05",
"20:29:06 # @Last Modified by: <NAME> # @Last Modified time: 2017-04-05 23:13:28 '''",
"# @Last Modified by: <NAME> # @Last Modified time: 2017-04-05 23:13:28 ''' Houses",
"''' Houses the core logic used to build the reverse-indices for the words",
"@Date: 2017-04-05 20:29:06 # @Last Modified by: <NAME> # @Last Modified time: 2017-04-05",
"267 specific imports from preprocessor.build_tables import read_input_files from preprocessor.build_tables import determine_word_positions from preprocessor.build_tables",
"coding: utf-8 -*- # @Author: <NAME> # @Date: 2017-04-05 20:29:06 # @Last Modified",
"2017-04-05 20:29:06 # @Last Modified by: <NAME> # @Last Modified time: 2017-04-05 23:13:28",
"<NAME> # @Date: 2017-04-05 20:29:06 # @Last Modified by: <NAME> # @Last Modified",
"module. ''' # CS 267 specific imports from preprocessor.build_tables import read_input_files from preprocessor.build_tables",
"''' # CS 267 specific imports from preprocessor.build_tables import read_input_files from preprocessor.build_tables import",
"utf-8 -*- # @Author: <NAME> # @Date: 2017-04-05 20:29:06 # @Last Modified by:",
"-*- coding: utf-8 -*- # @Author: <NAME> # @Date: 2017-04-05 20:29:06 # @Last"
] |
[
"<gh_stars>1-10 # Generated by Django 4.0.1 on 2022-03-16 14:58 import base.models from django.db",
"Generated by Django 4.0.1 on 2022-03-16 14:58 import base.models from django.db import migrations,",
"= [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations = [ migrations.AlterField( model_name='responses', name='photograph', field=models.ImageField(default='image_uploads/challenge-completed.png', upload_to=base.models.response_pic_location),",
"# Generated by Django 4.0.1 on 2022-03-16 14:58 import base.models from django.db import",
"base.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'),",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations = [",
"Migration(migrations.Migration): dependencies = [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations = [ migrations.AlterField( model_name='responses', name='photograph',",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ]",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations",
"Django 4.0.1 on 2022-03-16 14:58 import base.models from django.db import migrations, models class",
"models class Migration(migrations.Migration): dependencies = [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations = [ migrations.AlterField(",
"on 2022-03-16 14:58 import base.models from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"by Django 4.0.1 on 2022-03-16 14:58 import base.models from django.db import migrations, models",
"dependencies = [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations = [ migrations.AlterField( model_name='responses', name='photograph', field=models.ImageField(default='image_uploads/challenge-completed.png',",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations =",
"import base.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base',",
"('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations = [ migrations.AlterField( model_name='responses', name='photograph', field=models.ImageField(default='image_uploads/challenge-completed.png', upload_to=base.models.response_pic_location), ), ]",
"class Migration(migrations.Migration): dependencies = [ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations = [ migrations.AlterField( model_name='responses',",
"14:58 import base.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"[ ('base', '0031_alter_profile_picture_delete_weeklychallenge'), ] operations = [ migrations.AlterField( model_name='responses', name='photograph', field=models.ImageField(default='image_uploads/challenge-completed.png', upload_to=base.models.response_pic_location), ),",
"2022-03-16 14:58 import base.models from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"4.0.1 on 2022-03-16 14:58 import base.models from django.db import migrations, models class Migration(migrations.Migration):"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor',",
"tensorflow as tf import tensorflow_federated as tff from compressed_communication.broadcasters import histogram_model _mn =",
"KIND, either express or implied. # See the License for the specific language",
"_test_measurements_type = (tf.int32, (_nbins,)) def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class",
"Unless required by applicable law or agreed to in writing, software # distributed",
"= histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram) result = histogram_broadcaster.next(state, weights).result self.assertAllClose(result,",
"import collections from absl.testing import parameterized import tensorflow as tf import tensorflow_federated as",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"under the License. import collections from absl.testing import parameterized import tensorflow as tf",
"= (tf.int32, (_nbins,)) def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase,",
"_test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins)",
"histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) state = histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram,",
"License. # You may obtain a copy of the License at # #",
"( (tf.float32, (3,)), (tf.float32, (2,))) _test_measurements_type = (tf.int32, (_nbins,)) def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess(",
"(2,))) _test_measurements_type = (tf.int32, (_nbins,)) def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins)",
"_test_weights_type_struct_float_tensor = ( (tf.float32, (3,)), (tf.float32, (2,))) _test_measurements_type = (tf.int32, (_nbins,)) def _histogram_model():",
"_nbins = 4 _test_weights_type_float_tensor = (tf.float32, (3,)) _test_weights_type_struct_float_tensor = ( (tf.float32, (3,)), (tf.float32,",
"tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(()) expected_initialize_type = tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type",
"histogram = histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram) result = histogram_broadcaster.next(state, weights).result self.assertAllClose(result, weights) if",
"as tff from compressed_communication.broadcasters import histogram_model _mn = 0.0 _mx = 10.0 _nbins",
"specific language governing permissions and # limitations under the License. import collections from",
"= tff.type_at_server(()) expected_initialize_type = tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type)",
"= histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) state = histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state, weights).measurements",
"# Copyright 2022, Google LLC. # # Licensed under the Apache License, Version",
"law or agreed to in writing, software # distributed under the License is",
"def test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess)",
"the License for the specific language governing permissions and # limitations under the",
"_mn, _mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(()) expected_initialize_type = tff.FunctionType( parameter=None, result=server_state_type)",
"[[1.0, 2.0, 3.0], [1.0, 1.0]], [4, 1, 0, 0])) def test_histogram_impl(self, weights_type, weights,",
"expected_histogram) result = histogram_broadcaster.next(state, weights).result self.assertAllClose(result, weights) if __name__ == '__main__': tff.backends.native.set_local_python_execution_context(10) tf.test.main()",
"compliance with the License. # You may obtain a copy of the License",
"histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) state = histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state,",
"return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type),",
"server_state_type = tff.type_at_server(()) expected_initialize_type = tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type =",
"_mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def",
"_nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(()) expected_initialize_type = tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature,",
"_mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(()) expected_initialize_type = tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent(",
"import tensorflow_federated as tff from compressed_communication.broadcasters import histogram_model _mn = 0.0 _mx =",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"the License. import collections from absl.testing import parameterized import tensorflow as tf import",
"this file except in compliance with the License. # You may obtain a",
"state = histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram) result = histogram_broadcaster.next(state, weights).result",
"tf import tensorflow_federated as tff from compressed_communication.broadcasters import histogram_model _mn = 0.0 _mx",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"for the specific language governing permissions and # limitations under the License. import",
"(tf.float32, (2,))) _test_measurements_type = (tf.int32, (_nbins,)) def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx,",
"_test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0], [1.0, 1.0]], [4, 1, 0, 0])) def test_histogram_impl(self, weights_type,",
"_test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn,",
"tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase,",
"class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self, weights_type,",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type",
"weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor',",
"governing permissions and # limitations under the License. import collections from absl.testing import",
"weights_type, _mn, _mx, _nbins) state = histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram)",
"= histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram) result = histogram_broadcaster.next(state, weights).result self.assertAllClose(result, weights) if __name__",
"2022, Google LLC. # # Licensed under the Apache License, Version 2.0 (the",
"weights_type, expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type =",
"broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(()) expected_initialize_type",
"2.0, 3.0], [2, 1, 0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0], [1.0, 1.0]],",
"collections from absl.testing import parameterized import tensorflow as tf import tensorflow_federated as tff",
"tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0, 3.0], [2, 1,",
"ANY KIND, either express or implied. # See the License for the specific",
"parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0, 3.0], [2, 1, 0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor,",
"[1.0, 1.0]], [4, 1, 0, 0])) def test_histogram_impl(self, weights_type, weights, expected_histogram): weights_type =",
"measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0, 3.0], [2,",
"in compliance with the License. # You may obtain a copy of the",
"_mx = 10.0 _nbins = 4 _test_weights_type_float_tensor = (tf.float32, (3,)) _test_weights_type_struct_float_tensor = (",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"use this file except in compliance with the License. # You may obtain",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"# limitations under the License. import collections from absl.testing import parameterized import tensorflow",
"not use this file except in compliance with the License. # You may",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0, 3.0], [2, 1, 0,",
"[4, 1, 0, 0])) def test_histogram_impl(self, weights_type, weights, expected_histogram): weights_type = tff.to_type(weights_type) histogram_broadcaster",
"= (tf.float32, (3,)) _test_weights_type_struct_float_tensor = ( (tf.float32, (3,)), (tf.float32, (2,))) _test_measurements_type = (tf.int32,",
"See the License for the specific language governing permissions and # limitations under",
"= tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type)))",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"parameterized import tensorflow as tf import tensorflow_federated as tff from compressed_communication.broadcasters import histogram_model",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(()) expected_initialize_type = tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type)",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"= 4 _test_weights_type_float_tensor = (tf.float32, (3,)) _test_weights_type_struct_float_tensor = ( (tf.float32, (3,)), (tf.float32, (2,)))",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"0.0 _mx = 10.0 _nbins = 4 _test_weights_type_float_tensor = (tf.float32, (3,)) _test_weights_type_struct_float_tensor =",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"License. import collections from absl.testing import parameterized import tensorflow as tf import tensorflow_federated",
"_test_weights_type_float_tensor, [1.0, 2.0, 3.0], [2, 1, 0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0],",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"_test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type,",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"= ( (tf.float32, (3,)), (tf.float32, (2,))) _test_measurements_type = (tf.int32, (_nbins,)) def _histogram_model(): return",
"(tf.float32, (3,)), (tf.float32, (2,))) _test_measurements_type = (tf.int32, (_nbins,)) def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor,",
"histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(()) expected_initialize_type = tff.FunctionType(",
"HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0, 3.0], [2, 1, 0, 0]), ('struct_float_tensor',",
"compressed_communication.broadcasters import histogram_model _mn = 0.0 _mx = 10.0 _nbins = 4 _test_weights_type_float_tensor",
"tff from compressed_communication.broadcasters import histogram_model _mn = 0.0 _mx = 10.0 _nbins =",
"OF ANY KIND, either express or implied. # See the License for the",
"_mx, _nbins) state = histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram) result =",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"import histogram_model _mn = 0.0 _mx = 10.0 _nbins = 4 _test_weights_type_float_tensor =",
"Copyright 2022, Google LLC. # # Licensed under the Apache License, Version 2.0",
"expected_initialize_type = tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type =",
"[1.0, 2.0, 3.0], [2, 1, 0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0], [1.0,",
"# you may not use this file except in compliance with the License.",
"_mn = 0.0 _mx = 10.0 _nbins = 4 _test_weights_type_float_tensor = (tf.float32, (3,))",
"_mn, _mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type))",
"expected_next_type = tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type)",
"expected_histogram): weights_type = tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) state =",
"_test_weights_type_float_tensor = (tf.float32, (3,)) _test_weights_type_struct_float_tensor = ( (tf.float32, (3,)), (tf.float32, (2,))) _test_measurements_type =",
"agreed to in writing, software # distributed under the License is distributed on",
"0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0], [1.0, 1.0]], [4, 1, 0, 0]))",
"<filename>compressed_communication/broadcasters/histogram_model_test.py # Copyright 2022, Google LLC. # # Licensed under the Apache License,",
"histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram) result = histogram_broadcaster.next(state, weights).result self.assertAllClose(result, weights) if __name__ ==",
"histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor',",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"histogram_model _mn = 0.0 _mx = 10.0 _nbins = 4 _test_weights_type_float_tensor = (tf.float32,",
"weights, expected_histogram): weights_type = tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) state",
"from compressed_communication.broadcasters import histogram_model _mn = 0.0 _mx = 10.0 _nbins = 4",
"tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) state = histogram_broadcaster.initialize() histogram =",
"def test_histogram_impl(self, weights_type, weights, expected_histogram): weights_type = tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn,",
"state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters(",
"(the \"License\"); # you may not use this file except in compliance with",
"3.0], [1.0, 1.0]], [4, 1, 0, 0])) def test_histogram_impl(self, weights_type, weights, expected_histogram): weights_type",
"expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(())",
"_nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self,",
"1.0]], [4, 1, 0, 0])) def test_histogram_impl(self, weights_type, weights, expected_histogram): weights_type = tff.to_type(weights_type)",
"# # Unless required by applicable law or agreed to in writing, software",
"language governing permissions and # limitations under the License. import collections from absl.testing",
"= 0.0 _mx = 10.0 _nbins = 4 _test_weights_type_float_tensor = (tf.float32, (3,)) _test_weights_type_struct_float_tensor",
"all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0, 3.0],",
"express or implied. # See the License for the specific language governing permissions",
"parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"tensorflow_federated as tff from compressed_communication.broadcasters import histogram_model _mn = 0.0 _mx = 10.0",
"except in compliance with the License. # You may obtain a copy of",
"parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase):",
"by applicable law or agreed to in writing, software # distributed under the",
"expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type,",
"= 10.0 _nbins = 4 _test_weights_type_float_tensor = (tf.float32, (3,)) _test_weights_type_struct_float_tensor = ( (tf.float32,",
"('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx,",
"import tensorflow as tf import tensorflow_federated as tff from compressed_communication.broadcasters import histogram_model _mn",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0, 3.0], [2, 1, 0, 0]),",
"either express or implied. # See the License for the specific language governing",
"@parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0, 3.0], [2, 1, 0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0,",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"weights_type, _mn, _mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(()) expected_initialize_type = tff.FunctionType( parameter=None,",
"test_histogram_impl(self, weights_type, weights, expected_histogram): weights_type = tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx,",
"result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)),",
"result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0,",
"the specific language governing permissions and # limitations under the License. import collections",
"_nbins) state = histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram) result = histogram_broadcaster.next(state,",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"weights).measurements self.assertAllEqual(histogram, expected_histogram) result = histogram_broadcaster.next(state, weights).result self.assertAllClose(result, weights) if __name__ == '__main__':",
"_test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor,",
"2.0, 3.0], [1.0, 1.0]], [4, 1, 0, 0])) def test_histogram_impl(self, weights_type, weights, expected_histogram):",
"0])) def test_histogram_impl(self, weights_type, weights, expected_histogram): weights_type = tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type,",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"(3,)) _test_weights_type_struct_float_tensor = ( (tf.float32, (3,)), (tf.float32, (2,))) _test_measurements_type = (tf.int32, (_nbins,)) def",
"_histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor,",
"file except in compliance with the License. # You may obtain a copy",
"self.assertAllEqual(histogram, expected_histogram) result = histogram_broadcaster.next(state, weights).result self.assertAllClose(result, weights) if __name__ == '__main__': tff.backends.native.set_local_python_execution_context(10)",
"1, 0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0], [1.0, 1.0]], [4, 1, 0,",
"histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram) result = histogram_broadcaster.next(state, weights).result self.assertAllClose(result, weights)",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"License for the specific language governing permissions and # limitations under the License.",
"[2, 1, 0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0], [1.0, 1.0]], [4, 1,",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"4 _test_weights_type_float_tensor = (tf.float32, (3,)) _test_weights_type_struct_float_tensor = ( (tf.float32, (3,)), (tf.float32, (2,))) _test_measurements_type",
"import parameterized import tensorflow as tf import tensorflow_federated as tff from compressed_communication.broadcasters import",
"the License. # You may obtain a copy of the License at #",
"parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type,",
"weights_type = tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) state = histogram_broadcaster.initialize()",
"@parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process =",
"0, 0])) def test_histogram_impl(self, weights_type, weights, expected_histogram): weights_type = tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess(",
"to in writing, software # distributed under the License is distributed on an",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType( parameter=collections.OrderedDict(",
"(tf.float32, (3,)) _test_weights_type_struct_float_tensor = ( (tf.float32, (3,)), (tf.float32, (2,))) _test_measurements_type = (tf.int32, (_nbins,))",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"10.0 _nbins = 4 _test_weights_type_float_tensor = (tf.float32, (3,)) _test_weights_type_struct_float_tensor = ( (tf.float32, (3,)),",
"implied. # See the License for the specific language governing permissions and #",
"= histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) self.assertIsInstance(broadcast_process, tff.templates.MeasuredProcess) server_state_type = tff.type_at_server(()) expected_initialize_type =",
"= tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class",
"('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0], [1.0, 1.0]], [4, 1, 0, 0])) def test_histogram_impl(self,",
"\"License\"); # you may not use this file except in compliance with the",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True),",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"required by applicable law or agreed to in writing, software # distributed under",
"weights_type, weights, expected_histogram): weights_type = tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins)",
"broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type,",
"as tf import tensorflow_federated as tff from compressed_communication.broadcasters import histogram_model _mn = 0.0",
"('float_tensor', _test_weights_type_float_tensor, [1.0, 2.0, 3.0], [2, 1, 0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0,",
"applicable law or agreed to in writing, software # distributed under the License",
"1, 0, 0])) def test_histogram_impl(self, weights_type, weights, expected_histogram): weights_type = tff.to_type(weights_type) histogram_broadcaster =",
"0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0], [1.0, 1.0]], [4, 1, 0, 0])) def",
"Google LLC. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"LLC. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"and # limitations under the License. import collections from absl.testing import parameterized import",
"HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self, weights_type, expected_measurements_type):",
"3.0], [2, 1, 0, 0]), ('struct_float_tensor', _test_weights_type_struct_float_tensor, [[1.0, 2.0, 3.0], [1.0, 1.0]], [4,",
"or agreed to in writing, software # distributed under the License is distributed",
"= tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType(",
"from absl.testing import parameterized import tensorflow as tf import tensorflow_federated as tff from",
"(_nbins,)) def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters(",
"or implied. # See the License for the specific language governing permissions and",
"result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor,",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"absl.testing import parameterized import tensorflow as tf import tensorflow_federated as tff from compressed_communication.broadcasters",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput(",
"(3,)), (tf.float32, (2,))) _test_measurements_type = (tf.int32, (_nbins,)) def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn,",
"tff.type_at_server(()) expected_initialize_type = tff.FunctionType( parameter=None, result=server_state_type) tff.test.assert_types_equivalent( broadcast_process.initialize.type_signature, expected_initialize_type) expected_measurements_type = tff.to_type(expected_measurements_type) expected_next_type",
"= tff.to_type(weights_type) histogram_broadcaster = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) state = histogram_broadcaster.initialize() histogram",
"permissions and # limitations under the License. import collections from absl.testing import parameterized",
"with the License. # You may obtain a copy of the License at",
"(tf.int32, (_nbins,)) def _histogram_model(): return histogram_model.HistogramModelBroadcastProcess( _test_weights_type_struct_float_tensor, _mn, _mx, _nbins) class HistogramModelComputationTest(tf.test.TestCase, parameterized.TestCase):",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"_mn, _mx, _nbins) state = histogram_broadcaster.initialize() histogram = histogram_broadcaster.next(state, weights).measurements self.assertAllEqual(histogram, expected_histogram) result",
"in writing, software # distributed under the License is distributed on an \"AS",
"limitations under the License. import collections from absl.testing import parameterized import tensorflow as",
"state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature, expected_next_type) class HistogramModelExecutionTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('float_tensor', _test_weights_type_float_tensor, [1.0,",
"_test_measurements_type)) def test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess( weights_type, _mn, _mx, _nbins) self.assertIsInstance(broadcast_process,",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"tff.to_type(expected_measurements_type) expected_next_type = tff.FunctionType( parameter=collections.OrderedDict( state=server_state_type, weights=tff.type_at_server(weights_type)), result=tff.templates.MeasuredProcessOutput( state=server_state_type, result=tff.type_at_clients(weights_type, all_equal=True), measurements=tff.type_at_server(expected_measurements_type))) tff.test.assert_types_equivalent(broadcast_process.next.type_signature,",
"('float_tensor', _test_weights_type_float_tensor, _test_measurements_type), ('struct_float_tensor', _test_weights_type_struct_float_tensor, _test_measurements_type)) def test_historgram_type_properties(self, weights_type, expected_measurements_type): broadcast_process = histogram_model.HistogramModelBroadcastProcess("
] |
[
"** zoom xtile = int((lon_deg + 180.0) / 360.0 * n) ytile =",
"cur = conn.cursor() bboxStr = \"-180,-85,180,85\" if BBOX is None else \",\".join(map(str, BBOX))",
"for y in range(ystart, yend+1): download_url(zoom, x, y, cur) conn.commit() cur.close() conn.close() main(argv)",
"or \"overlay\" LAYERNAME = \"OSM Low Detail\" TILE_FORMAT = \"png\" def deg2num(lat_deg, lon_deg,",
"import urllib.request import random import os.path import sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX =",
"> 0: print('Skipping ' + url) return print(\"downloading %r\" % url) request =",
"math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n) return (xtile,",
"tile_column, tile_row); INSERT OR REPLACE INTO metadata VALUES('minzoom', '1'); INSERT OR REPLACE INTO",
"CREATE TABLE IF NOT EXISTS metadata(name text, value text); CREATE UNIQUE INDEX IF",
"existing[0][0] > 0: print('Skipping ' + url) return print(\"downloading %r\" % url) request",
"TABLE IF NOT EXISTS metadata(name text, value text); CREATE UNIQUE INDEX IF NOT",
"if len(argv) > 1 else 'osm.mbtiles' conn = sqlite3.connect(db) cur = conn.cursor() bboxStr",
"TILE_FORMAT, bboxStr)) # from 0 to 6 download all for zoom in range(0,",
"all for zoom in range(0, ZOOM_MAX+1): xstart = 0 ystart = 0 xend",
"xtile, yinverted, content)) def main(argv): db = argv[1] if len(argv) > 1 else",
"(zoom, xtile, ytile) ymax = 1 << zoom yinverted = ymax - ytile",
"bboxStr)) # from 0 to 6 download all for zoom in range(0, ZOOM_MAX+1):",
"int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)",
"VALUES('name', '{1}'); INSERT OR REPLACE INTO metadata VALUES('type', '{2}'); INSERT OR REPLACE INTO",
"(xtile, ytile) def download_url(zoom, xtile, ytile, cursor): subdomain = random.randint(1, 4) url =",
"- math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n) return",
"tile_row, tile_data) VALUES(?, ?, ?, ?)', (zoom, xtile, yinverted, content)) def main(argv): db",
"INTO metadata VALUES('name', '{1}'); INSERT OR REPLACE INTO metadata VALUES('type', '{2}'); INSERT OR",
") source = urllib.request.urlopen(request) content = source.read() source.close() cursor.execute('INSERT INTO tiles(zoom_level, tile_column, tile_row,",
"None # [lon_min, lat_min, lon_max, lat_max] or None for whole world ZOOM_MAX =",
"zoom in range(0, ZOOM_MAX+1): xstart = 0 ystart = 0 xend = 2**zoom-1",
"ytile) def download_url(zoom, xtile, ytile, cursor): subdomain = random.randint(1, 4) url = URL_TEMPLATE",
"else \",\".join(map(str, BBOX)) cur.executescript(''' CREATE TABLE IF NOT EXISTS tiles ( zoom_level integer,",
"URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None # [lon_min, lat_min, lon_max, lat_max] or None",
"whole world ZOOM_MAX = 7 LAYERTYPE = \"baselayer\" # \"baselayer\" or \"overlay\" LAYERNAME",
"import os.path import sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None # [lon_min, lat_min,",
"> 1 else 'osm.mbtiles' conn = sqlite3.connect(db) cur = conn.cursor() bboxStr = \"-180,-85,180,85\"",
"range(0, ZOOM_MAX+1): xstart = 0 ystart = 0 xend = 2**zoom-1 yend =",
"xtile, yinverted)).fetchall() if existing[0][0] > 0: print('Skipping ' + url) return print(\"downloading %r\"",
"\"OSM Low Detail\" TILE_FORMAT = \"png\" def deg2num(lat_deg, lon_deg, zoom): lat_rad = math.radians(lat_deg)",
"'{0}'); INSERT OR REPLACE INTO metadata VALUES('name', '{1}'); INSERT OR REPLACE INTO metadata",
"EXISTS metadata_name on metadata (name); CREATE UNIQUE INDEX IF NOT EXISTS tile_index on",
"1 existing = cursor.execute('SELECT count(*) FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?',",
"metadata VALUES('name', '{1}'); INSERT OR REPLACE INTO metadata VALUES('type', '{2}'); INSERT OR REPLACE",
"OR REPLACE INTO metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr)) # from",
"UNIQUE INDEX IF NOT EXISTS tile_index on tiles(zoom_level, tile_column, tile_row); INSERT OR REPLACE",
"tiles(zoom_level, tile_column, tile_row); INSERT OR REPLACE INTO metadata VALUES('minzoom', '1'); INSERT OR REPLACE",
"tile_column=? AND tile_row=?', (zoom, xtile, yinverted)).fetchall() if existing[0][0] > 0: print('Skipping ' +",
"CREATE UNIQUE INDEX IF NOT EXISTS tile_index on tiles(zoom_level, tile_column, tile_row); INSERT OR",
"2**zoom-1 if BBOX is not None: xstart, yend = deg2num(BBOX[1], BBOX[0], zoom) xend,",
"2.0 ** zoom xtile = int((lon_deg + 180.0) / 360.0 * n) ytile",
"( zoom_level integer, tile_column integer, tile_row integer, tile_data blob); CREATE TABLE IF NOT",
"on tiles(zoom_level, tile_column, tile_row); INSERT OR REPLACE INTO metadata VALUES('minzoom', '1'); INSERT OR",
"urllib.request import random import os.path import sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None",
"= 1 << zoom yinverted = ymax - ytile - 1 existing =",
"metadata VALUES('type', '{2}'); INSERT OR REPLACE INTO metadata VALUES('format', '{3}'); INSERT OR REPLACE",
"= 2**zoom-1 if BBOX is not None: xstart, yend = deg2num(BBOX[1], BBOX[0], zoom)",
"IF NOT EXISTS tiles ( zoom_level integer, tile_column integer, tile_row integer, tile_data blob);",
"= URL_TEMPLATE % (zoom, xtile, ytile) ymax = 1 << zoom yinverted =",
"deg2num(BBOX[3], BBOX[2], zoom) for x in range(xstart, xend+1): for y in range(ystart, yend+1):",
"= sqlite3.connect(db) cur = conn.cursor() bboxStr = \"-180,-85,180,85\" if BBOX is None else",
"AND tile_column=? AND tile_row=?', (zoom, xtile, yinverted)).fetchall() if existing[0][0] > 0: print('Skipping '",
"360.0 * n) ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) /",
"(zoom, xtile, yinverted, content)) def main(argv): db = argv[1] if len(argv) > 1",
"INSERT OR REPLACE INTO metadata VALUES('type', '{2}'); INSERT OR REPLACE INTO metadata VALUES('format',",
"import os import math import urllib.request import random import os.path import sqlite3 URL_TEMPLATE",
"conn = sqlite3.connect(db) cur = conn.cursor() bboxStr = \"-180,-85,180,85\" if BBOX is None",
"REPLACE INTO metadata VALUES('format', '{3}'); INSERT OR REPLACE INTO metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX,",
"zoom_level integer, tile_column integer, tile_row integer, tile_data blob); CREATE TABLE IF NOT EXISTS",
"?, ?)', (zoom, xtile, yinverted, content)) def main(argv): db = argv[1] if len(argv)",
"zoom yinverted = ymax - ytile - 1 existing = cursor.execute('SELECT count(*) FROM",
"BBOX = None # [lon_min, lat_min, lon_max, lat_max] or None for whole world",
"main(argv): db = argv[1] if len(argv) > 1 else 'osm.mbtiles' conn = sqlite3.connect(db)",
"'''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr)) # from 0 to 6 download all for",
"Detail\" TILE_FORMAT = \"png\" def deg2num(lat_deg, lon_deg, zoom): lat_rad = math.radians(lat_deg) n =",
"INTO metadata VALUES('format', '{3}'); INSERT OR REPLACE INTO metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME,",
"IF NOT EXISTS metadata_name on metadata (name); CREATE UNIQUE INDEX IF NOT EXISTS",
"= int((lon_deg + 180.0) / 360.0 * n) ytile = int((1.0 - math.log(math.tan(lat_rad)",
"content = source.read() source.close() cursor.execute('INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data) VALUES(?, ?, ?,",
"from 0 to 6 download all for zoom in range(0, ZOOM_MAX+1): xstart =",
"sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None # [lon_min, lat_min, lon_max, lat_max] or",
"tile_data) VALUES(?, ?, ?, ?)', (zoom, xtile, yinverted, content)) def main(argv): db =",
"'1'); INSERT OR REPLACE INTO metadata VALUES('maxzoom', '{0}'); INSERT OR REPLACE INTO metadata",
"zoom): lat_rad = math.radians(lat_deg) n = 2.0 ** zoom xtile = int((lon_deg +",
"not None: xstart, yend = deg2num(BBOX[1], BBOX[0], zoom) xend, ystart = deg2num(BBOX[3], BBOX[2],",
"import math import urllib.request import random import os.path import sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\"",
"INSERT OR REPLACE INTO metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr)) #",
"\"baselayer\" or \"overlay\" LAYERNAME = \"OSM Low Detail\" TILE_FORMAT = \"png\" def deg2num(lat_deg,",
"if BBOX is not None: xstart, yend = deg2num(BBOX[1], BBOX[0], zoom) xend, ystart",
"= urllib.request.Request( url, data=None, headers={ 'User-Agent': 'Low-Zoom Downloader' } ) source = urllib.request.urlopen(request)",
"= urllib.request.urlopen(request) content = source.read() source.close() cursor.execute('INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data) VALUES(?,",
"None for whole world ZOOM_MAX = 7 LAYERTYPE = \"baselayer\" # \"baselayer\" or",
"2**zoom-1 yend = 2**zoom-1 if BBOX is not None: xstart, yend = deg2num(BBOX[1],",
"metadata VALUES('format', '{3}'); INSERT OR REPLACE INTO metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE,",
"tile_data blob); CREATE TABLE IF NOT EXISTS metadata(name text, value text); CREATE UNIQUE",
"180.0) / 360.0 * n) ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 /",
"BBOX[0], zoom) xend, ystart = deg2num(BBOX[3], BBOX[2], zoom) for x in range(xstart, xend+1):",
"+ 180.0) / 360.0 * n) ytile = int((1.0 - math.log(math.tan(lat_rad) + (1",
"download_url(zoom, xtile, ytile, cursor): subdomain = random.randint(1, 4) url = URL_TEMPLATE % (zoom,",
"'{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr)) # from 0 to 6 download all",
"len(argv) > 1 else 'osm.mbtiles' conn = sqlite3.connect(db) cur = conn.cursor() bboxStr =",
"tile_index on tiles(zoom_level, tile_column, tile_row); INSERT OR REPLACE INTO metadata VALUES('minzoom', '1'); INSERT",
"\"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None # [lon_min, lat_min, lon_max, lat_max] or None for whole",
"WHERE zoom_level=? AND tile_column=? AND tile_row=?', (zoom, xtile, yinverted)).fetchall() if existing[0][0] > 0:",
"in range(0, ZOOM_MAX+1): xstart = 0 ystart = 0 xend = 2**zoom-1 yend",
"0 ystart = 0 xend = 2**zoom-1 yend = 2**zoom-1 if BBOX is",
"[lon_min, lat_min, lon_max, lat_max] or None for whole world ZOOM_MAX = 7 LAYERTYPE",
"- 1 existing = cursor.execute('SELECT count(*) FROM tiles WHERE zoom_level=? AND tile_column=? AND",
"#!/usr/bin/python3 from sys import argv import os import math import urllib.request import random",
"xend, ystart = deg2num(BBOX[3], BBOX[2], zoom) for x in range(xstart, xend+1): for y",
"tile_row); INSERT OR REPLACE INTO metadata VALUES('minzoom', '1'); INSERT OR REPLACE INTO metadata",
"= ymax - ytile - 1 existing = cursor.execute('SELECT count(*) FROM tiles WHERE",
"VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr)) # from 0 to 6 download",
"lon_deg, zoom): lat_rad = math.radians(lat_deg) n = 2.0 ** zoom xtile = int((lon_deg",
"data=None, headers={ 'User-Agent': 'Low-Zoom Downloader' } ) source = urllib.request.urlopen(request) content = source.read()",
"'osm.mbtiles' conn = sqlite3.connect(db) cur = conn.cursor() bboxStr = \"-180,-85,180,85\" if BBOX is",
"metadata (name); CREATE UNIQUE INDEX IF NOT EXISTS tile_index on tiles(zoom_level, tile_column, tile_row);",
"math import urllib.request import random import os.path import sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX",
"0 xend = 2**zoom-1 yend = 2**zoom-1 if BBOX is not None: xstart,",
"metadata VALUES('maxzoom', '{0}'); INSERT OR REPLACE INTO metadata VALUES('name', '{1}'); INSERT OR REPLACE",
"or None for whole world ZOOM_MAX = 7 LAYERTYPE = \"baselayer\" # \"baselayer\"",
"lat_min, lon_max, lat_max] or None for whole world ZOOM_MAX = 7 LAYERTYPE =",
"is not None: xstart, yend = deg2num(BBOX[1], BBOX[0], zoom) xend, ystart = deg2num(BBOX[3],",
"yend = deg2num(BBOX[1], BBOX[0], zoom) xend, ystart = deg2num(BBOX[3], BBOX[2], zoom) for x",
"EXISTS tiles ( zoom_level integer, tile_column integer, tile_row integer, tile_data blob); CREATE TABLE",
"= cursor.execute('SELECT count(*) FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?', (zoom, xtile,",
"= \"-180,-85,180,85\" if BBOX is None else \",\".join(map(str, BBOX)) cur.executescript(''' CREATE TABLE IF",
"0 to 6 download all for zoom in range(0, ZOOM_MAX+1): xstart = 0",
"headers={ 'User-Agent': 'Low-Zoom Downloader' } ) source = urllib.request.urlopen(request) content = source.read() source.close()",
"source.read() source.close() cursor.execute('INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data) VALUES(?, ?, ?, ?)', (zoom,",
"subdomain = random.randint(1, 4) url = URL_TEMPLATE % (zoom, xtile, ytile) ymax =",
"bboxStr = \"-180,-85,180,85\" if BBOX is None else \",\".join(map(str, BBOX)) cur.executescript(''' CREATE TABLE",
"tiles ( zoom_level integer, tile_column integer, tile_row integer, tile_data blob); CREATE TABLE IF",
"VALUES('type', '{2}'); INSERT OR REPLACE INTO metadata VALUES('format', '{3}'); INSERT OR REPLACE INTO",
"ystart = deg2num(BBOX[3], BBOX[2], zoom) for x in range(xstart, xend+1): for y in",
"tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?', (zoom, xtile, yinverted)).fetchall() if existing[0][0] >",
"for whole world ZOOM_MAX = 7 LAYERTYPE = \"baselayer\" # \"baselayer\" or \"overlay\"",
"# \"baselayer\" or \"overlay\" LAYERNAME = \"OSM Low Detail\" TILE_FORMAT = \"png\" def",
"argv[1] if len(argv) > 1 else 'osm.mbtiles' conn = sqlite3.connect(db) cur = conn.cursor()",
"= source.read() source.close() cursor.execute('INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data) VALUES(?, ?, ?, ?)',",
"conn.cursor() bboxStr = \"-180,-85,180,85\" if BBOX is None else \",\".join(map(str, BBOX)) cur.executescript(''' CREATE",
"url = URL_TEMPLATE % (zoom, xtile, ytile) ymax = 1 << zoom yinverted",
"<< zoom yinverted = ymax - ytile - 1 existing = cursor.execute('SELECT count(*)",
"xtile = int((lon_deg + 180.0) / 360.0 * n) ytile = int((1.0 -",
"Downloader' } ) source = urllib.request.urlopen(request) content = source.read() source.close() cursor.execute('INSERT INTO tiles(zoom_level,",
"'User-Agent': 'Low-Zoom Downloader' } ) source = urllib.request.urlopen(request) content = source.read() source.close() cursor.execute('INSERT",
"ZOOM_MAX+1): xstart = 0 ystart = 0 xend = 2**zoom-1 yend = 2**zoom-1",
"os import math import urllib.request import random import os.path import sqlite3 URL_TEMPLATE =",
"= deg2num(BBOX[3], BBOX[2], zoom) for x in range(xstart, xend+1): for y in range(ystart,",
"yinverted = ymax - ytile - 1 existing = cursor.execute('SELECT count(*) FROM tiles",
"n) return (xtile, ytile) def download_url(zoom, xtile, ytile, cursor): subdomain = random.randint(1, 4)",
"ytile - 1 existing = cursor.execute('SELECT count(*) FROM tiles WHERE zoom_level=? AND tile_column=?",
"ystart = 0 xend = 2**zoom-1 yend = 2**zoom-1 if BBOX is not",
"= \"OSM Low Detail\" TILE_FORMAT = \"png\" def deg2num(lat_deg, lon_deg, zoom): lat_rad =",
"tile_row=?', (zoom, xtile, yinverted)).fetchall() if existing[0][0] > 0: print('Skipping ' + url) return",
"url) return print(\"downloading %r\" % url) request = urllib.request.Request( url, data=None, headers={ 'User-Agent':",
"random.randint(1, 4) url = URL_TEMPLATE % (zoom, xtile, ytile) ymax = 1 <<",
"IF NOT EXISTS tile_index on tiles(zoom_level, tile_column, tile_row); INSERT OR REPLACE INTO metadata",
"for zoom in range(0, ZOOM_MAX+1): xstart = 0 ystart = 0 xend =",
"REPLACE INTO metadata VALUES('minzoom', '1'); INSERT OR REPLACE INTO metadata VALUES('maxzoom', '{0}'); INSERT",
"import sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None # [lon_min, lat_min, lon_max, lat_max]",
"deg2num(lat_deg, lon_deg, zoom): lat_rad = math.radians(lat_deg) n = 2.0 ** zoom xtile =",
"n = 2.0 ** zoom xtile = int((lon_deg + 180.0) / 360.0 *",
"sys import argv import os import math import urllib.request import random import os.path",
"REPLACE INTO metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr)) # from 0",
"yend = 2**zoom-1 if BBOX is not None: xstart, yend = deg2num(BBOX[1], BBOX[0],",
"NOT EXISTS tile_index on tiles(zoom_level, tile_column, tile_row); INSERT OR REPLACE INTO metadata VALUES('minzoom',",
"value text); CREATE UNIQUE INDEX IF NOT EXISTS metadata_name on metadata (name); CREATE",
"* n) ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi)",
"else 'osm.mbtiles' conn = sqlite3.connect(db) cur = conn.cursor() bboxStr = \"-180,-85,180,85\" if BBOX",
"url, data=None, headers={ 'User-Agent': 'Low-Zoom Downloader' } ) source = urllib.request.urlopen(request) content =",
"xend+1): for y in range(ystart, yend+1): download_url(zoom, x, y, cur) conn.commit() cur.close() conn.close()",
"existing = cursor.execute('SELECT count(*) FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?', (zoom,",
"(zoom, xtile, yinverted)).fetchall() if existing[0][0] > 0: print('Skipping ' + url) return print(\"downloading",
"?)', (zoom, xtile, yinverted, content)) def main(argv): db = argv[1] if len(argv) >",
"= 0 xend = 2**zoom-1 yend = 2**zoom-1 if BBOX is not None:",
"math.pi) / 2.0 * n) return (xtile, ytile) def download_url(zoom, xtile, ytile, cursor):",
"on metadata (name); CREATE UNIQUE INDEX IF NOT EXISTS tile_index on tiles(zoom_level, tile_column,",
"INTO metadata VALUES('maxzoom', '{0}'); INSERT OR REPLACE INTO metadata VALUES('name', '{1}'); INSERT OR",
"= conn.cursor() bboxStr = \"-180,-85,180,85\" if BBOX is None else \",\".join(map(str, BBOX)) cur.executescript('''",
"NOT EXISTS tiles ( zoom_level integer, tile_column integer, tile_row integer, tile_data blob); CREATE",
"zoom xtile = int((lon_deg + 180.0) / 360.0 * n) ytile = int((1.0",
"REPLACE INTO metadata VALUES('type', '{2}'); INSERT OR REPLACE INTO metadata VALUES('format', '{3}'); INSERT",
"urllib.request.Request( url, data=None, headers={ 'User-Agent': 'Low-Zoom Downloader' } ) source = urllib.request.urlopen(request) content",
"CREATE UNIQUE INDEX IF NOT EXISTS metadata_name on metadata (name); CREATE UNIQUE INDEX",
"= 2.0 ** zoom xtile = int((lon_deg + 180.0) / 360.0 * n)",
"LAYERTYPE = \"baselayer\" # \"baselayer\" or \"overlay\" LAYERNAME = \"OSM Low Detail\" TILE_FORMAT",
"INSERT OR REPLACE INTO metadata VALUES('name', '{1}'); INSERT OR REPLACE INTO metadata VALUES('type',",
"random import os.path import sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None # [lon_min,",
"if BBOX is None else \",\".join(map(str, BBOX)) cur.executescript(''' CREATE TABLE IF NOT EXISTS",
"yinverted, content)) def main(argv): db = argv[1] if len(argv) > 1 else 'osm.mbtiles'",
"IF NOT EXISTS metadata(name text, value text); CREATE UNIQUE INDEX IF NOT EXISTS",
"%r\" % url) request = urllib.request.Request( url, data=None, headers={ 'User-Agent': 'Low-Zoom Downloader' }",
"OR REPLACE INTO metadata VALUES('format', '{3}'); INSERT OR REPLACE INTO metadata VALUES('bounds', '{4}');",
"ytile, cursor): subdomain = random.randint(1, 4) url = URL_TEMPLATE % (zoom, xtile, ytile)",
"os.path import sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None # [lon_min, lat_min, lon_max,",
"VALUES('minzoom', '1'); INSERT OR REPLACE INTO metadata VALUES('maxzoom', '{0}'); INSERT OR REPLACE INTO",
"OR REPLACE INTO metadata VALUES('name', '{1}'); INSERT OR REPLACE INTO metadata VALUES('type', '{2}');",
"= 0 ystart = 0 xend = 2**zoom-1 yend = 2**zoom-1 if BBOX",
"VALUES('maxzoom', '{0}'); INSERT OR REPLACE INTO metadata VALUES('name', '{1}'); INSERT OR REPLACE INTO",
"1 else 'osm.mbtiles' conn = sqlite3.connect(db) cur = conn.cursor() bboxStr = \"-180,-85,180,85\" if",
"zoom_level=? AND tile_column=? AND tile_row=?', (zoom, xtile, yinverted)).fetchall() if existing[0][0] > 0: print('Skipping",
"INDEX IF NOT EXISTS metadata_name on metadata (name); CREATE UNIQUE INDEX IF NOT",
"# [lon_min, lat_min, lon_max, lat_max] or None for whole world ZOOM_MAX = 7",
"lat_max] or None for whole world ZOOM_MAX = 7 LAYERTYPE = \"baselayer\" #",
"- ytile - 1 existing = cursor.execute('SELECT count(*) FROM tiles WHERE zoom_level=? AND",
"xtile, ytile) ymax = 1 << zoom yinverted = ymax - ytile -",
"content)) def main(argv): db = argv[1] if len(argv) > 1 else 'osm.mbtiles' conn",
"BBOX)) cur.executescript(''' CREATE TABLE IF NOT EXISTS tiles ( zoom_level integer, tile_column integer,",
"cursor): subdomain = random.randint(1, 4) url = URL_TEMPLATE % (zoom, xtile, ytile) ymax",
"= math.radians(lat_deg) n = 2.0 ** zoom xtile = int((lon_deg + 180.0) /",
"None: xstart, yend = deg2num(BBOX[1], BBOX[0], zoom) xend, ystart = deg2num(BBOX[3], BBOX[2], zoom)",
"db = argv[1] if len(argv) > 1 else 'osm.mbtiles' conn = sqlite3.connect(db) cur",
"OR REPLACE INTO metadata VALUES('type', '{2}'); INSERT OR REPLACE INTO metadata VALUES('format', '{3}');",
"text, value text); CREATE UNIQUE INDEX IF NOT EXISTS metadata_name on metadata (name);",
"yinverted)).fetchall() if existing[0][0] > 0: print('Skipping ' + url) return print(\"downloading %r\" %",
"OR REPLACE INTO metadata VALUES('minzoom', '1'); INSERT OR REPLACE INTO metadata VALUES('maxzoom', '{0}');",
"'Low-Zoom Downloader' } ) source = urllib.request.urlopen(request) content = source.read() source.close() cursor.execute('INSERT INTO",
"= 2**zoom-1 yend = 2**zoom-1 if BBOX is not None: xstart, yend =",
"= None # [lon_min, lat_min, lon_max, lat_max] or None for whole world ZOOM_MAX",
"metadata(name text, value text); CREATE UNIQUE INDEX IF NOT EXISTS metadata_name on metadata",
"'{1}'); INSERT OR REPLACE INTO metadata VALUES('type', '{2}'); INSERT OR REPLACE INTO metadata",
"Low Detail\" TILE_FORMAT = \"png\" def deg2num(lat_deg, lon_deg, zoom): lat_rad = math.radians(lat_deg) n",
"6 download all for zoom in range(0, ZOOM_MAX+1): xstart = 0 ystart =",
"from sys import argv import os import math import urllib.request import random import",
"cursor.execute('SELECT count(*) FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?', (zoom, xtile, yinverted)).fetchall()",
"INTO metadata VALUES('minzoom', '1'); INSERT OR REPLACE INTO metadata VALUES('maxzoom', '{0}'); INSERT OR",
"deg2num(BBOX[1], BBOX[0], zoom) xend, ystart = deg2num(BBOX[3], BBOX[2], zoom) for x in range(xstart,",
"TABLE IF NOT EXISTS tiles ( zoom_level integer, tile_column integer, tile_row integer, tile_data",
"(name); CREATE UNIQUE INDEX IF NOT EXISTS tile_index on tiles(zoom_level, tile_column, tile_row); INSERT",
"'{3}'); INSERT OR REPLACE INTO metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr))",
"INTO tiles(zoom_level, tile_column, tile_row, tile_data) VALUES(?, ?, ?, ?)', (zoom, xtile, yinverted, content))",
"metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr)) # from 0 to 6",
"/ math.cos(lat_rad))) / math.pi) / 2.0 * n) return (xtile, ytile) def download_url(zoom,",
"zoom) for x in range(xstart, xend+1): for y in range(ystart, yend+1): download_url(zoom, x,",
"= \"baselayer\" # \"baselayer\" or \"overlay\" LAYERNAME = \"OSM Low Detail\" TILE_FORMAT =",
"BBOX is not None: xstart, yend = deg2num(BBOX[1], BBOX[0], zoom) xend, ystart =",
"/ 2.0 * n) return (xtile, ytile) def download_url(zoom, xtile, ytile, cursor): subdomain",
"REPLACE INTO metadata VALUES('name', '{1}'); INSERT OR REPLACE INTO metadata VALUES('type', '{2}'); INSERT",
"NOT EXISTS metadata_name on metadata (name); CREATE UNIQUE INDEX IF NOT EXISTS tile_index",
"EXISTS metadata(name text, value text); CREATE UNIQUE INDEX IF NOT EXISTS metadata_name on",
"import random import os.path import sqlite3 URL_TEMPLATE = \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None #",
"4) url = URL_TEMPLATE % (zoom, xtile, ytile) ymax = 1 << zoom",
"= deg2num(BBOX[1], BBOX[0], zoom) xend, ystart = deg2num(BBOX[3], BBOX[2], zoom) for x in",
"integer, tile_column integer, tile_row integer, tile_data blob); CREATE TABLE IF NOT EXISTS metadata(name",
"INSERT OR REPLACE INTO metadata VALUES('maxzoom', '{0}'); INSERT OR REPLACE INTO metadata VALUES('name',",
"INSERT OR REPLACE INTO metadata VALUES('minzoom', '1'); INSERT OR REPLACE INTO metadata VALUES('maxzoom',",
"xstart = 0 ystart = 0 xend = 2**zoom-1 yend = 2**zoom-1 if",
"math.cos(lat_rad))) / math.pi) / 2.0 * n) return (xtile, ytile) def download_url(zoom, xtile,",
"xend = 2**zoom-1 yend = 2**zoom-1 if BBOX is not None: xstart, yend",
"def download_url(zoom, xtile, ytile, cursor): subdomain = random.randint(1, 4) url = URL_TEMPLATE %",
"range(xstart, xend+1): for y in range(ystart, yend+1): download_url(zoom, x, y, cur) conn.commit() cur.close()",
"\"baselayer\" # \"baselayer\" or \"overlay\" LAYERNAME = \"OSM Low Detail\" TILE_FORMAT = \"png\"",
"integer, tile_data blob); CREATE TABLE IF NOT EXISTS metadata(name text, value text); CREATE",
"url) request = urllib.request.Request( url, data=None, headers={ 'User-Agent': 'Low-Zoom Downloader' } ) source",
"x in range(xstart, xend+1): for y in range(ystart, yend+1): download_url(zoom, x, y, cur)",
"EXISTS tile_index on tiles(zoom_level, tile_column, tile_row); INSERT OR REPLACE INTO metadata VALUES('minzoom', '1');",
"lon_max, lat_max] or None for whole world ZOOM_MAX = 7 LAYERTYPE = \"baselayer\"",
"sqlite3.connect(db) cur = conn.cursor() bboxStr = \"-180,-85,180,85\" if BBOX is None else \",\".join(map(str,",
"* n) return (xtile, ytile) def download_url(zoom, xtile, ytile, cursor): subdomain = random.randint(1,",
"AND tile_row=?', (zoom, xtile, yinverted)).fetchall() if existing[0][0] > 0: print('Skipping ' + url)",
"xstart, yend = deg2num(BBOX[1], BBOX[0], zoom) xend, ystart = deg2num(BBOX[3], BBOX[2], zoom) for",
"FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?', (zoom, xtile, yinverted)).fetchall() if existing[0][0]",
"= \"https://c.tile.openstreetmap.org/%d/%d/%d.png\" BBOX = None # [lon_min, lat_min, lon_max, lat_max] or None for",
"math.radians(lat_deg) n = 2.0 ** zoom xtile = int((lon_deg + 180.0) / 360.0",
"source = urllib.request.urlopen(request) content = source.read() source.close() cursor.execute('INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data)",
"INTO metadata VALUES('type', '{2}'); INSERT OR REPLACE INTO metadata VALUES('format', '{3}'); INSERT OR",
"cursor.execute('INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data) VALUES(?, ?, ?, ?)', (zoom, xtile, yinverted,",
"metadata VALUES('minzoom', '1'); INSERT OR REPLACE INTO metadata VALUES('maxzoom', '{0}'); INSERT OR REPLACE",
"integer, tile_row integer, tile_data blob); CREATE TABLE IF NOT EXISTS metadata(name text, value",
"world ZOOM_MAX = 7 LAYERTYPE = \"baselayer\" # \"baselayer\" or \"overlay\" LAYERNAME =",
"INSERT OR REPLACE INTO metadata VALUES('format', '{3}'); INSERT OR REPLACE INTO metadata VALUES('bounds',",
"/ 360.0 * n) ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad)))",
"} ) source = urllib.request.urlopen(request) content = source.read() source.close() cursor.execute('INSERT INTO tiles(zoom_level, tile_column,",
"for x in range(xstart, xend+1): for y in range(ystart, yend+1): download_url(zoom, x, y,",
"ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0",
"\",\".join(map(str, BBOX)) cur.executescript(''' CREATE TABLE IF NOT EXISTS tiles ( zoom_level integer, tile_column",
"= argv[1] if len(argv) > 1 else 'osm.mbtiles' conn = sqlite3.connect(db) cur =",
"\"overlay\" LAYERNAME = \"OSM Low Detail\" TILE_FORMAT = \"png\" def deg2num(lat_deg, lon_deg, zoom):",
"LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr)) # from 0 to 6 download all for zoom",
"\"-180,-85,180,85\" if BBOX is None else \",\".join(map(str, BBOX)) cur.executescript(''' CREATE TABLE IF NOT",
"xtile, ytile, cursor): subdomain = random.randint(1, 4) url = URL_TEMPLATE % (zoom, xtile,",
"TILE_FORMAT = \"png\" def deg2num(lat_deg, lon_deg, zoom): lat_rad = math.radians(lat_deg) n = 2.0",
"/ math.pi) / 2.0 * n) return (xtile, ytile) def download_url(zoom, xtile, ytile,",
"None else \",\".join(map(str, BBOX)) cur.executescript(''' CREATE TABLE IF NOT EXISTS tiles ( zoom_level",
"LAYERTYPE, TILE_FORMAT, bboxStr)) # from 0 to 6 download all for zoom in",
"download all for zoom in range(0, ZOOM_MAX+1): xstart = 0 ystart = 0",
"' + url) return print(\"downloading %r\" % url) request = urllib.request.Request( url, data=None,",
"ZOOM_MAX = 7 LAYERTYPE = \"baselayer\" # \"baselayer\" or \"overlay\" LAYERNAME = \"OSM",
"VALUES('format', '{3}'); INSERT OR REPLACE INTO metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT,",
"cur.executescript(''' CREATE TABLE IF NOT EXISTS tiles ( zoom_level integer, tile_column integer, tile_row",
"print(\"downloading %r\" % url) request = urllib.request.Request( url, data=None, headers={ 'User-Agent': 'Low-Zoom Downloader'",
"CREATE TABLE IF NOT EXISTS tiles ( zoom_level integer, tile_column integer, tile_row integer,",
"tile_column, tile_row, tile_data) VALUES(?, ?, ?, ?)', (zoom, xtile, yinverted, content)) def main(argv):",
"metadata_name on metadata (name); CREATE UNIQUE INDEX IF NOT EXISTS tile_index on tiles(zoom_level,",
"argv import os import math import urllib.request import random import os.path import sqlite3",
"= random.randint(1, 4) url = URL_TEMPLATE % (zoom, xtile, ytile) ymax = 1",
"% (zoom, xtile, ytile) ymax = 1 << zoom yinverted = ymax -",
"BBOX is None else \",\".join(map(str, BBOX)) cur.executescript(''' CREATE TABLE IF NOT EXISTS tiles",
"source.close() cursor.execute('INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data) VALUES(?, ?, ?, ?)', (zoom, xtile,",
"print('Skipping ' + url) return print(\"downloading %r\" % url) request = urllib.request.Request( url,",
"INDEX IF NOT EXISTS tile_index on tiles(zoom_level, tile_column, tile_row); INSERT OR REPLACE INTO",
"request = urllib.request.Request( url, data=None, headers={ 'User-Agent': 'Low-Zoom Downloader' } ) source =",
"zoom) xend, ystart = deg2num(BBOX[3], BBOX[2], zoom) for x in range(xstart, xend+1): for",
"+ url) return print(\"downloading %r\" % url) request = urllib.request.Request( url, data=None, headers={",
"import argv import os import math import urllib.request import random import os.path import",
"VALUES(?, ?, ?, ?)', (zoom, xtile, yinverted, content)) def main(argv): db = argv[1]",
"OR REPLACE INTO metadata VALUES('maxzoom', '{0}'); INSERT OR REPLACE INTO metadata VALUES('name', '{1}');",
"lat_rad = math.radians(lat_deg) n = 2.0 ** zoom xtile = int((lon_deg + 180.0)",
"= \"png\" def deg2num(lat_deg, lon_deg, zoom): lat_rad = math.radians(lat_deg) n = 2.0 **",
"% url) request = urllib.request.Request( url, data=None, headers={ 'User-Agent': 'Low-Zoom Downloader' } )",
"(1 / math.cos(lat_rad))) / math.pi) / 2.0 * n) return (xtile, ytile) def",
"in range(xstart, xend+1): for y in range(ystart, yend+1): download_url(zoom, x, y, cur) conn.commit()",
"URL_TEMPLATE % (zoom, xtile, ytile) ymax = 1 << zoom yinverted = ymax",
"1 << zoom yinverted = ymax - ytile - 1 existing = cursor.execute('SELECT",
"to 6 download all for zoom in range(0, ZOOM_MAX+1): xstart = 0 ystart",
"blob); CREATE TABLE IF NOT EXISTS metadata(name text, value text); CREATE UNIQUE INDEX",
"2.0 * n) return (xtile, ytile) def download_url(zoom, xtile, ytile, cursor): subdomain =",
"= int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 *",
"is None else \",\".join(map(str, BBOX)) cur.executescript(''' CREATE TABLE IF NOT EXISTS tiles (",
"ytile) ymax = 1 << zoom yinverted = ymax - ytile - 1",
"count(*) FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?', (zoom, xtile, yinverted)).fetchall() if",
"def deg2num(lat_deg, lon_deg, zoom): lat_rad = math.radians(lat_deg) n = 2.0 ** zoom xtile",
"return (xtile, ytile) def download_url(zoom, xtile, ytile, cursor): subdomain = random.randint(1, 4) url",
"LAYERNAME = \"OSM Low Detail\" TILE_FORMAT = \"png\" def deg2num(lat_deg, lon_deg, zoom): lat_rad",
"ymax = 1 << zoom yinverted = ymax - ytile - 1 existing",
"0: print('Skipping ' + url) return print(\"downloading %r\" % url) request = urllib.request.Request(",
"tile_row integer, tile_data blob); CREATE TABLE IF NOT EXISTS metadata(name text, value text);",
"ymax - ytile - 1 existing = cursor.execute('SELECT count(*) FROM tiles WHERE zoom_level=?",
"n) ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) /",
"tiles(zoom_level, tile_column, tile_row, tile_data) VALUES(?, ?, ?, ?)', (zoom, xtile, yinverted, content)) def",
"= 7 LAYERTYPE = \"baselayer\" # \"baselayer\" or \"overlay\" LAYERNAME = \"OSM Low",
"INTO metadata VALUES('bounds', '{4}'); '''.format(ZOOM_MAX, LAYERNAME, LAYERTYPE, TILE_FORMAT, bboxStr)) # from 0 to",
"NOT EXISTS metadata(name text, value text); CREATE UNIQUE INDEX IF NOT EXISTS metadata_name",
"BBOX[2], zoom) for x in range(xstart, xend+1): for y in range(ystart, yend+1): download_url(zoom,",
"return print(\"downloading %r\" % url) request = urllib.request.Request( url, data=None, headers={ 'User-Agent': 'Low-Zoom",
"# from 0 to 6 download all for zoom in range(0, ZOOM_MAX+1): xstart",
"int((lon_deg + 180.0) / 360.0 * n) ytile = int((1.0 - math.log(math.tan(lat_rad) +",
"+ (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n) return (xtile, ytile)",
"7 LAYERTYPE = \"baselayer\" # \"baselayer\" or \"overlay\" LAYERNAME = \"OSM Low Detail\"",
"\"png\" def deg2num(lat_deg, lon_deg, zoom): lat_rad = math.radians(lat_deg) n = 2.0 ** zoom",
"UNIQUE INDEX IF NOT EXISTS metadata_name on metadata (name); CREATE UNIQUE INDEX IF",
"text); CREATE UNIQUE INDEX IF NOT EXISTS metadata_name on metadata (name); CREATE UNIQUE",
"if existing[0][0] > 0: print('Skipping ' + url) return print(\"downloading %r\" % url)",
"urllib.request.urlopen(request) content = source.read() source.close() cursor.execute('INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data) VALUES(?, ?,",
"tile_column integer, tile_row integer, tile_data blob); CREATE TABLE IF NOT EXISTS metadata(name text,",
"def main(argv): db = argv[1] if len(argv) > 1 else 'osm.mbtiles' conn =",
"?, ?, ?)', (zoom, xtile, yinverted, content)) def main(argv): db = argv[1] if",
"REPLACE INTO metadata VALUES('maxzoom', '{0}'); INSERT OR REPLACE INTO metadata VALUES('name', '{1}'); INSERT",
"'{2}'); INSERT OR REPLACE INTO metadata VALUES('format', '{3}'); INSERT OR REPLACE INTO metadata"
] |
[
"txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() eval_set.append((iid, text))",
"txt) with open(txt) as f: text=f.readline().strip() train_set.append((iid, text)) for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0]",
"pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort() for txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with",
"val_set.append((iid, text)) for txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f:",
"'p362', 'p363']: continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort() for txt in txts[:-20]:",
"all_set=[] train_set=[] val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort() for spk in spks: if spk in",
"iid, text in val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt, 'w') as f: for iid, text",
"val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt, 'w') as f: for iid, text in eval_set: f.write(f'{iid}|{text}\\n')",
"spks=os.listdir(text_dir) spks.sort() for spk in spks: if spk in ['p360', 'p361', 'p362', 'p363']:",
"txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() train_set.append((iid, text)) for txt",
"for spk in spks: if spk in ['p360', 'p361', 'p362', 'p363']: continue #import",
"open(train_txt, 'w') as f: for iid, text in train_set: f.write(f'{iid}|{text}\\n') with open(val_txt, 'w')",
"text=f.readline().strip() eval_set.append((iid, text)) with open(train_txt, 'w') as f: for iid, text in train_set:",
"train_txt='VCTK-Corpus/training.txt' val_txt='VCTK-Corpus/validation.txt' eval_txt='VCTK-Corpus/evaluation.txt' import os all_set=[] train_set=[] val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort() for spk",
"iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() val_set.append((iid, text)) for txt in",
"spk in spks: if spk in ['p360', 'p361', 'p362', 'p363']: continue #import pdb;pdb.set_trace()",
"continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort() for txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir,",
"f: text=f.readline().strip() train_set.append((iid, text)) for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt)",
"'p363']: continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort() for txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0]",
"train_set: f.write(f'{iid}|{text}\\n') with open(val_txt, 'w') as f: for iid, text in val_set: f.write(f'{iid}|{text}\\n')",
"txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() train_set.append((iid, text))",
"with open(txt) as f: text=f.readline().strip() eval_set.append((iid, text)) with open(train_txt, 'w') as f: for",
"spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort() for txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt)",
"eval_set.append((iid, text)) with open(train_txt, 'w') as f: for iid, text in train_set: f.write(f'{iid}|{text}\\n')",
"as f: for iid, text in train_set: f.write(f'{iid}|{text}\\n') with open(val_txt, 'w') as f:",
"for iid, text in val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt, 'w') as f: for iid,",
"with open(txt) as f: text=f.readline().strip() val_set.append((iid, text)) for txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir,",
"txts=os.listdir(spk_dir) txts.sort() for txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f:",
"iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() train_set.append((iid, text)) for txt in",
"text in train_set: f.write(f'{iid}|{text}\\n') with open(val_txt, 'w') as f: for iid, text in",
"open(val_txt, 'w') as f: for iid, text in val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt, 'w')",
"text)) with open(train_txt, 'w') as f: for iid, text in train_set: f.write(f'{iid}|{text}\\n') with",
"text=f.readline().strip() train_set.append((iid, text)) for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as",
"for txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() eval_set.append((iid,",
"txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() val_set.append((iid, text)) for txt in txts[-10:]:",
"f: for iid, text in val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt, 'w') as f: for",
"text)) for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip()",
"wav_dir='VCTK-Corpus/wav48/' train_txt='VCTK-Corpus/training.txt' val_txt='VCTK-Corpus/validation.txt' eval_txt='VCTK-Corpus/evaluation.txt' import os all_set=[] train_set=[] val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort() for",
"f: text=f.readline().strip() eval_set.append((iid, text)) with open(train_txt, 'w') as f: for iid, text in",
"in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() val_set.append((iid, text)) for",
"as f: text=f.readline().strip() eval_set.append((iid, text)) with open(train_txt, 'w') as f: for iid, text",
"in train_set: f.write(f'{iid}|{text}\\n') with open(val_txt, 'w') as f: for iid, text in val_set:",
"spk in ['p360', 'p361', 'p362', 'p363']: continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort()",
"in ['p360', 'p361', 'p362', 'p363']: continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort() for",
"as f: text=f.readline().strip() val_set.append((iid, text)) for txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with",
"spks.sort() for spk in spks: if spk in ['p360', 'p361', 'p362', 'p363']: continue",
"for txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() train_set.append((iid,",
"import os all_set=[] train_set=[] val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort() for spk in spks: if",
"in val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt, 'w') as f: for iid, text in eval_set:",
"text in val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt, 'w') as f: for iid, text in",
"as f: for iid, text in val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt, 'w') as f:",
"txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() train_set.append((iid, text)) for txt in txts[-20:-10]:",
"with open(train_txt, 'w') as f: for iid, text in train_set: f.write(f'{iid}|{text}\\n') with open(val_txt,",
"#import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort() for txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt)",
"f: text=f.readline().strip() val_set.append((iid, text)) for txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt)",
"'w') as f: for iid, text in val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt, 'w') as",
"eval_set=[] spks=os.listdir(text_dir) spks.sort() for spk in spks: if spk in ['p360', 'p361', 'p362',",
"os all_set=[] train_set=[] val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort() for spk in spks: if spk",
"as f: text=f.readline().strip() train_set.append((iid, text)) for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with",
"txt) with open(txt) as f: text=f.readline().strip() eval_set.append((iid, text)) with open(train_txt, 'w') as f:",
"['p360', 'p361', 'p362', 'p363']: continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort() for txt",
"for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() val_set.append((iid,",
"iid, text in train_set: f.write(f'{iid}|{text}\\n') with open(val_txt, 'w') as f: for iid, text",
"text)) for txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip()",
"in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() train_set.append((iid, text)) for",
"for iid, text in train_set: f.write(f'{iid}|{text}\\n') with open(val_txt, 'w') as f: for iid,",
"train_set.append((iid, text)) for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f:",
"open(txt) as f: text=f.readline().strip() eval_set.append((iid, text)) with open(train_txt, 'w') as f: for iid,",
"with open(val_txt, 'w') as f: for iid, text in val_set: f.write(f'{iid}|{text}\\n') with open(eval_txt,",
"if spk in ['p360', 'p361', 'p362', 'p363']: continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir)",
"open(txt) as f: text=f.readline().strip() val_set.append((iid, text)) for txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt)",
"iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() eval_set.append((iid, text)) with open(train_txt, 'w')",
"in spks: if spk in ['p360', 'p361', 'p362', 'p363']: continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir,",
"eval_txt='VCTK-Corpus/evaluation.txt' import os all_set=[] train_set=[] val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort() for spk in spks:",
"val_txt='VCTK-Corpus/validation.txt' eval_txt='VCTK-Corpus/evaluation.txt' import os all_set=[] train_set=[] val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort() for spk in",
"text_dir='VCTK-Corpus/txt/' wav_dir='VCTK-Corpus/wav48/' train_txt='VCTK-Corpus/training.txt' val_txt='VCTK-Corpus/validation.txt' eval_txt='VCTK-Corpus/evaluation.txt' import os all_set=[] train_set=[] val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort()",
"spk) txts=os.listdir(spk_dir) txts.sort() for txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as",
"txt) with open(txt) as f: text=f.readline().strip() val_set.append((iid, text)) for txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0]",
"val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort() for spk in spks: if spk in ['p360', 'p361',",
"with open(txt) as f: text=f.readline().strip() train_set.append((iid, text)) for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir,",
"in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() eval_set.append((iid, text)) with",
"open(txt) as f: text=f.readline().strip() train_set.append((iid, text)) for txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt)",
"spks: if spk in ['p360', 'p361', 'p362', 'p363']: continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk)",
"txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() eval_set.append((iid, text)) with open(train_txt, 'w') as",
"txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() eval_set.append((iid, text)) with open(train_txt,",
"train_set=[] val_set=[] eval_set=[] spks=os.listdir(text_dir) spks.sort() for spk in spks: if spk in ['p360',",
"txt in txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() val_set.append((iid, text))",
"'w') as f: for iid, text in train_set: f.write(f'{iid}|{text}\\n') with open(val_txt, 'w') as",
"txts[-20:-10]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip() val_set.append((iid, text)) for txt",
"f: for iid, text in train_set: f.write(f'{iid}|{text}\\n') with open(val_txt, 'w') as f: for",
"'p361', 'p362', 'p363']: continue #import pdb;pdb.set_trace() spk_dir=os.path.join(text_dir, spk) txts=os.listdir(spk_dir) txts.sort() for txt in",
"f.write(f'{iid}|{text}\\n') with open(val_txt, 'w') as f: for iid, text in val_set: f.write(f'{iid}|{text}\\n') with",
"text=f.readline().strip() val_set.append((iid, text)) for txt in txts[-10:]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as",
"txts.sort() for txt in txts[:-20]: iid=os.path.basename(txt).split('.')[0] txt=os.path.join(spk_dir, txt) with open(txt) as f: text=f.readline().strip()"
] |
[
"\"\"\"Retain the K most recent scores, and replace the rest with zeros\"\"\" for",
"scores def select(self, choice_scores): \"\"\"Use the top k learner's scores for usage in",
"self.choices: continue choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent K velocity selector\"\"\"",
"enough scores to do K-selection, fall back to UCB1 min_num_scores = min([len(s) for",
"compute_rewards(self, scores): \"\"\"Compute the velocity of thte k+1 most recent scores. The velocity",
"with zeros so that the count remains the same. \"\"\" # take the",
"the average distance between scores. Return a list with those k velocities padded",
"If not all choices meet this threshold, default UCB1 # selection will be",
"that each choice must have in order to use # best-K optimizations. If",
"recent scores so we can get k velocities recent_scores = scores[:-self.k - 2:-1]",
"the list out with zeros, so the length of the list is #",
"= 0. return scores def select(self, choice_scores): \"\"\"Use the top k learner's scores",
"velocities recent_scores = scores[:-self.k - 2:-1] velocities = [recent_scores[i] - recent_scores[i + 1]",
"and replace the rest with zeros\"\"\" for i in range(len(scores)): if i >=",
"UCB1 min_num_scores = min([len(s) for s in choice_scores.values()]) if min_num_scores >= K_MIN: logger.info('{klass}:",
"bandit calculation\"\"\" # if we don't have enough scores to do K-selection, fall",
"be used. K_MIN = 2 logger = logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent K reward",
">= K_MIN: logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else: logger.warning(",
"# pad the list out with zeros, so the length of the list",
"UCB1 # selection will be used. K_MIN = 2 logger = logging.getLogger('btb') class",
"K reward selector Args: k (int): number of best scores to consider \"\"\"",
"recent scores, and replace the rest with zeros\"\"\" for i in range(len(scores)): if",
"minimum number of scores that each choice must have in order to use",
"self.k = k def compute_rewards(self, scores): \"\"\"Retain the K most recent scores, and",
"the rest with zeros\"\"\" for i in range(len(scores)): if i >= self.k: scores[i]",
"padded out with zeros so that the count remains the same. \"\"\" #",
"\"\"\" def __init__(self, choices, k=K_MIN): super(RecentKReward, self).__init__(choices) self.k = k def compute_rewards(self, scores):",
"K bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else: logger.warning( '{klass}: Not enough choices to",
"have enough scores to do K-selection, fall back to UCB1 min_num_scores = min([len(s)",
"the velocity of thte k+1 most recent scores. The velocity is the average",
"UCB1 # the minimum number of scores that each choice must have in",
"scores so we can get k velocities recent_scores = scores[:-self.k - 2:-1] velocities",
"= self.compute_rewards else: logger.warning( '{klass}: Not enough choices to do K-selection; using plain",
"used. K_MIN = 2 logger = logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent K reward selector",
"don't have enough scores to do K-selection, fall back to UCB1 min_num_scores =",
"recent_scores[i + 1] for i in range(len(recent_scores) - 1)] # pad the list",
"the K most recent scores, and replace the rest with zeros\"\"\" for i",
"\"\"\"Recent K velocity selector\"\"\" def compute_rewards(self, scores): \"\"\"Compute the velocity of thte k+1",
"to do K-selection, fall back to UCB1 min_num_scores = min([len(s) for s in",
"1 most recent scores so we can get k velocities recent_scores = scores[:-self.k",
"k velocities padded out with zeros so that the count remains the same.",
"threshold, default UCB1 # selection will be used. K_MIN = 2 logger =",
"not all choices meet this threshold, default UCB1 # selection will be used.",
"0. return scores def select(self, choice_scores): \"\"\"Use the top k learner's scores for",
"self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent K velocity selector\"\"\" def compute_rewards(self, scores): \"\"\"Compute the velocity",
"so the length of the list is # maintained zeros = (len(scores) -",
"K_MIN = 2 logger = logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent K reward selector Args:",
"1] for i in range(len(recent_scores) - 1)] # pad the list out with",
"order to use # best-K optimizations. If not all choices meet this threshold,",
"in rewards for the bandit calculation\"\"\" # if we don't have enough scores",
"k=K_MIN): super(RecentKReward, self).__init__(choices) self.k = k def compute_rewards(self, scores): \"\"\"Retain the K most",
"scores, and replace the rest with zeros\"\"\" for i in range(len(scores)): if i",
"logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else: logger.warning( '{klass}: Not",
"can get k velocities recent_scores = scores[:-self.k - 2:-1] velocities = [recent_scores[i] -",
"default UCB1 # selection will be used. K_MIN = 2 logger = logging.getLogger('btb')",
"self).__init__(choices) self.k = k def compute_rewards(self, scores): \"\"\"Retain the K most recent scores,",
"def select(self, choice_scores): \"\"\"Use the top k learner's scores for usage in rewards",
"out with zeros, so the length of the list is # maintained zeros",
"logger.warning( '{klass}: Not enough choices to do K-selection; using plain UCB1' .format(klass=type(self).__name__)) reward_func",
"RecentKVelocity(RecentKReward): \"\"\"Recent K velocity selector\"\"\" def compute_rewards(self, scores): \"\"\"Compute the velocity of thte",
"import UCB1 # the minimum number of scores that each choice must have",
"else: logger.warning( '{klass}: Not enough choices to do K-selection; using plain UCB1' .format(klass=type(self).__name__))",
"number of best scores to consider \"\"\" def __init__(self, choices, k=K_MIN): super(RecentKReward, self).__init__(choices)",
"zeros, so the length of the list is # maintained zeros = (len(scores)",
"choice_scores.values()]) if min_num_scores >= K_MIN: logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__)) reward_func =",
"usage in rewards for the bandit calculation\"\"\" # if we don't have enough",
"(int): number of best scores to consider \"\"\" def __init__(self, choices, k=K_MIN): super(RecentKReward,",
"choice, scores in choice_scores.items(): if choice not in self.choices: continue choice_rewards[choice] = reward_func(scores)",
"learner's scores for usage in rewards for the bandit calculation\"\"\" # if we",
"= super(RecentKReward, self).compute_rewards choice_rewards = {} for choice, scores in choice_scores.items(): if choice",
"most recent scores, and replace the rest with zeros\"\"\" for i in range(len(scores)):",
"# take the k + 1 most recent scores so we can get",
"must have in order to use # best-K optimizations. If not all choices",
"the bandit calculation\"\"\" # if we don't have enough scores to do K-selection,",
"i in range(len(recent_scores) - 1)] # pad the list out with zeros, so",
"use # best-K optimizations. If not all choices meet this threshold, default UCB1",
"if min_num_scores >= K_MIN: logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards",
"zeros\"\"\" for i in range(len(scores)): if i >= self.k: scores[i] = 0. return",
"we can get k velocities recent_scores = scores[:-self.k - 2:-1] velocities = [recent_scores[i]",
"list with those k velocities padded out with zeros so that the count",
"if choice not in self.choices: continue choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward):",
"\"\"\"Compute the velocity of thte k+1 most recent scores. The velocity is the",
"a list with those k velocities padded out with zeros so that the",
"compute_rewards(self, scores): \"\"\"Retain the K most recent scores, and replace the rest with",
"k (int): number of best scores to consider \"\"\" def __init__(self, choices, k=K_MIN):",
"fall back to UCB1 min_num_scores = min([len(s) for s in choice_scores.values()]) if min_num_scores",
"choice_scores): \"\"\"Use the top k learner's scores for usage in rewards for the",
"scores in choice_scores.items(): if choice not in self.choices: continue choice_rewards[choice] = reward_func(scores) return",
"K-selection, fall back to UCB1 min_num_scores = min([len(s) for s in choice_scores.values()]) if",
"scores. Return a list with those k velocities padded out with zeros so",
"= [recent_scores[i] - recent_scores[i + 1] for i in range(len(recent_scores) - 1)] #",
"in choice_scores.items(): if choice not in self.choices: continue choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards)",
"logger = logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent K reward selector Args: k (int): number",
"of the list is # maintained zeros = (len(scores) - self.k) * [0]",
"super(RecentKReward, self).__init__(choices) self.k = k def compute_rewards(self, scores): \"\"\"Retain the K most recent",
"in range(len(scores)): if i >= self.k: scores[i] = 0. return scores def select(self,",
"class RecentKVelocity(RecentKReward): \"\"\"Recent K velocity selector\"\"\" def compute_rewards(self, scores): \"\"\"Compute the velocity of",
"choices to do K-selection; using plain UCB1' .format(klass=type(self).__name__)) reward_func = super(RecentKReward, self).compute_rewards choice_rewards",
"'{klass}: Not enough choices to do K-selection; using plain UCB1' .format(klass=type(self).__name__)) reward_func =",
"recent scores. The velocity is the average distance between scores. Return a list",
"that the count remains the same. \"\"\" # take the k + 1",
"btb.selection.ucb1 import UCB1 # the minimum number of scores that each choice must",
"from btb.selection.ucb1 import UCB1 # the minimum number of scores that each choice",
"def compute_rewards(self, scores): \"\"\"Retain the K most recent scores, and replace the rest",
"self.k: scores[i] = 0. return scores def select(self, choice_scores): \"\"\"Use the top k",
"for the bandit calculation\"\"\" # if we don't have enough scores to do",
"do K-selection; using plain UCB1' .format(klass=type(self).__name__)) reward_func = super(RecentKReward, self).compute_rewards choice_rewards = {}",
"number of scores that each choice must have in order to use #",
"consider \"\"\" def __init__(self, choices, k=K_MIN): super(RecentKReward, self).__init__(choices) self.k = k def compute_rewards(self,",
"meet this threshold, default UCB1 # selection will be used. K_MIN = 2",
"k def compute_rewards(self, scores): \"\"\"Retain the K most recent scores, and replace the",
"for choice, scores in choice_scores.items(): if choice not in self.choices: continue choice_rewards[choice] =",
"replace the rest with zeros\"\"\" for i in range(len(scores)): if i >= self.k:",
"def compute_rewards(self, scores): \"\"\"Compute the velocity of thte k+1 most recent scores. The",
"so we can get k velocities recent_scores = scores[:-self.k - 2:-1] velocities =",
"list is # maintained zeros = (len(scores) - self.k) * [0] return velocities",
"velocities padded out with zeros so that the count remains the same. \"\"\"",
"so that the count remains the same. \"\"\" # take the k +",
"pad the list out with zeros, so the length of the list is",
"the minimum number of scores that each choice must have in order to",
"not in self.choices: continue choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent K",
">= self.k: scores[i] = 0. return scores def select(self, choice_scores): \"\"\"Use the top",
"the top k learner's scores for usage in rewards for the bandit calculation\"\"\"",
"of best scores to consider \"\"\" def __init__(self, choices, k=K_MIN): super(RecentKReward, self).__init__(choices) self.k",
"choice not in self.choices: continue choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent",
"in self.choices: continue choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent K velocity",
"def __init__(self, choices, k=K_MIN): super(RecentKReward, self).__init__(choices) self.k = k def compute_rewards(self, scores): \"\"\"Retain",
"select(self, choice_scores): \"\"\"Use the top k learner's scores for usage in rewards for",
"scores. The velocity is the average distance between scores. Return a list with",
"- 2:-1] velocities = [recent_scores[i] - recent_scores[i + 1] for i in range(len(recent_scores)",
"for i in range(len(recent_scores) - 1)] # pad the list out with zeros,",
"selector\"\"\" def compute_rewards(self, scores): \"\"\"Compute the velocity of thte k+1 most recent scores.",
"enough choices to do K-selection; using plain UCB1' .format(klass=type(self).__name__)) reward_func = super(RecentKReward, self).compute_rewards",
"best-K optimizations. If not all choices meet this threshold, default UCB1 # selection",
"rest with zeros\"\"\" for i in range(len(scores)): if i >= self.k: scores[i] =",
"K most recent scores, and replace the rest with zeros\"\"\" for i in",
"back to UCB1 min_num_scores = min([len(s) for s in choice_scores.values()]) if min_num_scores >=",
"for i in range(len(scores)): if i >= self.k: scores[i] = 0. return scores",
"self.compute_rewards else: logger.warning( '{klass}: Not enough choices to do K-selection; using plain UCB1'",
"self).compute_rewards choice_rewards = {} for choice, scores in choice_scores.items(): if choice not in",
"velocity selector\"\"\" def compute_rewards(self, scores): \"\"\"Compute the velocity of thte k+1 most recent",
"is the average distance between scores. Return a list with those k velocities",
"all choices meet this threshold, default UCB1 # selection will be used. K_MIN",
"\"\"\"Recent K reward selector Args: k (int): number of best scores to consider",
"Return a list with those k velocities padded out with zeros so that",
"the count remains the same. \"\"\" # take the k + 1 most",
"logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent K reward selector Args: k (int): number of best",
"recent_scores = scores[:-self.k - 2:-1] velocities = [recent_scores[i] - recent_scores[i + 1] for",
"selector Args: k (int): number of best scores to consider \"\"\" def __init__(self,",
"of scores that each choice must have in order to use # best-K",
"+ 1] for i in range(len(recent_scores) - 1)] # pad the list out",
"most recent scores. The velocity is the average distance between scores. Return a",
"will be used. K_MIN = 2 logger = logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent K",
"most recent scores so we can get k velocities recent_scores = scores[:-self.k -",
"logging from btb.selection.ucb1 import UCB1 # the minimum number of scores that each",
"= reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent K velocity selector\"\"\" def compute_rewards(self, scores):",
"to consider \"\"\" def __init__(self, choices, k=K_MIN): super(RecentKReward, self).__init__(choices) self.k = k def",
"do K-selection, fall back to UCB1 min_num_scores = min([len(s) for s in choice_scores.values()])",
"= k def compute_rewards(self, scores): \"\"\"Retain the K most recent scores, and replace",
".format(klass=type(self).__name__)) reward_func = super(RecentKReward, self).compute_rewards choice_rewards = {} for choice, scores in choice_scores.items():",
"same. \"\"\" # take the k + 1 most recent scores so we",
"s in choice_scores.values()]) if min_num_scores >= K_MIN: logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__))",
"those k velocities padded out with zeros so that the count remains the",
"if we don't have enough scores to do K-selection, fall back to UCB1",
"is # maintained zeros = (len(scores) - self.k) * [0] return velocities +",
"velocity of thte k+1 most recent scores. The velocity is the average distance",
"+ 1 most recent scores so we can get k velocities recent_scores =",
"selection will be used. K_MIN = 2 logger = logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent",
"bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else: logger.warning( '{klass}: Not enough choices to do",
"have in order to use # best-K optimizations. If not all choices meet",
"k learner's scores for usage in rewards for the bandit calculation\"\"\" # if",
"scores): \"\"\"Compute the velocity of thte k+1 most recent scores. The velocity is",
"- recent_scores[i + 1] for i in range(len(recent_scores) - 1)] # pad the",
"scores that each choice must have in order to use # best-K optimizations.",
"optimizations. If not all choices meet this threshold, default UCB1 # selection will",
"with zeros\"\"\" for i in range(len(scores)): if i >= self.k: scores[i] = 0.",
"choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent K velocity selector\"\"\" def compute_rewards(self,",
"using plain UCB1' .format(klass=type(self).__name__)) reward_func = super(RecentKReward, self).compute_rewards choice_rewards = {} for choice,",
"between scores. Return a list with those k velocities padded out with zeros",
"average distance between scores. Return a list with those k velocities padded out",
"range(len(recent_scores) - 1)] # pad the list out with zeros, so the length",
"choices meet this threshold, default UCB1 # selection will be used. K_MIN =",
"\"\"\"Use the top k learner's scores for usage in rewards for the bandit",
"scores to do K-selection, fall back to UCB1 min_num_scores = min([len(s) for s",
"range(len(scores)): if i >= self.k: scores[i] = 0. return scores def select(self, choice_scores):",
"import logging from btb.selection.ucb1 import UCB1 # the minimum number of scores that",
"RecentKReward(UCB1): \"\"\"Recent K reward selector Args: k (int): number of best scores to",
"in order to use # best-K optimizations. If not all choices meet this",
"list out with zeros, so the length of the list is # maintained",
"scores to consider \"\"\" def __init__(self, choices, k=K_MIN): super(RecentKReward, self).__init__(choices) self.k = k",
"reward_func = self.compute_rewards else: logger.warning( '{klass}: Not enough choices to do K-selection; using",
"# the minimum number of scores that each choice must have in order",
"{} for choice, scores in choice_scores.items(): if choice not in self.choices: continue choice_rewards[choice]",
"selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else: logger.warning( '{klass}: Not enough choices to do K-selection;",
"scores): \"\"\"Retain the K most recent scores, and replace the rest with zeros\"\"\"",
"i in range(len(scores)): if i >= self.k: scores[i] = 0. return scores def",
"# maintained zeros = (len(scores) - self.k) * [0] return velocities + zeros",
"min_num_scores >= K_MIN: logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else:",
"the list is # maintained zeros = (len(scores) - self.k) * [0] return",
"super(RecentKReward, self).compute_rewards choice_rewards = {} for choice, scores in choice_scores.items(): if choice not",
"k+1 most recent scores. The velocity is the average distance between scores. Return",
"length of the list is # maintained zeros = (len(scores) - self.k) *",
"this threshold, default UCB1 # selection will be used. K_MIN = 2 logger",
"# if we don't have enough scores to do K-selection, fall back to",
"min_num_scores = min([len(s) for s in choice_scores.values()]) if min_num_scores >= K_MIN: logger.info('{klass}: using",
"min([len(s) for s in choice_scores.values()]) if min_num_scores >= K_MIN: logger.info('{klass}: using Best K",
"= scores[:-self.k - 2:-1] velocities = [recent_scores[i] - recent_scores[i + 1] for i",
"in choice_scores.values()]) if min_num_scores >= K_MIN: logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__)) reward_func",
"The velocity is the average distance between scores. Return a list with those",
"out with zeros so that the count remains the same. \"\"\" # take",
"with those k velocities padded out with zeros so that the count remains",
"get k velocities recent_scores = scores[:-self.k - 2:-1] velocities = [recent_scores[i] - recent_scores[i",
"the same. \"\"\" # take the k + 1 most recent scores so",
"of thte k+1 most recent scores. The velocity is the average distance between",
"for s in choice_scores.values()]) if min_num_scores >= K_MIN: logger.info('{klass}: using Best K bandit",
"i >= self.k: scores[i] = 0. return scores def select(self, choice_scores): \"\"\"Use the",
"using Best K bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else: logger.warning( '{klass}: Not enough",
"2:-1] velocities = [recent_scores[i] - recent_scores[i + 1] for i in range(len(recent_scores) -",
"scores[i] = 0. return scores def select(self, choice_scores): \"\"\"Use the top k learner's",
"Args: k (int): number of best scores to consider \"\"\" def __init__(self, choices,",
"K-selection; using plain UCB1' .format(klass=type(self).__name__)) reward_func = super(RecentKReward, self).compute_rewards choice_rewards = {} for",
"choices, k=K_MIN): super(RecentKReward, self).__init__(choices) self.k = k def compute_rewards(self, scores): \"\"\"Retain the K",
"choice_rewards = {} for choice, scores in choice_scores.items(): if choice not in self.choices:",
"k + 1 most recent scores so we can get k velocities recent_scores",
"1)] # pad the list out with zeros, so the length of the",
"K velocity selector\"\"\" def compute_rewards(self, scores): \"\"\"Compute the velocity of thte k+1 most",
"continue choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent K velocity selector\"\"\" def",
"choice must have in order to use # best-K optimizations. If not all",
"scores[:-self.k - 2:-1] velocities = [recent_scores[i] - recent_scores[i + 1] for i in",
"K_MIN: logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else: logger.warning( '{klass}:",
"= logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent K reward selector Args: k (int): number of",
"if i >= self.k: scores[i] = 0. return scores def select(self, choice_scores): \"\"\"Use",
"Best K bandit selection'.format(klass=type(self).__name__)) reward_func = self.compute_rewards else: logger.warning( '{klass}: Not enough choices",
"UCB1' .format(klass=type(self).__name__)) reward_func = super(RecentKReward, self).compute_rewards choice_rewards = {} for choice, scores in",
"reward_func(scores) return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent K velocity selector\"\"\" def compute_rewards(self, scores): \"\"\"Compute",
"k velocities recent_scores = scores[:-self.k - 2:-1] velocities = [recent_scores[i] - recent_scores[i +",
"[recent_scores[i] - recent_scores[i + 1] for i in range(len(recent_scores) - 1)] # pad",
"each choice must have in order to use # best-K optimizations. If not",
"best scores to consider \"\"\" def __init__(self, choices, k=K_MIN): super(RecentKReward, self).__init__(choices) self.k =",
"count remains the same. \"\"\" # take the k + 1 most recent",
"calculation\"\"\" # if we don't have enough scores to do K-selection, fall back",
"plain UCB1' .format(klass=type(self).__name__)) reward_func = super(RecentKReward, self).compute_rewards choice_rewards = {} for choice, scores",
"# best-K optimizations. If not all choices meet this threshold, default UCB1 #",
"for usage in rewards for the bandit calculation\"\"\" # if we don't have",
"__init__(self, choices, k=K_MIN): super(RecentKReward, self).__init__(choices) self.k = k def compute_rewards(self, scores): \"\"\"Retain the",
"top k learner's scores for usage in rewards for the bandit calculation\"\"\" #",
"return self.bandit(choice_rewards) class RecentKVelocity(RecentKReward): \"\"\"Recent K velocity selector\"\"\" def compute_rewards(self, scores): \"\"\"Compute the",
"thte k+1 most recent scores. The velocity is the average distance between scores.",
"zeros so that the count remains the same. \"\"\" # take the k",
"the k + 1 most recent scores so we can get k velocities",
"return scores def select(self, choice_scores): \"\"\"Use the top k learner's scores for usage",
"distance between scores. Return a list with those k velocities padded out with",
"\"\"\" # take the k + 1 most recent scores so we can",
"with zeros, so the length of the list is # maintained zeros =",
"to do K-selection; using plain UCB1' .format(klass=type(self).__name__)) reward_func = super(RecentKReward, self).compute_rewards choice_rewards =",
"choice_scores.items(): if choice not in self.choices: continue choice_rewards[choice] = reward_func(scores) return self.bandit(choice_rewards) class",
"# selection will be used. K_MIN = 2 logger = logging.getLogger('btb') class RecentKReward(UCB1):",
"velocities = [recent_scores[i] - recent_scores[i + 1] for i in range(len(recent_scores) - 1)]",
"in range(len(recent_scores) - 1)] # pad the list out with zeros, so the",
"Not enough choices to do K-selection; using plain UCB1' .format(klass=type(self).__name__)) reward_func = super(RecentKReward,",
"reward selector Args: k (int): number of best scores to consider \"\"\" def",
"take the k + 1 most recent scores so we can get k",
"= min([len(s) for s in choice_scores.values()]) if min_num_scores >= K_MIN: logger.info('{klass}: using Best",
"we don't have enough scores to do K-selection, fall back to UCB1 min_num_scores",
"to UCB1 min_num_scores = min([len(s) for s in choice_scores.values()]) if min_num_scores >= K_MIN:",
"2 logger = logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent K reward selector Args: k (int):",
"reward_func = super(RecentKReward, self).compute_rewards choice_rewards = {} for choice, scores in choice_scores.items(): if",
"to use # best-K optimizations. If not all choices meet this threshold, default",
"rewards for the bandit calculation\"\"\" # if we don't have enough scores to",
"remains the same. \"\"\" # take the k + 1 most recent scores",
"= {} for choice, scores in choice_scores.items(): if choice not in self.choices: continue",
"- 1)] # pad the list out with zeros, so the length of",
"scores for usage in rewards for the bandit calculation\"\"\" # if we don't",
"<filename>btb/selection/recent.py import logging from btb.selection.ucb1 import UCB1 # the minimum number of scores",
"class RecentKReward(UCB1): \"\"\"Recent K reward selector Args: k (int): number of best scores",
"velocity is the average distance between scores. Return a list with those k",
"= 2 logger = logging.getLogger('btb') class RecentKReward(UCB1): \"\"\"Recent K reward selector Args: k",
"the length of the list is # maintained zeros = (len(scores) - self.k)"
] |
[
"p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\",",
"indicator, value): p = Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self):",
"\"Q\", 1013) def test_invalid(self): with self.assertRaises(PressureDecodeError): Pressure(\"3000\") # no unit indicator; more likely",
"import Pressure from aviation_weather.exceptions import PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\" def",
"Pressure from aviation_weather.exceptions import PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self,",
"test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013) def test_invalid(self): with self.assertRaises(PressureDecodeError):",
"self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013) def test_invalid(self): with self.assertRaises(PressureDecodeError): Pressure(\"3000\")",
"import PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw, indicator, value):",
"aviation_weather.exceptions import PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw, indicator,",
"raw, indicator, value): p = Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def",
"unittest from aviation_weather import Pressure from aviation_weather.exceptions import PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit tests",
"from aviation_weather.exceptions import PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw,",
"aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw, indicator, value): p = Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator)",
"tests for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw, indicator, value): p = Pressure(raw) self.assertEqual(raw, p.raw)",
"Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def",
"\"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013) def test_invalid(self): with self.assertRaises(PressureDecodeError): Pressure(\"3000\") #",
"self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\",",
"def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013) def test_invalid(self): with self.assertRaises(PressureDecodeError): Pressure(\"3000\") # no unit",
"_test_valid(self, raw, indicator, value): p = Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value)",
"def _test_valid(self, raw, indicator, value): p = Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value,",
"import unittest from aviation_weather import Pressure from aviation_weather.exceptions import PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit",
"self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self):",
"self._test_valid(\"Q1013\", \"Q\", 1013) def test_invalid(self): with self.assertRaises(PressureDecodeError): Pressure(\"3000\") # no unit indicator; more",
"\"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw, indicator, value): p = Pressure(raw) self.assertEqual(raw,",
"test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013) def test_invalid(self): with self.assertRaises(PressureDecodeError): Pressure(\"3000\") # no unit indicator;",
"class TestPressure(unittest.TestCase): \"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw, indicator, value): p =",
"= Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92)",
"def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013) def test_invalid(self): with",
"TestPressure(unittest.TestCase): \"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw, indicator, value): p = Pressure(raw)",
"1013) def test_invalid(self): with self.assertRaises(PressureDecodeError): Pressure(\"3000\") # no unit indicator; more likely visibility",
"PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw, indicator, value): p",
"for aviation_weather.components.pressure.Pressure\"\"\" def _test_valid(self, raw, indicator, value): p = Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator,",
"aviation_weather import Pressure from aviation_weather.exceptions import PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit tests for aviation_weather.components.pressure.Pressure\"\"\"",
"p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013) def test_invalid(self):",
"p = Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\",",
"value): p = Pressure(raw) self.assertEqual(raw, p.raw) self.assertEqual(indicator, p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\",",
"p.indicator) self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013)",
"self.assertEqual(value, p.value) def test_valid_altimeter(self): self._test_valid(\"A2992\", \"A\", 29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013) def",
"from aviation_weather import Pressure from aviation_weather.exceptions import PressureDecodeError class TestPressure(unittest.TestCase): \"\"\"Unit tests for",
"29.92) def test_valid_QNH(self): self._test_valid(\"Q1013\", \"Q\", 1013) def test_invalid(self): with self.assertRaises(PressureDecodeError): Pressure(\"3000\") # no"
] |
[
"design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True)",
"self.save() RATE_CHOICES = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5,",
"image @classmethod def all_images(cls): project_images = cls.objects.all() return project_images @classmethod def search_by_title(cls, project):",
"= cls.objects.filter(title__icontains=project) return projects def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Profile(models.Model): profile_picture",
"Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) projects = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings') design =",
"(7, '7'), (8, '8'), (9, '9'), (10, '10') ] class Rating(models.Model): user =",
"models.TextField() project_link = models.CharField(max_length=60) project_owner = models.ForeignKey( User, on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=now)",
"(8, '8'), (9, '9'), (10, '10') ] class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE)",
"models.ImageField(upload_to='project/') project_description = models.TextField() project_link = models.CharField(max_length=60) project_owner = models.ForeignKey( User, on_delete=models.CASCADE, null=True)",
"ResizedImageField(size=[300, 300], quality=75, default='default.jpg', upload_to='profile_pics/') user_bio = models.TextField() user = models.OneToOneField(User, on_delete=models.CASCADE) def",
"cls.objects.get(id=id) return image @classmethod def all_images(cls): project_images = cls.objects.all() return project_images @classmethod def",
"@classmethod def all_images(cls): project_images = cls.objects.all() return project_images @classmethod def search_by_title(cls, project): projects",
"import now from django.contrib.auth.models import User from django.urls import reverse from django_resized import",
"on_delete=models.CASCADE, related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField(",
"= cls.objects.get(id=id) return image @classmethod def all_images(cls): project_images = cls.objects.all() return project_images @classmethod",
"project_owner = models.ForeignKey( User, on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=now) def __str__(self): return self.title",
"Project, on_delete=models.CASCADE, related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability =",
"return self.title def save_project(self): self.save() @classmethod def get_image_by_id(cls, id): image = cls.objects.get(id=id) return",
"def all_images(cls): project_images = cls.objects.all() return project_images @classmethod def search_by_title(cls, project): projects =",
"import models from django.utils.timezone import now from django.contrib.auth.models import User from django.urls import",
"models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' def save_profile(self): self.save() RATE_CHOICES = [",
"from django.contrib.auth.models import User from django.urls import reverse from django_resized import ResizedImageField class",
"class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) projects = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings') design",
"models.FloatField(default=0) review = models.TextField() def __str__(self): return str(self.id) @classmethod def get_ratings(cls, id): rating",
"return str(self.id) @classmethod def get_ratings(cls, id): rating = cls.objects.all()[id] # return rating return",
"import reverse from django_resized import ResizedImageField class Project(models.Model): title = models.CharField(max_length=50) project_image =",
"models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/') project_description = models.TextField() project_link = models.CharField(max_length=60) project_owner = models.ForeignKey(",
"usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating = models.FloatField(default=0) review = models.TextField() def __str__(self):",
"(2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8,",
"projects = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES,",
"'10') ] class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) projects = models.ForeignKey( Project, on_delete=models.CASCADE,",
"id): image = cls.objects.get(id=id) return image @classmethod def all_images(cls): project_images = cls.objects.all() return",
"from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User from",
"= models.ImageField(upload_to='project/') project_description = models.TextField() project_link = models.CharField(max_length=60) project_owner = models.ForeignKey( User, on_delete=models.CASCADE,",
"str(self.id) @classmethod def get_ratings(cls, id): rating = cls.objects.all()[id] # return rating return [rating]",
"user_bio = models.TextField() user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' def",
"= models.TextField() user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' def save_profile(self):",
"null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating = models.FloatField(default=0)",
"models.TextField() user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' def save_profile(self): self.save()",
"import User from django.urls import reverse from django_resized import ResizedImageField class Project(models.Model): title",
"search_by_title(cls, project): projects = cls.objects.filter(title__icontains=project) return projects def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk})",
"return f'{self.user.username} Profile' def save_profile(self): self.save() RATE_CHOICES = [ (1, '1'), (2, '2'),",
"= models.FloatField(default=0) review = models.TextField() def __str__(self): return str(self.id) @classmethod def get_ratings(cls, id):",
"models.CharField(max_length=60) project_owner = models.ForeignKey( User, on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=now) def __str__(self): return",
"cls.objects.filter(title__icontains=project) return projects def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Profile(models.Model): profile_picture =",
"= models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True)",
"django.urls import reverse from django_resized import ResizedImageField class Project(models.Model): title = models.CharField(max_length=50) project_image",
"__str__(self): return self.title def save_project(self): self.save() @classmethod def get_image_by_id(cls, id): image = cls.objects.get(id=id)",
"'3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'),",
"= ResizedImageField(size=[300, 300], quality=75, default='default.jpg', upload_to='profile_pics/') user_bio = models.TextField() user = models.OneToOneField(User, on_delete=models.CASCADE)",
"= models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' def save_profile(self): self.save() RATE_CHOICES =",
"@classmethod def search_by_title(cls, project): projects = cls.objects.filter(title__icontains=project) return projects def get_absolute_url(self): return reverse('project-detail',",
"get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Profile(models.Model): profile_picture = ResizedImageField(size=[300, 300], quality=75, default='default.jpg',",
"300], quality=75, default='default.jpg', upload_to='profile_pics/') user_bio = models.TextField() user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self):",
"__str__(self): return str(self.id) @classmethod def get_ratings(cls, id): rating = cls.objects.all()[id] # return rating",
"user = models.ForeignKey(User, on_delete=models.CASCADE) projects = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES,",
"null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating = models.FloatField(default=0) review = models.TextField() def",
"models.ForeignKey(User, on_delete=models.CASCADE) projects = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content",
"models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating = models.FloatField(default=0) review = models.TextField() def __str__(self): return str(self.id)",
"on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=now) def __str__(self): return self.title def save_project(self): self.save() @classmethod",
"def save_project(self): self.save() @classmethod def get_image_by_id(cls, id): image = cls.objects.get(id=id) return image @classmethod",
"user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' def save_profile(self): self.save() RATE_CHOICES",
"project_images @classmethod def search_by_title(cls, project): projects = cls.objects.filter(title__icontains=project) return projects def get_absolute_url(self): return",
"reverse('project-detail', kwargs={'pk': self.pk}) class Profile(models.Model): profile_picture = ResizedImageField(size=[300, 300], quality=75, default='default.jpg', upload_to='profile_pics/') user_bio",
"return project_images @classmethod def search_by_title(cls, project): projects = cls.objects.filter(title__icontains=project) return projects def get_absolute_url(self):",
"f'{self.user.username} Profile' def save_profile(self): self.save() RATE_CHOICES = [ (1, '1'), (2, '2'), (3,",
"Project(models.Model): title = models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/') project_description = models.TextField() project_link = models.CharField(max_length=60)",
"= models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating = models.FloatField(default=0) review =",
"= models.TextField() def __str__(self): return str(self.id) @classmethod def get_ratings(cls, id): rating = cls.objects.all()[id]",
"now from django.contrib.auth.models import User from django.urls import reverse from django_resized import ResizedImageField",
"self.pk}) class Profile(models.Model): profile_picture = ResizedImageField(size=[300, 300], quality=75, default='default.jpg', upload_to='profile_pics/') user_bio = models.TextField()",
"'9'), (10, '10') ] class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) projects = models.ForeignKey(",
"return projects def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Profile(models.Model): profile_picture = ResizedImageField(size=[300,",
"(9, '9'), (10, '10') ] class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) projects =",
"def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Profile(models.Model): profile_picture = ResizedImageField(size=[300, 300], quality=75,",
"null=True) average_rating = models.FloatField(default=0) review = models.TextField() def __str__(self): return str(self.id) @classmethod def",
"'5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10') ] class",
"] class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) projects = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings')",
"= models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating",
"= models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating = models.FloatField(default=0) review = models.TextField() def __str__(self): return",
"= models.TextField() project_link = models.CharField(max_length=60) project_owner = models.ForeignKey( User, on_delete=models.CASCADE, null=True) date_posted =",
"average_rating = models.FloatField(default=0) review = models.TextField() def __str__(self): return str(self.id) @classmethod def get_ratings(cls,",
"= [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6,",
"User from django.urls import reverse from django_resized import ResizedImageField class Project(models.Model): title =",
"self.title def save_project(self): self.save() @classmethod def get_image_by_id(cls, id): image = cls.objects.get(id=id) return image",
"kwargs={'pk': self.pk}) class Profile(models.Model): profile_picture = ResizedImageField(size=[300, 300], quality=75, default='default.jpg', upload_to='profile_pics/') user_bio =",
"= models.ForeignKey(User, on_delete=models.CASCADE) projects = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True)",
"User, on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=now) def __str__(self): return self.title def save_project(self): self.save()",
"image = cls.objects.get(id=id) return image @classmethod def all_images(cls): project_images = cls.objects.all() return project_images",
"quality=75, default='default.jpg', upload_to='profile_pics/') user_bio = models.TextField() user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return",
"choices=RATE_CHOICES, null=True) average_rating = models.FloatField(default=0) review = models.TextField() def __str__(self): return str(self.id) @classmethod",
"'2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'),",
"models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability",
"@classmethod def get_image_by_id(cls, id): image = cls.objects.get(id=id) return image @classmethod def all_images(cls): project_images",
"def search_by_title(cls, project): projects = cls.objects.filter(title__icontains=project) return projects def get_absolute_url(self): return reverse('project-detail', kwargs={'pk':",
"on_delete=models.CASCADE) projects = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content =",
"from django.urls import reverse from django_resized import ResizedImageField class Project(models.Model): title = models.CharField(max_length=50)",
"'6'), (7, '7'), (8, '8'), (9, '9'), (10, '10') ] class Rating(models.Model): user",
"review = models.TextField() def __str__(self): return str(self.id) @classmethod def get_ratings(cls, id): rating =",
"django_resized import ResizedImageField class Project(models.Model): title = models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/') project_description =",
"'7'), (8, '8'), (9, '9'), (10, '10') ] class Rating(models.Model): user = models.ForeignKey(User,",
"project): projects = cls.objects.filter(title__icontains=project) return projects def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class",
"projects = cls.objects.filter(title__icontains=project) return projects def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Profile(models.Model):",
"return image @classmethod def all_images(cls): project_images = cls.objects.all() return project_images @classmethod def search_by_title(cls,",
"upload_to='profile_pics/') user_bio = models.TextField() user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile'",
"ResizedImageField class Project(models.Model): title = models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/') project_description = models.TextField() project_link",
"(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7,",
"projects def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Profile(models.Model): profile_picture = ResizedImageField(size=[300, 300],",
"= models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/') project_description = models.TextField() project_link = models.CharField(max_length=60) project_owner =",
"__str__(self): return f'{self.user.username} Profile' def save_profile(self): self.save() RATE_CHOICES = [ (1, '1'), (2,",
"(5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10') ]",
"return reverse('project-detail', kwargs={'pk': self.pk}) class Profile(models.Model): profile_picture = ResizedImageField(size=[300, 300], quality=75, default='default.jpg', upload_to='profile_pics/')",
"models.DateTimeField(default=now) def __str__(self): return self.title def save_project(self): self.save() @classmethod def get_image_by_id(cls, id): image",
"get_image_by_id(cls, id): image = cls.objects.get(id=id) return image @classmethod def all_images(cls): project_images = cls.objects.all()",
"django.utils.timezone import now from django.contrib.auth.models import User from django.urls import reverse from django_resized",
"models from django.utils.timezone import now from django.contrib.auth.models import User from django.urls import reverse",
"cls.objects.all() return project_images @classmethod def search_by_title(cls, project): projects = cls.objects.filter(title__icontains=project) return projects def",
"'1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'),",
"class Profile(models.Model): profile_picture = ResizedImageField(size=[300, 300], quality=75, default='default.jpg', upload_to='profile_pics/') user_bio = models.TextField() user",
"null=True) date_posted = models.DateTimeField(default=now) def __str__(self): return self.title def save_project(self): self.save() @classmethod def",
"profile_picture = ResizedImageField(size=[300, 300], quality=75, default='default.jpg', upload_to='profile_pics/') user_bio = models.TextField() user = models.OneToOneField(User,",
"reverse from django_resized import ResizedImageField class Project(models.Model): title = models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/')",
"= models.CharField(max_length=60) project_owner = models.ForeignKey( User, on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=now) def __str__(self):",
"= models.ForeignKey( User, on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=now) def __str__(self): return self.title def",
"project_images = cls.objects.all() return project_images @classmethod def search_by_title(cls, project): projects = cls.objects.filter(title__icontains=project) return",
"project_description = models.TextField() project_link = models.CharField(max_length=60) project_owner = models.ForeignKey( User, on_delete=models.CASCADE, null=True) date_posted",
"models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating =",
"models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating = models.FloatField(default=0) review = models.TextField()",
"import ResizedImageField class Project(models.Model): title = models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/') project_description = models.TextField()",
"related_name='project_ratings') design = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES,",
"(6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10') ] class Rating(models.Model):",
"Profile(models.Model): profile_picture = ResizedImageField(size=[300, 300], quality=75, default='default.jpg', upload_to='profile_pics/') user_bio = models.TextField() user =",
"date_posted = models.DateTimeField(default=now) def __str__(self): return self.title def save_project(self): self.save() @classmethod def get_image_by_id(cls,",
"def get_image_by_id(cls, id): image = cls.objects.get(id=id) return image @classmethod def all_images(cls): project_images =",
"project_image = models.ImageField(upload_to='project/') project_description = models.TextField() project_link = models.CharField(max_length=60) project_owner = models.ForeignKey( User,",
"[ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'),",
"content = models.PositiveSmallIntegerField(choices=RATE_CHOICES, null=True) usability = models.PositiveSmallIntegerField( choices=RATE_CHOICES, null=True) average_rating = models.FloatField(default=0) review",
"project_link = models.CharField(max_length=60) project_owner = models.ForeignKey( User, on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=now) def",
"save_profile(self): self.save() RATE_CHOICES = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'),",
"self.save() @classmethod def get_image_by_id(cls, id): image = cls.objects.get(id=id) return image @classmethod def all_images(cls):",
"on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' def save_profile(self): self.save() RATE_CHOICES = [ (1,",
"<gh_stars>0 from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User",
"= models.DateTimeField(default=now) def __str__(self): return self.title def save_project(self): self.save() @classmethod def get_image_by_id(cls, id):",
"def __str__(self): return f'{self.user.username} Profile' def save_profile(self): self.save() RATE_CHOICES = [ (1, '1'),",
"def __str__(self): return self.title def save_project(self): self.save() @classmethod def get_image_by_id(cls, id): image =",
"from django_resized import ResizedImageField class Project(models.Model): title = models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/') project_description",
"django.db import models from django.utils.timezone import now from django.contrib.auth.models import User from django.urls",
"all_images(cls): project_images = cls.objects.all() return project_images @classmethod def search_by_title(cls, project): projects = cls.objects.filter(title__icontains=project)",
"django.contrib.auth.models import User from django.urls import reverse from django_resized import ResizedImageField class Project(models.Model):",
"(10, '10') ] class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) projects = models.ForeignKey( Project,",
"models.TextField() def __str__(self): return str(self.id) @classmethod def get_ratings(cls, id): rating = cls.objects.all()[id] #",
"= cls.objects.all() return project_images @classmethod def search_by_title(cls, project): projects = cls.objects.filter(title__icontains=project) return projects",
"save_project(self): self.save() @classmethod def get_image_by_id(cls, id): image = cls.objects.get(id=id) return image @classmethod def",
"(3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9,",
"def __str__(self): return str(self.id) @classmethod def get_ratings(cls, id): rating = cls.objects.all()[id] # return",
"'4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10')",
"models.ForeignKey( User, on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=now) def __str__(self): return self.title def save_project(self):",
"'8'), (9, '9'), (10, '10') ] class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) projects",
"Profile' def save_profile(self): self.save() RATE_CHOICES = [ (1, '1'), (2, '2'), (3, '3'),",
"RATE_CHOICES = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'),",
"(4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10,",
"title = models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/') project_description = models.TextField() project_link = models.CharField(max_length=60) project_owner",
"default='default.jpg', upload_to='profile_pics/') user_bio = models.TextField() user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username}",
"from django.utils.timezone import now from django.contrib.auth.models import User from django.urls import reverse from",
"class Project(models.Model): title = models.CharField(max_length=50) project_image = models.ImageField(upload_to='project/') project_description = models.TextField() project_link =",
"def save_profile(self): self.save() RATE_CHOICES = [ (1, '1'), (2, '2'), (3, '3'), (4,"
] |
[
"data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' * 40}\" ]) return",
"parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def",
"dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' *",
"in services_config: service = serv.service # ------------------------------------------------------------------------- # Service config # ------------------------------------------------------------------------- data_service.extend([",
"NOT USE YAML LIBRARY BECAUSE IT DOESN'T GUARANTEES ORDER ON KEYS # data_service",
"f\"{TAB}#{'-' * 40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' * 40}\" ]) return \"\\n\".join(data_service) __all__",
"{service.name.lower()}:{service.version}\" ]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port:",
"default=\"3.7\", help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig]) -> str:",
"# data_service = [ f\"version: {parsed.compose_version}\", f\"services:\\n\", ] for serv in services_config: service",
"in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\")",
"\" \" * 2 def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\", help=\"build a docker-compose\")",
"{service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") # ------------------------------------------------------------------------- #",
"argparse from typing import List import yaml from ..dal.services import ServiceConfig TAB =",
"= parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\")",
"data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint:",
"a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace,",
"typing import List import yaml from ..dal.services import ServiceConfig TAB = \" \"",
"{e}={e}\") # TODO: importar de catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if dep.ports:",
"argparse.Namespace, services_config: List[ServiceConfig]) -> str: # # NOT USE YAML LIBRARY BECAUSE IT",
"for serv in services_config: service = serv.service # ------------------------------------------------------------------------- # Service config #",
"f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if",
"if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\")",
"\"--compose-version\", default=\"3.7\", help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig]) ->",
"TODO: importar de catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if dep.ports: # data_service.append(f\"{TAB}{TAB}ports:",
"{dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' * 40}\" ])",
"f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\")",
"# TODO: importar de catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if dep.ports: #",
"importar de catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\")",
"f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\")",
"services_config: service = serv.service # ------------------------------------------------------------------------- # Service config # ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-'",
"{e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command:",
"IT DOESN'T GUARANTEES ORDER ON KEYS # data_service = [ f\"version: {parsed.compose_version}\", f\"services:\\n\",",
"TAB = \" \" * 2 def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\", help=\"build",
"# # NOT USE YAML LIBRARY BECAUSE IT DOESN'T GUARANTEES ORDER ON KEYS",
"service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") # ------------------------------------------------------------------------- # Dependencies #",
"* 40}\", f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if",
"data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\",",
"sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig])",
"] for serv in services_config: service = serv.service # ------------------------------------------------------------------------- # Service config",
"------------------------------------------------------------------------- # Dependencies # ------------------------------------------------------------------------- for dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\")",
"if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}-",
"data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") # TODO:",
"------------------------------------------------------------------------- # Service config # ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# Service: '{service.name}'\",",
"from typing import List import yaml from ..dal.services import ServiceConfig TAB = \"",
"data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") #",
"services_config: List[ServiceConfig]) -> str: # # NOT USE YAML LIBRARY BECAUSE IT DOESN'T",
"------------------------------------------------------------------------- for dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e in dep.environment:",
"..dal.services import ServiceConfig TAB = \" \" * 2 def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser",
"ON KEYS # data_service = [ f\"version: {parsed.compose_version}\", f\"services:\\n\", ] for serv in",
"f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' * 40}\" ]) return \"\\n\".join(data_service) __all__ = (\"cli_docker_compose\", \"build_docker_compose\")",
"= serv.service # ------------------------------------------------------------------------- # Service config # ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' * 40}\",",
"yaml from ..dal.services import ServiceConfig TAB = \" \" * 2 def cli_docker_compose(parser:",
"import argparse from typing import List import yaml from ..dal.services import ServiceConfig TAB",
"import List import yaml from ..dal.services import ServiceConfig TAB = \" \" *",
"USE YAML LIBRARY BECAUSE IT DOESN'T GUARANTEES ORDER ON KEYS # data_service =",
"= [ f\"version: {parsed.compose_version}\", f\"services:\\n\", ] for serv in services_config: service = serv.service",
"GUARANTEES ORDER ON KEYS # data_service = [ f\"version: {parsed.compose_version}\", f\"services:\\n\", ] for",
"serv in services_config: service = serv.service # ------------------------------------------------------------------------- # Service config # -------------------------------------------------------------------------",
"docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace, services_config:",
"catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([",
"ServiceConfig TAB = \" \" * 2 def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\",",
"{parsed.compose_version}\", f\"services:\\n\", ] for serv in services_config: service = serv.service # ------------------------------------------------------------------------- #",
"for e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command:",
"40}\", f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if service.environment:",
"# ------------------------------------------------------------------------- # Service config # ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# Service:",
"data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") # ------------------------------------------------------------------------- # Dependencies # -------------------------------------------------------------------------",
"BECAUSE IT DOESN'T GUARANTEES ORDER ON KEYS # data_service = [ f\"version: {parsed.compose_version}\",",
"f\"services:\\n\", ] for serv in services_config: service = serv.service # ------------------------------------------------------------------------- # Service",
"sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig]) -> str: # # NOT USE",
"40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' * 40}\" ]) return \"\\n\".join(data_service) __all__ = (\"cli_docker_compose\",",
"in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\")",
"data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' * 40}\" ]) return \"\\n\".join(data_service)",
"dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} -",
"data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\"",
"[ f\"version: {parsed.compose_version}\", f\"services:\\n\", ] for serv in services_config: service = serv.service #",
"argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose format\")",
"40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}-",
"service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if",
"in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") # TODO: importar de catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command:",
"DOESN'T GUARANTEES ORDER ON KEYS # data_service = [ f\"version: {parsed.compose_version}\", f\"services:\\n\", ]",
"if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") # ------------------------------------------------------------------------- # Dependencies",
"cli_docker_compose(parser: argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose",
"ORDER ON KEYS # data_service = [ f\"version: {parsed.compose_version}\", f\"services:\\n\", ] for serv",
"f\"version: {parsed.compose_version}\", f\"services:\\n\", ] for serv in services_config: service = serv.service # -------------------------------------------------------------------------",
"import yaml from ..dal.services import ServiceConfig TAB = \" \" * 2 def",
"# ------------------------------------------------------------------------- # Dependencies # ------------------------------------------------------------------------- for dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\")",
"YAML LIBRARY BECAUSE IT DOESN'T GUARANTEES ORDER ON KEYS # data_service = [",
"# Service config # ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-'",
"config # ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-' * 40}\",",
"service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") #",
"# data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' *",
"{dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") # TODO: importar de",
"from ..dal.services import ServiceConfig TAB = \" \" * 2 def cli_docker_compose(parser: argparse._SubParsersAction):",
"service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") # ------------------------------------------------------------------------- # Dependencies # ------------------------------------------------------------------------- for dep in",
"List[ServiceConfig]) -> str: # # NOT USE YAML LIBRARY BECAUSE IT DOESN'T GUARANTEES",
"serv.service # ------------------------------------------------------------------------- # Service config # ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}#",
"Service: '{service.name}'\", f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for",
"2 def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\",",
"List import yaml from ..dal.services import ServiceConfig TAB = \" \" * 2",
"data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' * 40}\"",
"for e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") # TODO: importar de catálogo if",
"service = serv.service # ------------------------------------------------------------------------- # Service config # ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' *",
"data_service.append(f\"{TAB}{TAB}environment:\") for e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") # TODO: importar de catálogo",
"* 40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-' * 40}\" ]) return \"\\n\".join(data_service) __all__ =",
"data_service.append(\"\") # ------------------------------------------------------------------------- # Dependencies # ------------------------------------------------------------------------- for dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image:",
"def build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig]) -> str: # # NOT USE YAML LIBRARY",
"for dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB}",
"data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") # -------------------------------------------------------------------------",
"\" * 2 def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\",",
"format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig]) -> str: # # NOT",
"data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") # ------------------------------------------------------------------------- # Dependencies # ------------------------------------------------------------------------- for dep in service.dependencies:",
"# NOT USE YAML LIBRARY BECAUSE IT DOESN'T GUARANTEES ORDER ON KEYS #",
"{service.entrypoint}\") data_service.append(\"\") # ------------------------------------------------------------------------- # Dependencies # ------------------------------------------------------------------------- for dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\")",
"service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\")",
"data_service = [ f\"version: {parsed.compose_version}\", f\"services:\\n\", ] for serv in services_config: service =",
"nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig]) -> str: # # NOT USE YAML",
"de catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\")",
"help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed:",
"- {e}={e}\") # TODO: importar de catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if",
"docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig]) -> str: # #",
"# ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\",",
"f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e in",
"{service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") # ------------------------------------------------------------------------- # Dependencies # ------------------------------------------------------------------------- for",
"sub_parser = parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\",",
"if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\") # ------------------------------------------------------------------------- # Dependencies # ------------------------------------------------------------------------- for dep",
"# ------------------------------------------------------------------------- for dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e in",
"{dep.command}\") # if dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}#",
"if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") # if dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-'",
"# if dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# END",
"------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image:",
"LIBRARY BECAUSE IT DOESN'T GUARANTEES ORDER ON KEYS # data_service = [ f\"version:",
"dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# END '{service.name}'\", f\"{TAB}#{'-'",
"f\"{TAB}#{'-' * 40}\", f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ])",
"data_service.append(f\"{TAB}{TAB}environment:\") for e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if",
"dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") # TODO: importar de catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\")",
"data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") # TODO: importar de catálogo if dep.command: data_service.append(f\"{TAB}{TAB}command: {dep.command}\") #",
"e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") # TODO: importar de catálogo if dep.command:",
"e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command:",
"str: # # NOT USE YAML LIBRARY BECAUSE IT DOESN'T GUARANTEES ORDER ON",
"]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e in service.environment: data_service.append(f\"{TAB}{TAB}{TAB}- {e}={e}\") if service.port: data_service.append(f\"{TAB}{TAB}ports:\")",
"= \" \" * 2 def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\", help=\"build a",
"-> str: # # NOT USE YAML LIBRARY BECAUSE IT DOESN'T GUARANTEES ORDER",
"import ServiceConfig TAB = \" \" * 2 def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser =",
"Service config # ------------------------------------------------------------------------- data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# Service: '{service.name}'\", f\"{TAB}#{'-' *",
"build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig]) -> str: # # NOT USE YAML LIBRARY BECAUSE",
"Dependencies # ------------------------------------------------------------------------- for dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e",
"help=\"minimum docker-compose format\") sub_parser.add_argument(\"PATH\", nargs=\"+\") def build_docker_compose(parsed: argparse.Namespace, services_config: List[ServiceConfig]) -> str: #",
"if dep.ports: # data_service.append(f\"{TAB}{TAB}ports: {dep.environment}\") data_service.append(\"\") data_service.extend([ f\"{TAB}#{'-' * 40}\", f\"{TAB}# END '{service.name}'\",",
"service.port: data_service.append(f\"{TAB}{TAB}ports:\") data_service.append(f\"{TAB}{TAB}{TAB}- {service.port}:{service.port}\") if service.command: data_service.append(f\"{TAB}{TAB}command: {service.command}\") if service.entrypoint: data_service.append(f\"{TAB}{TAB}command: {service.entrypoint}\") data_service.append(\"\")",
"KEYS # data_service = [ f\"version: {parsed.compose_version}\", f\"services:\\n\", ] for serv in services_config:",
"data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for e in dep.environment: data_service.append(f\"{TAB}{TAB}{TAB} - {e}={e}\") # TODO: importar",
"# Dependencies # ------------------------------------------------------------------------- for dep in service.dependencies: data_service.append(f\"{TAB}{dep.name}:\") data_service.append(f\"{TAB}{TAB}image: {dep.image}\") data_service.append(f\"{TAB}{TAB}environment:\") for",
"* 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e in service.environment:",
"def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\", default=\"3.7\", help=\"minimum",
"'{service.name}'\", f\"{TAB}#{'-' * 40}\", f\"{TAB}{service.name.lower()}:\", f\"{TAB}{TAB}image: {service.name.lower()}:{service.version}\" ]) if service.environment: data_service.append(f\"{TAB}{TAB}environment:\") for e",
"* 2 def cli_docker_compose(parser: argparse._SubParsersAction): sub_parser = parser.add_parser(\"docker-compose\", help=\"build a docker-compose\") sub_parser.add_argument(\"-v\", \"--compose-version\","
] |
[
"return len(list(([e for e in nums if len(str(e))%2 == 0]))) if __name__ ==",
"int: return len(list(([e for e in nums if len(str(e))%2 == 0]))) if __name__",
"len(list(([e for e in nums if len(str(e))%2 == 0]))) if __name__ == '__main__':",
"for e in nums if len(str(e))%2 == 0]))) if __name__ == '__main__': print(findNumbers([12,345,2,6,7896]))",
"def findNumbers(nums: [int]) -> int: return len(list(([e for e in nums if len(str(e))%2",
"findNumbers(nums: [int]) -> int: return len(list(([e for e in nums if len(str(e))%2 ==",
"[int]) -> int: return len(list(([e for e in nums if len(str(e))%2 == 0])))",
"<reponame>Imipenem/Competitive_Prog_with_Python<gh_stars>0 def findNumbers(nums: [int]) -> int: return len(list(([e for e in nums if",
"-> int: return len(list(([e for e in nums if len(str(e))%2 == 0]))) if"
] |
[
"(event.key == K_SPACE or event.key == K_UP): playerEvent = event # move pipes",
"+ 10 return [ {'x': pipeX, 'y': gapY - PIPEHEIGHT}, # upper pipe",
"0}) for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN",
"crash here crashTest = checkCrash(player, upperPipes, lowerPipes) if crashTest[0]: players.remove(player) if len(players) ==0:",
"or event.key == K_UP): if self.y > -2 * self.height: self.velY = self.flapAcc",
"and lower pipe rects uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'],",
"def update(self, event): if event.type == KEYDOWN and (event.key == K_SPACE or event.key",
"self.width = 20 self.height = 20 maxValue = int((SCREENHEIGHT - self.height) / SCREENHEIGHT",
"random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE)) gapY += int(BASEY * 0.2) pipeX =",
"* 0.79 BASEX = 0 try: xrange except NameError: xrange = range class",
"not just their rects\"\"\" rect = rect1.clip(rect2) if rect.width == 0 or rect.height",
"uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX,",
"+= int(BASEY * 0.2) pipeX = SCREENWIDTH + 10 return [ {'x': pipeX,",
"100) minValue = int(self.height / SCREENHEIGHT * 100) self.y = int((SCREENHEIGHT - self.height)",
"= self.flapAcc self.flapped = True def main(): global SCREEN, FPSCLOCK, myfont pygame.init() FPSCLOCK",
"= 20 maxValue = int((SCREENHEIGHT - self.height) / SCREENHEIGHT * 100) minValue =",
"'y': gapY + PIPEGAPSIZE}, # lower pipe ] def showScore(score): \"\"\"displays score in",
"uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT) #",
"downward accleration self.flapAcc = -9 # players speed on flapping self.flapped = False",
"0 try: xrange except NameError: xrange = range class Player: def __init__(self): self.x",
"= pixelCollision(playerRect, uPipeRect) lCollide = pixelCollision(playerRect, lPipeRect) if uCollide or lCollide: return [True,",
"player.height) # print score so player overlaps the score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x,",
"= 20 self.height = 20 maxValue = int((SCREENHEIGHT - self.height) / SCREENHEIGHT *",
"lCollide: return [True, False] return [False, False] def pixelCollision(rect1, rect2): \"\"\"Checks if two",
"upperPipes: pipeMidPos = pipe['x'] + PIPEWIDTH / 2 if pipeMidPos <= playerMidPos <",
"'lowerPipes': lowerPipes, } # check for score playerMidPos = player.x + player.width /",
"or event.key == K_UP): return # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in",
"score playerMidPos = player.x + player.width / 2 for pipe in upperPipes: pipeMidPos",
"generated pipe\"\"\" # y of gap between upper and lower pipe gapY =",
"0 def update(self, event): if event.type == KEYDOWN and (event.key == K_SPACE or",
"{'x': pipeX, 'y': gapY - PIPEHEIGHT}, # upper pipe {'x': pipeX, 'y': gapY",
"rect = rect1.clip(rect2) if rect.width == 0 or rect.height == 0: return False",
"SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT))",
"collided with upipe or lpipe uCollide = pixelCollision(playerRect, uPipeRect) lCollide = pixelCollision(playerRect, lPipeRect)",
"newPipe1 = getRandomPipe() # newPipe2 = getRandomPipe() # list of upper pipes upperPipes",
"512 SCREENHEIGHT = 512 # amount by which base can maximum shift to",
"minValue = int(self.height / SCREENHEIGHT * 100) self.y = int((SCREENHEIGHT - self.height) *",
"# newPipe2 = getRandomPipe() # list of upper pipes upperPipes = [ newPipe1[0],",
"lpipe uCollide = pixelCollision(playerRect, uPipeRect) lCollide = pixelCollision(playerRect, lPipeRect) if uCollide or lCollide:",
"pipes to left for uPipe, lPipe in zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX lPipe['x']",
"= pixelCollision(playerRect, lPipeRect) if uCollide or lCollide: return [True, False] return [False, False]",
"new pipes to add to upperPipes lowerPipes list newPipe1 = getRandomPipe() # newPipe2",
"# draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,",
"pygame.display.update() def getRandomPipe(): \"\"\"returns a randomly generated pipe\"\"\" # y of gap between",
"# player velocity, max velocity, downward accleration, accleration on flap self.velY = -9",
"lPipe['y'], PIPEWIDTH, PIPEHEIGHT) # if bird collided with upipe or lpipe uCollide =",
"speed on flapping self.flapped = False # True when player flaps self.score =",
"player.width / 2 for pipe in upperPipes: pipeMidPos = pipe['x'] + PIPEWIDTH /",
"player's movement if player.velY < player.maxVelY and not player.flapped: player.velY += player.accY if",
"xrange = range class Player: def __init__(self): self.x = int(SCREENWIDTH * 0.2) self.width",
"players.remove(player) if len(players) ==0: return { 'player': player, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes, }",
"0) FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe(): \"\"\"returns a randomly generated pipe\"\"\" # y of",
"= SCREENWIDTH + 10 return [ {'x': pipeX, 'y': gapY - PIPEHEIGHT}, #",
"# move pipes to left for uPipe, lPipe in zip(upperPipes, lowerPipes): uPipe['x'] +=",
"= -9 # player's velocity along Y, default same as playerFlapped self.maxVelY =",
"player.flapped = False player.y += min(player.velY, BASEY - player.y - player.height) # print",
"rect1.clip(rect2) if rect.width == 0 or rect.height == 0: return False return True",
"newPipe2[0], ] # list of lowerpipe lowerPipes = [ newPipe1[1], # newPipe2[1], ]",
"= int((SCREENHEIGHT - self.height) * random.randint(minValue, maxValue) / 100 ) # player velocity,",
"min(player.velY, BASEY - player.y - player.height) # print score so player overlaps the",
"* FPS = 30 SCREENWIDTH = 512 SCREENHEIGHT = 512 # amount by",
"lowerPipes.append(newPipe[1]) # remove first pipe if its out of the screen if upperPipes[0]['x']",
"remove first pipe if its out of the screen if upperPipes[0]['x'] < -PIPEWIDTH:",
"lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes'] while True: for event in pygame.event.get(): if event.type ==",
"pipe rects uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH,",
"if player.flapped: player.flapped = False player.y += min(player.velY, BASEY - player.y - player.height)",
"gap between upper and lower part of pipe PIPEHEIGHT = 300 PIPEWIDTH =",
"if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): playerEvent",
"pipe ] def showScore(score): \"\"\"displays score in center of screen\"\"\" label = myfont.render(str(score),",
"screen if upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) # draw sprites SCREEN.fill((0,0,0)) for uPipe,",
"event.key == K_UP): return # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes,",
"accleration, accleration on flap self.velY = -9 # player's velocity along Y, default",
"int(BASEY * 0.2) pipeX = SCREENWIDTH + 10 return [ {'x': pipeX, 'y':",
"300 PIPEWIDTH = 50 BASEY = SCREENHEIGHT * 0.79 BASEX = 0 try:",
"and (event.key == K_SPACE or event.key == K_UP): if self.y > -2 *",
"and lower pipe gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE)) gapY +=",
"pipe {'x': pipeX, 'y': gapY + PIPEGAPSIZE}, # lower pipe ] def showScore(score):",
"not player.flapped: player.velY += player.accY if player.flapped: player.flapped = False player.y += min(player.velY,",
"K_SPACE or event.key == K_UP): if self.y > -2 * self.height: self.velY =",
"= pygame.font.SysFont(\"Comic Sans MS\", 30) while True: crashInfo = mainGame() showGameOverScreen(crashInfo) def mainGame():",
"# draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT))",
"as playerFlapped self.maxVelY = 10 # max vel along Y, max descend speed",
"gapY + PIPEGAPSIZE}, # lower pipe ] def showScore(score): \"\"\"displays score in center",
"[False, False] def pixelCollision(rect1, rect2): \"\"\"Checks if two objects collide and not just",
"lowerPipes): uPipe['x'] += pipeVelX lPipe['x'] += pipeVelX # add new pipe when first",
"import pygame from pygame.locals import * FPS = 30 SCREENWIDTH = 512 SCREENHEIGHT",
"pygame.locals import * FPS = 30 SCREENWIDTH = 512 SCREENHEIGHT = 512 #",
"showGameOverScreen(crashInfo): \"\"\"crashes the player down ans shows gameover image\"\"\" player = crashInfo['player'] upperPipes,",
"\"\"\"crashes the player down ans shows gameover image\"\"\" player = crashInfo['player'] upperPipes, lowerPipes",
"* self.height: self.velY = self.flapAcc self.flapped = True def main(): global SCREEN, FPSCLOCK,",
"< pipeMidPos + 4: player.score += 1 # player's movement if player.velY <",
"player.accY if player.flapped: player.flapped = False player.y += min(player.velY, BASEY - player.y -",
"in zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX lPipe['x'] += pipeVelX # add new pipe",
"of screen if 0 < upperPipes[0]['x'] < 5: newPipe = getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1])",
"else: playerRect = pygame.Rect(player.x, player.y, player.width, player.height) for uPipe, lPipe in zip(upperPipes, lowerPipes):",
"lPipe in zip(upperPipes, lowerPipes): # upper and lower pipe rects uPipeRect = pygame.Rect(uPipe['x'],",
"player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe(): \"\"\"returns a randomly generated pipe\"\"\" # y",
"+= pipeVelX # add new pipe when first pipe is about to touch",
"event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): playerEvent =",
"5: newPipe = getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove first pipe if its out",
"= int(self.height / SCREENHEIGHT * 100) self.y = int((SCREENHEIGHT - self.height) * random.randint(minValue,",
"(uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for player in players: player.update(playerEvent)",
"playerMidPos < pipeMidPos + 4: player.score += 1 # player's movement if player.velY",
"sys import pygame from pygame.locals import * FPS = 30 SCREENWIDTH = 512",
"< upperPipes[0]['x'] < 5: newPipe = getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove first pipe",
"1 # player's movement if player.velY < player.maxVelY and not player.flapped: player.velY +=",
"draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255),",
"lCollide = pixelCollision(playerRect, lPipeRect) if uCollide or lCollide: return [True, False] return [False,",
"between upper and lower pipe gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE))",
"from pygame.locals import * FPS = 30 SCREENWIDTH = 512 SCREENHEIGHT = 512",
"to upperPipes lowerPipes list newPipe1 = getRandomPipe() # newPipe2 = getRandomPipe() # list",
"PIPEWIDTH, PIPEHEIGHT) # if bird collided with upipe or lpipe uCollide = pixelCollision(playerRect,",
"player.flapped: player.velY += player.accY if player.flapped: player.flapped = False player.y += min(player.velY, BASEY",
"sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'],",
") # player velocity, max velocity, downward accleration, accleration on flap self.velY =",
"= event # move pipes to left for uPipe, lPipe in zip(upperPipes, lowerPipes):",
"\"\"\"Checks if two objects collide and not just their rects\"\"\" rect = rect1.clip(rect2)",
"BASEX = 0 try: xrange except NameError: xrange = range class Player: def",
"is about to touch left of screen if 0 < upperPipes[0]['x'] < 5:",
"if rect.width == 0 or rect.height == 0: return False return True if",
"== 0 or rect.height == 0: return False return True if __name__ ==",
"mainGame(): players = [] for i in range(0,1): players.append(Player()) # get 2 new",
"draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT))",
"self.y > -2 * self.height: self.velY = self.flapAcc self.flapped = True def main():",
"to add to upperPipes lowerPipes list newPipe1 = getRandomPipe() # newPipe2 = getRandomPipe()",
"[ {'x': pipeX, 'y': gapY - PIPEHEIGHT}, # upper pipe {'x': pipeX, 'y':",
"# amount by which base can maximum shift to left PIPEGAPSIZE = 100",
"along Y, default same as playerFlapped self.maxVelY = 10 # max vel along",
"image\"\"\" player = crashInfo['player'] upperPipes, lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes'] while True: for event",
"FPSCLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont = pygame.font.SysFont(\"Comic Sans",
"(uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200),",
"player.update(playerEvent) # check for crash here crashTest = checkCrash(player, upperPipes, lowerPipes) if crashTest[0]:",
"[] for i in range(0,1): players.append(Player()) # get 2 new pipes to add",
"lower pipe gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE)) gapY += int(BASEY",
"touch left of screen if 0 < upperPipes[0]['x'] < 5: newPipe = getRandomPipe()",
"- PIPEGAPSIZE)) gapY += int(BASEY * 0.2) pipeX = SCREENWIDTH + 10 return",
"lower part of pipe PIPEHEIGHT = 300 PIPEWIDTH = 50 BASEY = SCREENHEIGHT",
"+= pipeVelX lPipe['x'] += pipeVelX # add new pipe when first pipe is",
"player in players: player.update(playerEvent) # check for crash here crashTest = checkCrash(player, upperPipes,",
"if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): if",
"# check for crash here crashTest = checkCrash(player, upperPipes, lowerPipes) if crashTest[0]: players.remove(player)",
"'type': 0, 'key': 0}) for event in pygame.event.get(): if event.type == QUIT or",
"- self.height) * random.randint(minValue, maxValue) / 100 ) # player velocity, max velocity,",
"+ 4: player.score += 1 # player's movement if player.velY < player.maxVelY and",
"- player.y - player.height) # print score so player overlaps the score showScore(player.score)",
"center of screen\"\"\" label = myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label, (10, 10)) def checkCrash(player,",
"= pygame.Rect(player.x, player.y, player.width, player.height) for uPipe, lPipe in zip(upperPipes, lowerPipes): # upper",
"label = myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label, (10, 10)) def checkCrash(player, upperPipes, lowerPipes): \"\"\"returns",
"range(0,1): players.append(Player()) # get 2 new pipes to add to upperPipes lowerPipes list",
"upper and lower pipe gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE)) gapY",
"0.2) pipeX = SCREENWIDTH + 10 return [ {'x': pipeX, 'y': gapY -",
"global SCREEN, FPSCLOCK, myfont pygame.init() FPSCLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy",
"pixelCollision(playerRect, uPipeRect) lCollide = pixelCollision(playerRect, lPipeRect) if uCollide or lCollide: return [True, False]",
"get 2 new pipes to add to upperPipes lowerPipes list newPipe1 = getRandomPipe()",
"if player crashes into ground if player.y + player.height >= BASEY - 1:",
"\"\"\"displays score in center of screen\"\"\" label = myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label, (10,",
"list newPipe1 = getRandomPipe() # newPipe2 = getRandomPipe() # list of upper pipes",
"# get 2 new pipes to add to upperPipes lowerPipes list newPipe1 =",
"MS\", 30) while True: crashInfo = mainGame() showGameOverScreen(crashInfo) def mainGame(): players = []",
"/ SCREENHEIGHT * 100) self.y = int((SCREENHEIGHT - self.height) * random.randint(minValue, maxValue) /",
"lowerPipes.pop(0) # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'],",
"random import sys import pygame from pygame.locals import * FPS = 30 SCREENWIDTH",
"+= min(player.velY, BASEY - player.y - player.height) # print score so player overlaps",
"self.height) / SCREENHEIGHT * 100) minValue = int(self.height / SCREENHEIGHT * 100) self.y",
"pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont = pygame.font.SysFont(\"Comic Sans MS\", 30)",
"(10, 10)) def checkCrash(player, upperPipes, lowerPipes): \"\"\"returns True if player collders with base",
"collide and not just their rects\"\"\" rect = rect1.clip(rect2) if rect.width == 0",
"0.6 - PIPEGAPSIZE)) gapY += int(BASEY * 0.2) pipeX = SCREENWIDTH + 10",
"] pipeVelX = -4 while True: playerEvent = type('', (object,),{ 'type': 0, 'key':",
"if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit()",
"itertools import cycle import random import sys import pygame from pygame.locals import *",
"SCREEN, FPSCLOCK, myfont pygame.init() FPSCLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird')",
"= pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont = pygame.font.SysFont(\"Comic Sans MS\", 30) while True:",
"= getRandomPipe() # list of upper pipes upperPipes = [ newPipe1[0], # newPipe2[0],",
"BASEY = SCREENHEIGHT * 0.79 BASEX = 0 try: xrange except NameError: xrange",
"player.width, player.height) for uPipe, lPipe in zip(upperPipes, lowerPipes): # upper and lower pipe",
"== K_UP): playerEvent = event # move pipes to left for uPipe, lPipe",
"and (event.key == K_SPACE or event.key == K_UP): return # draw sprites SCREEN.fill((0,0,0))",
"== QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if",
"KEYDOWN and (event.key == K_SPACE or event.key == K_UP): return # draw sprites",
"gapY - PIPEHEIGHT}, # upper pipe {'x': pipeX, 'y': gapY + PIPEGAPSIZE}, #",
"getRandomPipe() # list of upper pipes upperPipes = [ newPipe1[0], # newPipe2[0], ]",
"when first pipe is about to touch left of screen if 0 <",
"add to upperPipes lowerPipes list newPipe1 = getRandomPipe() # newPipe2 = getRandomPipe() #",
"player.flapped: player.flapped = False player.y += min(player.velY, BASEY - player.y - player.height) #",
"and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key ==",
"'player': player, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes, } # check for score playerMidPos =",
"add new pipe when first pipe is about to touch left of screen",
"PIPEWIDTH, PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT) # if bird collided with",
"lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0)",
"myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label, (10, 10)) def checkCrash(player, upperPipes, lowerPipes): \"\"\"returns True if",
"self.maxVelY = 10 # max vel along Y, max descend speed self.accY =",
"sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255),",
"PIPEHEIGHT = 300 PIPEWIDTH = 50 BASEY = SCREENHEIGHT * 0.79 BASEX =",
"SCREENHEIGHT * 100) minValue = int(self.height / SCREENHEIGHT * 100) self.y = int((SCREENHEIGHT",
"speed self.accY = 1 # players downward accleration self.flapAcc = -9 # players",
"for i in range(0,1): players.append(Player()) # get 2 new pipes to add to",
"check for crash here crashTest = checkCrash(player, upperPipes, lowerPipes) if crashTest[0]: players.remove(player) if",
"= crashInfo['upperPipes'], crashInfo['lowerPipes'] while True: for event in pygame.event.get(): if event.type == QUIT",
"/ 100 ) # player velocity, max velocity, downward accleration, accleration on flap",
"ans shows gameover image\"\"\" player = crashInfo['player'] upperPipes, lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes'] while",
"pygame.font.SysFont(\"Comic Sans MS\", 30) while True: crashInfo = mainGame() showGameOverScreen(crashInfo) def mainGame(): players",
"(BASEX, BASEY,SCREENWIDTH,BASEY)) for player in players: player.update(playerEvent) # check for crash here crashTest",
"between upper and lower part of pipe PIPEHEIGHT = 300 PIPEWIDTH = 50",
"# gap between upper and lower part of pipe PIPEHEIGHT = 300 PIPEWIDTH",
"+ PIPEGAPSIZE}, # lower pipe ] def showScore(score): \"\"\"displays score in center of",
"flap self.velY = -9 # player's velocity along Y, default same as playerFlapped",
"playerEvent = event # move pipes to left for uPipe, lPipe in zip(upperPipes,",
"(object,),{ 'type': 0, 'key': 0}) for event in pygame.event.get(): if event.type == QUIT",
"pipe PIPEHEIGHT = 300 PIPEWIDTH = 50 BASEY = SCREENHEIGHT * 0.79 BASEX",
"descend speed self.accY = 1 # players downward accleration self.flapAcc = -9 #",
"out of the screen if upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) # draw sprites",
"[True, False] return [False, False] def pixelCollision(rect1, rect2): \"\"\"Checks if two objects collide",
"= SCREENHEIGHT * 0.79 BASEX = 0 try: xrange except NameError: xrange =",
"lPipe['x'] += pipeVelX # add new pipe when first pipe is about to",
"rect2): \"\"\"Checks if two objects collide and not just their rects\"\"\" rect =",
"if two objects collide and not just their rects\"\"\" rect = rect1.clip(rect2) if",
"len(players) ==0: return { 'player': player, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes, } # check",
"SCREEN.blit(label, (10, 10)) def checkCrash(player, upperPipes, lowerPipes): \"\"\"returns True if player collders with",
"or event.key == K_UP): playerEvent = event # move pipes to left for",
"= [ newPipe1[0], # newPipe2[0], ] # list of lowerpipe lowerPipes = [",
"PIPEGAPSIZE = 100 # gap between upper and lower part of pipe PIPEHEIGHT",
"if pipeMidPos <= playerMidPos < pipeMidPos + 4: player.score += 1 # player's",
"newPipe2 = getRandomPipe() # list of upper pipes upperPipes = [ newPipe1[0], #",
"True: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN",
"512 # amount by which base can maximum shift to left PIPEGAPSIZE =",
"a randomly generated pipe\"\"\" # y of gap between upper and lower pipe",
"upper pipe {'x': pipeX, 'y': gapY + PIPEGAPSIZE}, # lower pipe ] def",
"pygame.Rect(player.x, player.y, player.width, player.height) for uPipe, lPipe in zip(upperPipes, lowerPipes): # upper and",
"xrange except NameError: xrange = range class Player: def __init__(self): self.x = int(SCREENWIDTH",
"lowerPipes, } # check for score playerMidPos = player.x + player.width / 2",
"uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x,",
"with upipe or lpipe uCollide = pixelCollision(playerRect, uPipeRect) lCollide = pixelCollision(playerRect, lPipeRect) if",
"pipeX, 'y': gapY + PIPEGAPSIZE}, # lower pipe ] def showScore(score): \"\"\"displays score",
"for pipe in upperPipes: pipeMidPos = pipe['x'] + PIPEWIDTH / 2 if pipeMidPos",
"zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY))",
"(BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update() def",
"(lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for player in players: player.update(playerEvent) # check for",
"import random import sys import pygame from pygame.locals import * FPS = 30",
"= int((SCREENHEIGHT - self.height) / SCREENHEIGHT * 100) minValue = int(self.height / SCREENHEIGHT",
"SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont = pygame.font.SysFont(\"Comic Sans MS\", 30) while True: crashInfo =",
"pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for player in players: player.update(playerEvent) # check",
"/ 2 for pipe in upperPipes: pipeMidPos = pipe['x'] + PIPEWIDTH / 2",
"PIPEHEIGHT}, # upper pipe {'x': pipeX, 'y': gapY + PIPEGAPSIZE}, # lower pipe",
"by which base can maximum shift to left PIPEGAPSIZE = 100 # gap",
"= int(SCREENWIDTH * 0.2) self.width = 20 self.height = 20 maxValue = int((SCREENHEIGHT",
"True if player collders with base or pipes.\"\"\" # if player crashes into",
"# player's movement if player.velY < player.maxVelY and not player.flapped: player.velY += player.accY",
"in range(0,1): players.append(Player()) # get 2 new pipes to add to upperPipes lowerPipes",
"pipe gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE)) gapY += int(BASEY *",
"def checkCrash(player, upperPipes, lowerPipes): \"\"\"returns True if player collders with base or pipes.\"\"\"",
"crashInfo['upperPipes'], crashInfo['lowerPipes'] while True: for event in pygame.event.get(): if event.type == QUIT or",
"main(): global SCREEN, FPSCLOCK, myfont pygame.init() FPSCLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))",
"crashTest[0]: players.remove(player) if len(players) ==0: return { 'player': player, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes,",
"lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY))",
"player.score += 1 # player's movement if player.velY < player.maxVelY and not player.flapped:",
"SCREENWIDTH + 10 return [ {'x': pipeX, 'y': gapY - PIPEHEIGHT}, # upper",
"y of gap between upper and lower pipe gapY = random.randrange(0, int(BASEY *",
"< player.maxVelY and not player.flapped: player.velY += player.accY if player.flapped: player.flapped = False",
"for uPipe, lPipe in zip(upperPipes, lowerPipes): # upper and lower pipe rects uPipeRect",
"(player.x, player.y, player.width, player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe(): \"\"\"returns a randomly generated",
"zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for player",
"False # True when player flaps self.score = 0 def update(self, event): if",
"= getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove first pipe if its out of the",
"showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe(): \"\"\"returns",
"int(BASEY * 0.6 - PIPEGAPSIZE)) gapY += int(BASEY * 0.2) pipeX = SCREENWIDTH",
"if 0 < upperPipes[0]['x'] < 5: newPipe = getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove",
"player, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes, } # check for score playerMidPos = player.x",
"def main(): global SCREEN, FPSCLOCK, myfont pygame.init() FPSCLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH,",
"(255,255,255)) SCREEN.blit(label, (10, 10)) def checkCrash(player, upperPipes, lowerPipes): \"\"\"returns True if player collders",
"if uCollide or lCollide: return [True, False] return [False, False] def pixelCollision(rect1, rect2):",
"1: return [True, True] else: playerRect = pygame.Rect(player.x, player.y, player.width, player.height) for uPipe,",
"Y, max descend speed self.accY = 1 # players downward accleration self.flapAcc =",
"if player.velY < player.maxVelY and not player.flapped: player.velY += player.accY if player.flapped: player.flapped",
"BASEY - player.y - player.height) # print score so player overlaps the score",
"= 30 SCREENWIDTH = 512 SCREENHEIGHT = 512 # amount by which base",
"while True: crashInfo = mainGame() showGameOverScreen(crashInfo) def mainGame(): players = [] for i",
"upperPipes[0]['x'] < 5: newPipe = getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove first pipe if",
"* 0.2) self.width = 20 self.height = 20 maxValue = int((SCREENHEIGHT - self.height)",
"in players: player.update(playerEvent) # check for crash here crashTest = checkCrash(player, upperPipes, lowerPipes)",
"playerMidPos = player.x + player.width / 2 for pipe in upperPipes: pipeMidPos =",
"PIPEGAPSIZE)) gapY += int(BASEY * 0.2) pipeX = SCREENWIDTH + 10 return [",
"list of upper pipes upperPipes = [ newPipe1[0], # newPipe2[0], ] # list",
"pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes the player down ans shows gameover image\"\"\" player",
"* 100) minValue = int(self.height / SCREENHEIGHT * 100) self.y = int((SCREENHEIGHT -",
"PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) FPSCLOCK.tick(FPS)",
"# max vel along Y, max descend speed self.accY = 1 # players",
"event.key == K_UP): playerEvent = event # move pipes to left for uPipe,",
"* random.randint(minValue, maxValue) / 100 ) # player velocity, max velocity, downward accleration,",
"== K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE or",
"two objects collide and not just their rects\"\"\" rect = rect1.clip(rect2) if rect.width",
"player.velY += player.accY if player.flapped: player.flapped = False player.y += min(player.velY, BASEY -",
"= 100 # gap between upper and lower part of pipe PIPEHEIGHT =",
"players.append(Player()) # get 2 new pipes to add to upperPipes lowerPipes list newPipe1",
"BASEY - 1: return [True, True] else: playerRect = pygame.Rect(player.x, player.y, player.width, player.height)",
"down ans shows gameover image\"\"\" player = crashInfo['player'] upperPipes, lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes']",
"players speed on flapping self.flapped = False # True when player flaps self.score",
"pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT) # if bird",
"/ SCREENHEIGHT * 100) minValue = int(self.height / SCREENHEIGHT * 100) self.y =",
"* 0.6 - PIPEGAPSIZE)) gapY += int(BASEY * 0.2) pipeX = SCREENWIDTH +",
"= pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont = pygame.font.SysFont(\"Comic Sans MS\",",
"crashInfo['lowerPipes'] while True: for event in pygame.event.get(): if event.type == QUIT or (event.type",
"player.y, player.width, player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe(): \"\"\"returns a randomly generated pipe\"\"\"",
"# newPipe2[0], ] # list of lowerpipe lowerPipes = [ newPipe1[1], # newPipe2[1],",
"= 1 # players downward accleration self.flapAcc = -9 # players speed on",
"if player collders with base or pipes.\"\"\" # if player crashes into ground",
"if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): return",
"part of pipe PIPEHEIGHT = 300 PIPEWIDTH = 50 BASEY = SCREENHEIGHT *",
"return [True, True] else: playerRect = pygame.Rect(player.x, player.y, player.width, player.height) for uPipe, lPipe",
"move pipes to left for uPipe, lPipe in zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX",
"lowerPipes list newPipe1 = getRandomPipe() # newPipe2 = getRandomPipe() # list of upper",
"PIPEHEIGHT) # if bird collided with upipe or lpipe uCollide = pixelCollision(playerRect, uPipeRect)",
"uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for player in players: player.update(playerEvent) #",
"__init__(self): self.x = int(SCREENWIDTH * 0.2) self.width = 20 self.height = 20 maxValue",
"pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update()",
"pipe when first pipe is about to touch left of screen if 0",
"PIPEGAPSIZE}, # lower pipe ] def showScore(score): \"\"\"displays score in center of screen\"\"\"",
"self.y = int((SCREENHEIGHT - self.height) * random.randint(minValue, maxValue) / 100 ) # player",
"range class Player: def __init__(self): self.x = int(SCREENWIDTH * 0.2) self.width = 20",
"pipeX = SCREENWIDTH + 10 return [ {'x': pipeX, 'y': gapY - PIPEHEIGHT},",
"0) pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes the player down ans shows gameover image\"\"\"",
"randomly generated pipe\"\"\" # y of gap between upper and lower pipe gapY",
"if upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe",
"pipeMidPos + 4: player.score += 1 # player's movement if player.velY < player.maxVelY",
"player.y, player.width, player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes the player down ans",
"for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and",
"int(self.height / SCREENHEIGHT * 100) self.y = int((SCREENHEIGHT - self.height) * random.randint(minValue, maxValue)",
"upper pipes upperPipes = [ newPipe1[0], # newPipe2[0], ] # list of lowerpipe",
"= range class Player: def __init__(self): self.x = int(SCREENWIDTH * 0.2) self.width =",
"+= 1 # player's movement if player.velY < player.maxVelY and not player.flapped: player.velY",
"pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):",
"# True when player flaps self.score = 0 def update(self, event): if event.type",
"return [False, False] def pixelCollision(rect1, rect2): \"\"\"Checks if two objects collide and not",
"accleration self.flapAcc = -9 # players speed on flapping self.flapped = False #",
"= True def main(): global SCREEN, FPSCLOCK, myfont pygame.init() FPSCLOCK = pygame.time.Clock() SCREEN",
"shift to left PIPEGAPSIZE = 100 # gap between upper and lower part",
"[True, True] else: playerRect = pygame.Rect(player.x, player.y, player.width, player.height) for uPipe, lPipe in",
"pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width,",
"gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE)) gapY += int(BASEY * 0.2)",
"or rect.height == 0: return False return True if __name__ == '__main__': main()",
"rects\"\"\" rect = rect1.clip(rect2) if rect.width == 0 or rect.height == 0: return",
"lowerPipes): # upper and lower pipe rects uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT)",
"(event.key == K_SPACE or event.key == K_UP): return # draw sprites SCREEN.fill((0,0,0)) for",
"player velocity, max velocity, downward accleration, accleration on flap self.velY = -9 #",
"pipe is about to touch left of screen if 0 < upperPipes[0]['x'] <",
"maxValue = int((SCREENHEIGHT - self.height) / SCREENHEIGHT * 100) minValue = int(self.height /",
"] # list of lowerpipe lowerPipes = [ newPipe1[1], # newPipe2[1], ] pipeVelX",
"0.79 BASEX = 0 try: xrange except NameError: xrange = range class Player:",
"its out of the screen if upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) # draw",
"True: crashInfo = mainGame() showGameOverScreen(crashInfo) def mainGame(): players = [] for i in",
"uPipe, lPipe in zip(upperPipes, lowerPipes): # upper and lower pipe rects uPipeRect =",
"in zip(upperPipes, lowerPipes): # upper and lower pipe rects uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'],",
"self.height: self.velY = self.flapAcc self.flapped = True def main(): global SCREEN, FPSCLOCK, myfont",
"K_UP): playerEvent = event # move pipes to left for uPipe, lPipe in",
"crashTest = checkCrash(player, upperPipes, lowerPipes) if crashTest[0]: players.remove(player) if len(players) ==0: return {",
"gap between upper and lower pipe gapY = random.randrange(0, int(BASEY * 0.6 -",
"lowerPipes): \"\"\"returns True if player collders with base or pipes.\"\"\" # if player",
"'y': gapY - PIPEHEIGHT}, # upper pipe {'x': pipeX, 'y': gapY + PIPEGAPSIZE},",
"base or pipes.\"\"\" # if player crashes into ground if player.y + player.height",
"for player in players: player.update(playerEvent) # check for crash here crashTest = checkCrash(player,",
"cycle import random import sys import pygame from pygame.locals import * FPS =",
"and lower part of pipe PIPEHEIGHT = 300 PIPEWIDTH = 50 BASEY =",
"2 new pipes to add to upperPipes lowerPipes list newPipe1 = getRandomPipe() #",
"uCollide = pixelCollision(playerRect, uPipeRect) lCollide = pixelCollision(playerRect, lPipeRect) if uCollide or lCollide: return",
"players downward accleration self.flapAcc = -9 # players speed on flapping self.flapped =",
"getRandomPipe() # newPipe2 = getRandomPipe() # list of upper pipes upperPipes = [",
"self.accY = 1 # players downward accleration self.flapAcc = -9 # players speed",
"def mainGame(): players = [] for i in range(0,1): players.append(Player()) # get 2",
"upperPipes lowerPipes list newPipe1 = getRandomPipe() # newPipe2 = getRandomPipe() # list of",
"= crashInfo['player'] upperPipes, lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes'] while True: for event in pygame.event.get():",
"= pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT) # if",
"0 or rect.height == 0: return False return True if __name__ == '__main__':",
"crashInfo = mainGame() showGameOverScreen(crashInfo) def mainGame(): players = [] for i in range(0,1):",
"'upperPipes': upperPipes, 'lowerPipes': lowerPipes, } # check for score playerMidPos = player.x +",
"True when player flaps self.score = 0 def update(self, event): if event.type ==",
"score in center of screen\"\"\" label = myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label, (10, 10))",
"= pipe['x'] + PIPEWIDTH / 2 if pipeMidPos <= playerMidPos < pipeMidPos +",
"= pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT) # if bird collided with upipe or lpipe",
"lowerpipe lowerPipes = [ newPipe1[1], # newPipe2[1], ] pipeVelX = -4 while True:",
"= False player.y += min(player.velY, BASEY - player.y - player.height) # print score",
"pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes the",
"upperPipes.pop(0) lowerPipes.pop(0) # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255),",
"0.2) self.width = 20 self.height = 20 maxValue = int((SCREENHEIGHT - self.height) /",
"int((SCREENHEIGHT - self.height) * random.randint(minValue, maxValue) / 100 ) # player velocity, max",
"= -9 # players speed on flapping self.flapped = False # True when",
"FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe(): \"\"\"returns a randomly generated pipe\"\"\" # y of gap",
"zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX lPipe['x'] += pipeVelX # add new pipe when",
"upper and lower pipe rects uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect =",
"= random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE)) gapY += int(BASEY * 0.2) pipeX",
"# print score so player overlaps the score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y,",
"pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN,",
"uPipe, lPipe in zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX lPipe['x'] += pipeVelX # add",
"player's velocity along Y, default same as playerFlapped self.maxVelY = 10 # max",
"lower pipe ] def showScore(score): \"\"\"displays score in center of screen\"\"\" label =",
"player.y + player.height >= BASEY - 1: return [True, True] else: playerRect =",
"{ 'player': player, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes, } # check for score playerMidPos",
"K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE or event.key",
"left of screen if 0 < upperPipes[0]['x'] < 5: newPipe = getRandomPipe() upperPipes.append(newPipe[0])",
"getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove first pipe if its out of the screen",
"True] else: playerRect = pygame.Rect(player.x, player.y, player.width, player.height) for uPipe, lPipe in zip(upperPipes,",
"ground if player.y + player.height >= BASEY - 1: return [True, True] else:",
"left for uPipe, lPipe in zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX lPipe['x'] += pipeVelX",
"myfont = pygame.font.SysFont(\"Comic Sans MS\", 30) while True: crashInfo = mainGame() showGameOverScreen(crashInfo) def",
"playerRect = pygame.Rect(player.x, player.y, player.width, player.height) for uPipe, lPipe in zip(upperPipes, lowerPipes): #",
"random.randint(minValue, maxValue) / 100 ) # player velocity, max velocity, downward accleration, accleration",
"self.x = int(SCREENWIDTH * 0.2) self.width = 20 self.height = 20 maxValue =",
"QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type",
"+ player.width / 2 for pipe in upperPipes: pipeMidPos = pipe['x'] + PIPEWIDTH",
"of screen\"\"\" label = myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label, (10, 10)) def checkCrash(player, upperPipes,",
"upperPipes, lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes'] while True: for event in pygame.event.get(): if event.type",
"uCollide or lCollide: return [True, False] return [False, False] def pixelCollision(rect1, rect2): \"\"\"Checks",
">= BASEY - 1: return [True, True] else: playerRect = pygame.Rect(player.x, player.y, player.width,",
"self.velY = self.flapAcc self.flapped = True def main(): global SCREEN, FPSCLOCK, myfont pygame.init()",
"pipe['x'] + PIPEWIDTH / 2 if pipeMidPos <= playerMidPos < pipeMidPos + 4:",
"in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for",
"of upper pipes upperPipes = [ newPipe1[0], # newPipe2[0], ] # list of",
"player = crashInfo['player'] upperPipes, lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes'] while True: for event in",
"4: player.score += 1 # player's movement if player.velY < player.maxVelY and not",
"showScore(score): \"\"\"displays score in center of screen\"\"\" label = myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label,",
"with base or pipes.\"\"\" # if player crashes into ground if player.y +",
"pipe in upperPipes: pipeMidPos = pipe['x'] + PIPEWIDTH / 2 if pipeMidPos <=",
"for uPipe, lPipe in zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX lPipe['x'] += pipeVelX #",
"class Player: def __init__(self): self.x = int(SCREENWIDTH * 0.2) self.width = 20 self.height",
"if len(players) ==0: return { 'player': player, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes, } #",
"player overlaps the score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) pygame.display.update()",
"gapY += int(BASEY * 0.2) pipeX = SCREENWIDTH + 10 return [ {'x':",
"uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT))",
"player.y, player.width, player.height) for uPipe, lPipe in zip(upperPipes, lowerPipes): # upper and lower",
"event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key",
"newPipe = getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove first pipe if its out of",
"= [] for i in range(0,1): players.append(Player()) # get 2 new pipes to",
"- player.height) # print score so player overlaps the score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200),",
"list of lowerpipe lowerPipes = [ newPipe1[1], # newPipe2[1], ] pipeVelX = -4",
"event # move pipes to left for uPipe, lPipe in zip(upperPipes, lowerPipes): uPipe['x']",
"self.height) * random.randint(minValue, maxValue) / 100 ) # player velocity, max velocity, downward",
"playerFlapped self.maxVelY = 10 # max vel along Y, max descend speed self.accY",
"PIPEWIDTH / 2 if pipeMidPos <= playerMidPos < pipeMidPos + 4: player.score +=",
"or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type ==",
"lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score)",
"2 for pipe in upperPipes: pipeMidPos = pipe['x'] + PIPEWIDTH / 2 if",
"upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove first pipe if its out of the screen if",
"self.flapped = False # True when player flaps self.score = 0 def update(self,",
"import sys import pygame from pygame.locals import * FPS = 30 SCREENWIDTH =",
"SCREENWIDTH = 512 SCREENHEIGHT = 512 # amount by which base can maximum",
"# players speed on flapping self.flapped = False # True when player flaps",
"screen if 0 < upperPipes[0]['x'] < 5: newPipe = getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) #",
"return { 'player': player, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes, } # check for score",
"(255,255,255,200), (player.x, player.y, player.width, player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes the player",
"player.width, player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes the player down ans shows",
"lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT) # if bird collided with upipe or",
"new pipe when first pipe is about to touch left of screen if",
"showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes",
"upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in",
"K_SPACE or event.key == K_UP): return # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe",
"False] def pixelCollision(rect1, rect2): \"\"\"Checks if two objects collide and not just their",
"-9 # player's velocity along Y, default same as playerFlapped self.maxVelY = 10",
"upperPipes = [ newPipe1[0], # newPipe2[0], ] # list of lowerpipe lowerPipes =",
"from itertools import cycle import random import sys import pygame from pygame.locals import",
"event): if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):",
"player.y += min(player.velY, BASEY - player.y - player.height) # print score so player",
"= False # True when player flaps self.score = 0 def update(self, event):",
"event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): if self.y",
"event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE",
"< -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes,",
"<= playerMidPos < pipeMidPos + 4: player.score += 1 # player's movement if",
"{'x': pipeX, 'y': gapY + PIPEGAPSIZE}, # lower pipe ] def showScore(score): \"\"\"displays",
"(lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width),",
"= player.x + player.width / 2 for pipe in upperPipes: pipeMidPos = pipe['x']",
"check for score playerMidPos = player.x + player.width / 2 for pipe in",
"on flap self.velY = -9 # player's velocity along Y, default same as",
"player.height) for uPipe, lPipe in zip(upperPipes, lowerPipes): # upper and lower pipe rects",
"pygame.display.set_caption('Flappy Bird') myfont = pygame.font.SysFont(\"Comic Sans MS\", 30) while True: crashInfo = mainGame()",
"(event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN",
"1, (255,255,255)) SCREEN.blit(label, (10, 10)) def checkCrash(player, upperPipes, lowerPipes): \"\"\"returns True if player",
"or pipes.\"\"\" # if player crashes into ground if player.y + player.height >=",
"myfont pygame.init() FPSCLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont =",
"print score so player overlaps the score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width,",
"= type('', (object,),{ 'type': 0, 'key': 0}) for event in pygame.event.get(): if event.type",
"pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for player in players: player.update(playerEvent) # check for crash here",
"in center of screen\"\"\" label = myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label, (10, 10)) def",
"# if bird collided with upipe or lpipe uCollide = pixelCollision(playerRect, uPipeRect) lCollide",
"rects uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT)",
"def __init__(self): self.x = int(SCREENWIDTH * 0.2) self.width = 20 self.height = 20",
"player.height >= BASEY - 1: return [True, True] else: playerRect = pygame.Rect(player.x, player.y,",
"100 ) # player velocity, max velocity, downward accleration, accleration on flap self.velY",
"= myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label, (10, 10)) def checkCrash(player, upperPipes, lowerPipes): \"\"\"returns True",
"# add new pipe when first pipe is about to touch left of",
"= [ newPipe1[1], # newPipe2[1], ] pipeVelX = -4 while True: playerEvent =",
"showGameOverScreen(crashInfo) def mainGame(): players = [] for i in range(0,1): players.append(Player()) # get",
"if crashTest[0]: players.remove(player) if len(players) ==0: return { 'player': player, 'upperPipes': upperPipes, 'lowerPipes':",
"= 512 SCREENHEIGHT = 512 # amount by which base can maximum shift",
"+= player.accY if player.flapped: player.flapped = False player.y += min(player.velY, BASEY - player.y",
"playerEvent = type('', (object,),{ 'type': 0, 'key': 0}) for event in pygame.event.get(): if",
"# newPipe2[1], ] pipeVelX = -4 while True: playerEvent = type('', (object,),{ 'type':",
"100) self.y = int((SCREENHEIGHT - self.height) * random.randint(minValue, maxValue) / 100 ) #",
"self.flapAcc = -9 # players speed on flapping self.flapped = False # True",
"velocity, downward accleration, accleration on flap self.velY = -9 # player's velocity along",
"in upperPipes: pipeMidPos = pipe['x'] + PIPEWIDTH / 2 if pipeMidPos <= playerMidPos",
"uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT) # if bird collided",
"== KEYDOWN and (event.key == K_SPACE or event.key == K_UP): return # draw",
"when player flaps self.score = 0 def update(self, event): if event.type == KEYDOWN",
"> -2 * self.height: self.velY = self.flapAcc self.flapped = True def main(): global",
"= getRandomPipe() # newPipe2 = getRandomPipe() # list of upper pipes upperPipes =",
"# upper pipe {'x': pipeX, 'y': gapY + PIPEGAPSIZE}, # lower pipe ]",
"= -4 while True: playerEvent = type('', (object,),{ 'type': 0, 'key': 0}) for",
"= mainGame() showGameOverScreen(crashInfo) def mainGame(): players = [] for i in range(0,1): players.append(Player())",
"of the screen if upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) # draw sprites SCREEN.fill((0,0,0))",
"velocity, max velocity, downward accleration, accleration on flap self.velY = -9 # player's",
"= 0 def update(self, event): if event.type == KEYDOWN and (event.key == K_SPACE",
"* 0.2) pipeX = SCREENWIDTH + 10 return [ {'x': pipeX, 'y': gapY",
"} # check for score playerMidPos = player.x + player.width / 2 for",
"maxValue) / 100 ) # player velocity, max velocity, downward accleration, accleration on",
"pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for player in players:",
"checkCrash(player, upperPipes, lowerPipes): \"\"\"returns True if player collders with base or pipes.\"\"\" #",
"SCREENHEIGHT * 100) self.y = int((SCREENHEIGHT - self.height) * random.randint(minValue, maxValue) / 100",
"-9 # players speed on flapping self.flapped = False # True when player",
"int(SCREENWIDTH * 0.2) self.width = 20 self.height = 20 maxValue = int((SCREENHEIGHT -",
"# players downward accleration self.flapAcc = -9 # players speed on flapping self.flapped",
"pipe if its out of the screen if upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0)",
"if player.y + player.height >= BASEY - 1: return [True, True] else: playerRect",
"int((SCREENHEIGHT - self.height) / SCREENHEIGHT * 100) minValue = int(self.height / SCREENHEIGHT *",
"their rects\"\"\" rect = rect1.clip(rect2) if rect.width == 0 or rect.height == 0:",
"pixelCollision(rect1, rect2): \"\"\"Checks if two objects collide and not just their rects\"\"\" rect",
"pygame from pygame.locals import * FPS = 30 SCREENWIDTH = 512 SCREENHEIGHT =",
"gameover image\"\"\" player = crashInfo['player'] upperPipes, lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes'] while True: for",
"return [ {'x': pipeX, 'y': gapY - PIPEHEIGHT}, # upper pipe {'x': pipeX,",
"and (event.key == K_SPACE or event.key == K_UP): playerEvent = event # move",
"lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for player in",
"shows gameover image\"\"\" player = crashInfo['player'] upperPipes, lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes'] while True:",
"newPipe1[0], # newPipe2[0], ] # list of lowerpipe lowerPipes = [ newPipe1[1], #",
"-PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes):",
"getRandomPipe(): \"\"\"returns a randomly generated pipe\"\"\" # y of gap between upper and",
"pygame.init() FPSCLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont = pygame.font.SysFont(\"Comic",
"score so player overlaps the score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width),",
"into ground if player.y + player.height >= BASEY - 1: return [True, True]",
"# if player crashes into ground if player.y + player.height >= BASEY -",
"K_UP): if self.y > -2 * self.height: self.velY = self.flapAcc self.flapped = True",
"Player: def __init__(self): self.x = int(SCREENWIDTH * 0.2) self.width = 20 self.height =",
"bird collided with upipe or lpipe uCollide = pixelCollision(playerRect, uPipeRect) lCollide = pixelCollision(playerRect,",
"default same as playerFlapped self.maxVelY = 10 # max vel along Y, max",
"# list of lowerpipe lowerPipes = [ newPipe1[1], # newPipe2[1], ] pipeVelX =",
"checkCrash(player, upperPipes, lowerPipes) if crashTest[0]: players.remove(player) if len(players) ==0: return { 'player': player,",
"# lower pipe ] def showScore(score): \"\"\"displays score in center of screen\"\"\" label",
"# list of upper pipes upperPipes = [ newPipe1[0], # newPipe2[0], ] #",
"return # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'],",
"True def main(): global SCREEN, FPSCLOCK, myfont pygame.init() FPSCLOCK = pygame.time.Clock() SCREEN =",
"== K_UP): return # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes):",
"upperPipes, lowerPipes): \"\"\"returns True if player collders with base or pipes.\"\"\" # if",
"def showGameOverScreen(crashInfo): \"\"\"crashes the player down ans shows gameover image\"\"\" player = crashInfo['player']",
"[ newPipe1[0], # newPipe2[0], ] # list of lowerpipe lowerPipes = [ newPipe1[1],",
"or lCollide: return [True, False] return [False, False] def pixelCollision(rect1, rect2): \"\"\"Checks if",
"-2 * self.height: self.velY = self.flapAcc self.flapped = True def main(): global SCREEN,",
"pipeMidPos <= playerMidPos < pipeMidPos + 4: player.score += 1 # player's movement",
"KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key",
"BASEY,SCREENWIDTH,BASEY)) for player in players: player.update(playerEvent) # check for crash here crashTest =",
"of lowerpipe lowerPipes = [ newPipe1[1], # newPipe2[1], ] pipeVelX = -4 while",
"def pixelCollision(rect1, rect2): \"\"\"Checks if two objects collide and not just their rects\"\"\"",
"= 50 BASEY = SCREENHEIGHT * 0.79 BASEX = 0 try: xrange except",
"if its out of the screen if upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) #",
"downward accleration, accleration on flap self.velY = -9 # player's velocity along Y,",
"or lpipe uCollide = pixelCollision(playerRect, uPipeRect) lCollide = pixelCollision(playerRect, lPipeRect) if uCollide or",
"= rect1.clip(rect2) if rect.width == 0 or rect.height == 0: return False return",
"10)) def checkCrash(player, upperPipes, lowerPipes): \"\"\"returns True if player collders with base or",
"score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo):",
"uPipeRect) lCollide = pixelCollision(playerRect, lPipeRect) if uCollide or lCollide: return [True, False] return",
"rect.width == 0 or rect.height == 0: return False return True if __name__",
"if bird collided with upipe or lpipe uCollide = pixelCollision(playerRect, uPipeRect) lCollide =",
"event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit()",
"except NameError: xrange = range class Player: def __init__(self): self.x = int(SCREENWIDTH *",
"vel along Y, max descend speed self.accY = 1 # players downward accleration",
"player.velY < player.maxVelY and not player.flapped: player.velY += player.accY if player.flapped: player.flapped =",
"same as playerFlapped self.maxVelY = 10 # max vel along Y, max descend",
"for score playerMidPos = player.x + player.width / 2 for pipe in upperPipes:",
"+ PIPEWIDTH / 2 if pipeMidPos <= playerMidPos < pipeMidPos + 4: player.score",
"import * FPS = 30 SCREENWIDTH = 512 SCREENHEIGHT = 512 # amount",
"maximum shift to left PIPEGAPSIZE = 100 # gap between upper and lower",
"= 10 # max vel along Y, max descend speed self.accY = 1",
"-4 while True: playerEvent = type('', (object,),{ 'type': 0, 'key': 0}) for event",
"players: player.update(playerEvent) # check for crash here crashTest = checkCrash(player, upperPipes, lowerPipes) if",
"==0: return { 'player': player, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes, } # check for",
"def showScore(score): \"\"\"displays score in center of screen\"\"\" label = myfont.render(str(score), 1, (255,255,255))",
"= 512 # amount by which base can maximum shift to left PIPEGAPSIZE",
"players = [] for i in range(0,1): players.append(Player()) # get 2 new pipes",
"lPipeRect) if uCollide or lCollide: return [True, False] return [False, False] def pixelCollision(rect1,",
"update(self, event): if event.type == KEYDOWN and (event.key == K_SPACE or event.key ==",
"if self.y > -2 * self.height: self.velY = self.flapAcc self.flapped = True def",
"in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key ==",
"] def showScore(score): \"\"\"displays score in center of screen\"\"\" label = myfont.render(str(score), 1,",
"player crashes into ground if player.y + player.height >= BASEY - 1: return",
"zip(upperPipes, lowerPipes): # upper and lower pipe rects uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH,",
"SCREENHEIGHT * 0.79 BASEX = 0 try: xrange except NameError: xrange = range",
"FPS = 30 SCREENWIDTH = 512 SCREENHEIGHT = 512 # amount by which",
"100 # gap between upper and lower part of pipe PIPEHEIGHT = 300",
"FPSCLOCK, myfont pygame.init() FPSCLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont",
"lPipe in zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX lPipe['x'] += pipeVelX # add new",
"mainGame() showGameOverScreen(crashInfo) def mainGame(): players = [] for i in range(0,1): players.append(Player()) #",
"# upper and lower pipe rects uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect",
"K_UP): return # draw sprites SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255),",
"pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont = pygame.font.SysFont(\"Comic Sans MS\", 30) while True: crashInfo",
"first pipe is about to touch left of screen if 0 < upperPipes[0]['x']",
"(player.x, player.y, player.width, player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes the player down",
"flaps self.score = 0 def update(self, event): if event.type == KEYDOWN and (event.key",
"newPipe1[1], # newPipe2[1], ] pipeVelX = -4 while True: playerEvent = type('', (object,),{",
"player.y - player.height) # print score so player overlaps the score showScore(player.score) pygame.draw.ellipse(SCREEN,",
"self.velY = -9 # player's velocity along Y, default same as playerFlapped self.maxVelY",
"- 1: return [True, True] else: playerRect = pygame.Rect(player.x, player.y, player.width, player.height) for",
"to left PIPEGAPSIZE = 100 # gap between upper and lower part of",
"\"\"\"returns a randomly generated pipe\"\"\" # y of gap between upper and lower",
"pipeVelX # add new pipe when first pipe is about to touch left",
"50 BASEY = SCREENHEIGHT * 0.79 BASEX = 0 try: xrange except NameError:",
"self.flapAcc self.flapped = True def main(): global SCREEN, FPSCLOCK, myfont pygame.init() FPSCLOCK =",
"try: xrange except NameError: xrange = range class Player: def __init__(self): self.x =",
"pipes upperPipes = [ newPipe1[0], # newPipe2[0], ] # list of lowerpipe lowerPipes",
"PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y,",
"just their rects\"\"\" rect = rect1.clip(rect2) if rect.width == 0 or rect.height ==",
"[ newPipe1[1], # newPipe2[1], ] pipeVelX = -4 while True: playerEvent = type('',",
"to left for uPipe, lPipe in zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX lPipe['x'] +=",
"event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): return #",
"self.height = 20 maxValue = int((SCREENHEIGHT - self.height) / SCREENHEIGHT * 100) minValue",
"pixelCollision(playerRect, lPipeRect) if uCollide or lCollide: return [True, False] return [False, False] def",
"SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') myfont = pygame.font.SysFont(\"Comic Sans MS\", 30) while",
"i in range(0,1): players.append(Player()) # get 2 new pipes to add to upperPipes",
"KEYDOWN and (event.key == K_SPACE or event.key == K_UP): playerEvent = event #",
"(255,255,255,200), (player.x, player.y, player.width, player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe(): \"\"\"returns a randomly",
"Y, default same as playerFlapped self.maxVelY = 10 # max vel along Y,",
"* 100) self.y = int((SCREENHEIGHT - self.height) * random.randint(minValue, maxValue) / 100 )",
"max descend speed self.accY = 1 # players downward accleration self.flapAcc = -9",
"for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255),",
"pipeX, 'y': gapY - PIPEHEIGHT}, # upper pipe {'x': pipeX, 'y': gapY +",
"self.score = 0 def update(self, event): if event.type == KEYDOWN and (event.key ==",
"# remove first pipe if its out of the screen if upperPipes[0]['x'] <",
"here crashTest = checkCrash(player, upperPipes, lowerPipes) if crashTest[0]: players.remove(player) if len(players) ==0: return",
"while True: for event in pygame.event.get(): if event.type == QUIT or (event.type ==",
"of gap between upper and lower pipe gapY = random.randrange(0, int(BASEY * 0.6",
"NameError: xrange = range class Player: def __init__(self): self.x = int(SCREENWIDTH * 0.2)",
"of pipe PIPEHEIGHT = 300 PIPEWIDTH = 50 BASEY = SCREENHEIGHT * 0.79",
"True: playerEvent = type('', (object,),{ 'type': 0, 'key': 0}) for event in pygame.event.get():",
"< 5: newPipe = getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove first pipe if its",
"movement if player.velY < player.maxVelY and not player.flapped: player.velY += player.accY if player.flapped:",
"= checkCrash(player, upperPipes, lowerPipes) if crashTest[0]: players.remove(player) if len(players) ==0: return { 'player':",
"max vel along Y, max descend speed self.accY = 1 # players downward",
"- self.height) / SCREENHEIGHT * 100) minValue = int(self.height / SCREENHEIGHT * 100)",
"/ 2 if pipeMidPos <= playerMidPos < pipeMidPos + 4: player.score += 1",
"10 # max vel along Y, max descend speed self.accY = 1 #",
"crashInfo['player'] upperPipes, lowerPipes = crashInfo['upperPipes'], crashInfo['lowerPipes'] while True: for event in pygame.event.get(): if",
"accleration on flap self.velY = -9 # player's velocity along Y, default same",
"FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes the player down ans shows gameover image\"\"\" player =",
"screen\"\"\" label = myfont.render(str(score), 1, (255,255,255)) SCREEN.blit(label, (10, 10)) def checkCrash(player, upperPipes, lowerPipes):",
"upper and lower part of pipe PIPEHEIGHT = 300 PIPEWIDTH = 50 BASEY",
"collders with base or pipes.\"\"\" # if player crashes into ground if player.y",
"lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255),",
"pipeVelX = -4 while True: playerEvent = type('', (object,),{ 'type': 0, 'key': 0})",
"lowerPipes) if crashTest[0]: players.remove(player) if len(players) ==0: return { 'player': player, 'upperPipes': upperPipes,",
"self.flapped = True def main(): global SCREEN, FPSCLOCK, myfont pygame.init() FPSCLOCK = pygame.time.Clock()",
"to touch left of screen if 0 < upperPipes[0]['x'] < 5: newPipe =",
"lower pipe rects uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], PIPEWIDTH, PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'],",
"pipes to add to upperPipes lowerPipes list newPipe1 = getRandomPipe() # newPipe2 =",
"the score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS) def",
"pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe(): \"\"\"returns a",
"first pipe if its out of the screen if upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0)",
"and not player.flapped: player.velY += player.accY if player.flapped: player.flapped = False player.y +=",
"max velocity, downward accleration, accleration on flap self.velY = -9 # player's velocity",
"KEYDOWN and (event.key == K_SPACE or event.key == K_UP): if self.y > -2",
"== K_SPACE or event.key == K_UP): return # draw sprites SCREEN.fill((0,0,0)) for uPipe,",
"== K_SPACE or event.key == K_UP): playerEvent = event # move pipes to",
"30 SCREENWIDTH = 512 SCREENHEIGHT = 512 # amount by which base can",
"pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT) # if bird collided with upipe or lpipe uCollide",
"SCREENHEIGHT = 512 # amount by which base can maximum shift to left",
"== K_UP): if self.y > -2 * self.height: self.velY = self.flapAcc self.flapped =",
"uPipe['x'] += pipeVelX lPipe['x'] += pipeVelX # add new pipe when first pipe",
"pipes.\"\"\" # if player crashes into ground if player.y + player.height >= BASEY",
"type('', (object,),{ 'type': 0, 'key': 0}) for event in pygame.event.get(): if event.type ==",
"pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE or event.key ==",
"the player down ans shows gameover image\"\"\" player = crashInfo['player'] upperPipes, lowerPipes =",
"BASEY,SCREENWIDTH,BASEY)) showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe():",
"pipe\"\"\" # y of gap between upper and lower pipe gapY = random.randrange(0,",
"False player.y += min(player.velY, BASEY - player.y - player.height) # print score so",
"\"\"\"returns True if player collders with base or pipes.\"\"\" # if player crashes",
"20 self.height = 20 maxValue = int((SCREENHEIGHT - self.height) / SCREENHEIGHT * 100)",
"== KEYDOWN and (event.key == K_SPACE or event.key == K_UP): if self.y >",
"== K_SPACE or event.key == K_UP): if self.y > -2 * self.height: self.velY",
"player collders with base or pipes.\"\"\" # if player crashes into ground if",
"SCREEN.fill((0,0,0)) for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'],",
"about to touch left of screen if 0 < upperPipes[0]['x'] < 5: newPipe",
"player.x + player.width / 2 for pipe in upperPipes: pipeMidPos = pipe['x'] +",
"on flapping self.flapped = False # True when player flaps self.score = 0",
"1 # players downward accleration self.flapAcc = -9 # players speed on flapping",
"along Y, max descend speed self.accY = 1 # players downward accleration self.flapAcc",
"# player's velocity along Y, default same as playerFlapped self.maxVelY = 10 #",
"PIPEHEIGHT) lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], PIPEWIDTH, PIPEHEIGHT) # if bird collided with upipe",
"upipe or lpipe uCollide = pixelCollision(playerRect, uPipeRect) lCollide = pixelCollision(playerRect, lPipeRect) if uCollide",
"20 maxValue = int((SCREENHEIGHT - self.height) / SCREENHEIGHT * 100) minValue = int(self.height",
"10 return [ {'x': pipeX, 'y': gapY - PIPEHEIGHT}, # upper pipe {'x':",
"upperPipes, lowerPipes) if crashTest[0]: players.remove(player) if len(players) ==0: return { 'player': player, 'upperPipes':",
"= 300 PIPEWIDTH = 50 BASEY = SCREENHEIGHT * 0.79 BASEX = 0",
"upperPipes, 'lowerPipes': lowerPipes, } # check for score playerMidPos = player.x + player.width",
"left PIPEGAPSIZE = 100 # gap between upper and lower part of pipe",
"event.key == K_UP): if self.y > -2 * self.height: self.velY = self.flapAcc self.flapped",
"== KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and",
"return [True, False] return [False, False] def pixelCollision(rect1, rect2): \"\"\"Checks if two objects",
"'key': 0}) for event in pygame.event.get(): if event.type == QUIT or (event.type ==",
"pipeMidPos = pipe['x'] + PIPEWIDTH / 2 if pipeMidPos <= playerMidPos < pipeMidPos",
"player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS) def showGameOverScreen(crashInfo): \"\"\"crashes the player down ans shows gameover",
"player.maxVelY and not player.flapped: player.velY += player.accY if player.flapped: player.flapped = False player.y",
"False] return [False, False] def pixelCollision(rect1, rect2): \"\"\"Checks if two objects collide and",
"Bird') myfont = pygame.font.SysFont(\"Comic Sans MS\", 30) while True: crashInfo = mainGame() showGameOverScreen(crashInfo)",
"overlaps the score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0) pygame.display.update() FPSCLOCK.tick(FPS)",
"player flaps self.score = 0 def update(self, event): if event.type == KEYDOWN and",
"lowerPipes = [ newPipe1[1], # newPipe2[1], ] pipeVelX = -4 while True: playerEvent",
"K_SPACE or event.key == K_UP): playerEvent = event # move pipes to left",
"= 0 try: xrange except NameError: xrange = range class Player: def __init__(self):",
"for uPipe, lPipe in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH,",
"30) while True: crashInfo = mainGame() showGameOverScreen(crashInfo) def mainGame(): players = [] for",
"# y of gap between upper and lower pipe gapY = random.randrange(0, int(BASEY",
"import cycle import random import sys import pygame from pygame.locals import * FPS",
"0, 'key': 0}) for event in pygame.event.get(): if event.type == QUIT or (event.type",
"- PIPEHEIGHT}, # upper pipe {'x': pipeX, 'y': gapY + PIPEGAPSIZE}, # lower",
"0 < upperPipes[0]['x'] < 5: newPipe = getRandomPipe() upperPipes.append(newPipe[0]) lowerPipes.append(newPipe[1]) # remove first",
"# check for score playerMidPos = player.x + player.width / 2 for pipe",
"== KEYDOWN and (event.key == K_SPACE or event.key == K_UP): playerEvent = event",
"crashes into ground if player.y + player.height >= BASEY - 1: return [True,",
"objects collide and not just their rects\"\"\" rect = rect1.clip(rect2) if rect.width ==",
"2 if pipeMidPos <= playerMidPos < pipeMidPos + 4: player.score += 1 #",
"+ player.height >= BASEY - 1: return [True, True] else: playerRect = pygame.Rect(player.x,",
"which base can maximum shift to left PIPEGAPSIZE = 100 # gap between",
"player down ans shows gameover image\"\"\" player = crashInfo['player'] upperPipes, lowerPipes = crashInfo['upperPipes'],",
"player.width, player.width), 0) FPSCLOCK.tick(FPS) pygame.display.update() def getRandomPipe(): \"\"\"returns a randomly generated pipe\"\"\" #",
"Sans MS\", 30) while True: crashInfo = mainGame() showGameOverScreen(crashInfo) def mainGame(): players =",
"so player overlaps the score showScore(player.score) pygame.draw.ellipse(SCREEN, (255,255,255,200), (player.x, player.y, player.width, player.width), 0)",
"can maximum shift to left PIPEGAPSIZE = 100 # gap between upper and",
"lPipe['y'],PIPEWIDTH,PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX, BASEY,SCREENWIDTH,BASEY)) for player in players: player.update(playerEvent) # check for crash",
"base can maximum shift to left PIPEGAPSIZE = 100 # gap between upper",
"flapping self.flapped = False # True when player flaps self.score = 0 def",
"velocity along Y, default same as playerFlapped self.maxVelY = 10 # max vel",
"and not just their rects\"\"\" rect = rect1.clip(rect2) if rect.width == 0 or",
"amount by which base can maximum shift to left PIPEGAPSIZE = 100 #",
"def getRandomPipe(): \"\"\"returns a randomly generated pipe\"\"\" # y of gap between upper",
"while True: playerEvent = type('', (object,),{ 'type': 0, 'key': 0}) for event in",
"pipeVelX lPipe['x'] += pipeVelX # add new pipe when first pipe is about",
"the screen if upperPipes[0]['x'] < -PIPEWIDTH: upperPipes.pop(0) lowerPipes.pop(0) # draw sprites SCREEN.fill((0,0,0)) for",
"(event.key == K_SPACE or event.key == K_UP): if self.y > -2 * self.height:",
"sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):",
"newPipe2[1], ] pipeVelX = -4 while True: playerEvent = type('', (object,),{ 'type': 0,",
"for crash here crashTest = checkCrash(player, upperPipes, lowerPipes) if crashTest[0]: players.remove(player) if len(players)",
"in zip(upperPipes, lowerPipes): pygame.draw.rect(SCREEN,(255,255,255), (uPipe['x'], uPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (lPipe['x'], lPipe['y'],PIPEWIDTH, PIPEHEIGHT)) pygame.draw.rect(SCREEN,(255,255,255), (BASEX,",
"PIPEWIDTH = 50 BASEY = SCREENHEIGHT * 0.79 BASEX = 0 try: xrange"
] |
[
"redirect('lab_reports') @login_required def lab_reports(request): reports = Report.objects.filter(user = request.user) if reports: return render(request,",
"if appointments: return render(request, \"appointments_list.html\", {'appointments': appointments}) else: message = \"No records Found\"",
"\"No records Found\" return render(request, \"appointments_list.html\", {'message': message}) def single_report(request, report_id): report =",
"from django.shortcuts import render, get_object_or_404 from .models import About,Appointment,Doctor,Report,Service,History from django.http import HttpResponse,HttpResponseRedirect",
"def profile(request): history = History.objects.filter(user = request.user) if history: return render(request, \"profile.html\", {'history':",
"'about': About.objects.all() } return render(request, \"about.html\", context) def doctor_list(request): context = { 'doctors':",
"request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time') doctor = doctor_id user = request.user appointment =",
"views here. def home(request): return render(request, \"index.html\", {}) def about(request): context = {",
"doctor = doctor_id user = request.user appointment = Appointment.objects.create(date=date, time=time, user=user, disease_option=disease, doctor",
"'POST': appointment.delete() return redirect('appointments_list') return redirect('appointments_list') @login_required def lab_report_delete(request, report_id): lab_report = get_object_or_404(Report,",
"date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time') doctor = doctor_id user = request.user appointment = Appointment.objects.create(date=date,",
"Appointment.objects.create(date=date, time=time, user=user, disease_option=disease, doctor = doctor) appointment.save() appointments = Appointment.objects.filter(user = request.user)",
"appointment.delete() return redirect('appointments_list') return redirect('appointments_list') @login_required def lab_report_delete(request, report_id): lab_report = get_object_or_404(Report, pk=report_id)",
"= \"No records Found\" return render(request, \"profile.html\", {'message': message}) @login_required def booking(request, doctor_id):",
"= Appointment.objects.create(date=date, time=time, user=user, disease_option=disease, doctor = doctor) appointment.save() appointments = Appointment.objects.filter(user =",
"Report.objects.filter(user = request.user) if reports: return render(request, \"lab_reports_list.html\", {'reports': reports}) else: message =",
"service_id): service = get_object_or_404(Service, pk=service_id) return render(request, 'single_service.html', {'service': service, 'services_info' : Service.objects.all()})",
"appointment = get_object_or_404(Appointment, pk=appointment_id) if request.method == 'POST': appointment.delete() return redirect('appointments_list') return redirect('appointments_list')",
"= get_object_or_404(Doctor, pk=doctor_id) return render(request, \"single_doctor_booking.html\", {'doctor': doctor}) @login_required def profile(request): history =",
"\"profile.html\", {'message': message}) @login_required def booking(request, doctor_id): if request.method == 'POST' and request.POST.get('Appointment",
"\"lab_reports_list.html\", {'reports': reports}) else: message = \"No records Found\" return render(request, \"lab_reports_list.html\", {'message':",
"Appointment.objects.filter(user = request.user) if appointments: return render(request, \"appointments_list.html\", {'appointments': appointments}) else: message =",
"= { 'service': Service.objects.all() } return render(request, \"services.html\", context) @login_required def appointment_delete(request, appointment_id):",
"def home(request): return render(request, \"index.html\", {}) def about(request): context = { 'about': About.objects.all()",
"HttpResponse,HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth.decorators import login_required # Create your views",
"render(request, \"appointments_list.html\", {'appointments': appointments}) else: message = \"No records Found\" return render(request, \"appointments_list.html\",",
"@login_required def booking(request, doctor_id): if request.method == 'POST' and request.POST.get('Appointment Date') and request.POST.get('Appointment",
"get_object_or_404(Service, pk=service_id) return render(request, 'single_service.html', {'service': service, 'services_info' : Service.objects.all()}) def single_doctor(request,doctor_id): doctor",
"request.method == 'POST' and request.POST.get('Appointment Date') and request.POST.get('Appointment Time'): disease = request.POST.get('issue') date=request.POST.get('Appointment",
"get_object_or_404(Report, pk=report_id) if request.method == 'POST': lab_report.delete() return redirect('lab_reports') return redirect('lab_reports') @login_required def",
"} return render(request, \"about.html\", context) def doctor_list(request): context = { 'doctors': Doctor.objects.all() }",
"history}) else: message = \"No records Found\" return render(request, \"profile.html\", {'message': message}) @login_required",
"redirect('appointments_list') return redirect('appointments_list') @login_required def lab_report_delete(request, report_id): lab_report = get_object_or_404(Report, pk=report_id) if request.method",
"report_id): lab_report = get_object_or_404(Report, pk=report_id) if request.method == 'POST': lab_report.delete() return redirect('lab_reports') return",
"Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) def contactus(request): pass def patient_info(request):",
"appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) else: appointments =",
"context = { 'doctors': Doctor.objects.all() } return render(request, \"doctor_list_booking.html\", context) def services(request): context",
"return render(request, \"lab_reports_list.html\", {'message': message}) @login_required def appointments(request): appointments = Appointment.objects.filter(user = request.user)",
"return render(request, \"doctor_list_booking.html\", context) def services(request): context = { 'service': Service.objects.all() } return",
"def appointment_delete(request, appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id) if request.method == 'POST': appointment.delete() return",
"return render(request, \"services.html\", context) @login_required def appointment_delete(request, appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id) if",
"= get_object_or_404(Report, pk=report_id) return render(request, \"single_report.html\", {'report': report}) def single_service(request, service_id): service =",
"Service.objects.all()}) def single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor, pk=doctor_id) return render(request, \"single_doctor_booking.html\", {'doctor': doctor}) @login_required",
"history: return render(request, \"profile.html\", {'history': history}) else: message = \"No records Found\" return",
"render(request, 'single_service.html', {'service': service, 'services_info' : Service.objects.all()}) def single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor, pk=doctor_id)",
"doctor_id): if request.method == 'POST' and request.POST.get('Appointment Date') and request.POST.get('Appointment Time'): disease =",
"Time'): disease = request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time') doctor = doctor_id user =",
"= request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time') doctor = doctor_id user = request.user appointment",
"Date') time=request.POST.get('Appointment Time') doctor = doctor_id user = request.user appointment = Appointment.objects.create(date=date, time=time,",
"@login_required def lab_report_delete(request, report_id): lab_report = get_object_or_404(Report, pk=report_id) if request.method == 'POST': lab_report.delete()",
"{}) def about(request): context = { 'about': About.objects.all() } return render(request, \"about.html\", context)",
"records Found\" return render(request, \"lab_reports_list.html\", {'message': message}) @login_required def appointments(request): appointments = Appointment.objects.filter(user",
"= get_object_or_404(Service, pk=service_id) return render(request, 'single_service.html', {'service': service, 'services_info' : Service.objects.all()}) def single_doctor(request,doctor_id):",
"request.user) if history: return render(request, \"profile.html\", {'history': history}) else: message = \"No records",
"else: message = \"No records Found\" return render(request, \"profile.html\", {'message': message}) @login_required def",
"'services_info' : Service.objects.all()}) def single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor, pk=doctor_id) return render(request, \"single_doctor_booking.html\", {'doctor':",
"@login_required def profile(request): history = History.objects.filter(user = request.user) if history: return render(request, \"profile.html\",",
"{'report': report}) def single_service(request, service_id): service = get_object_or_404(Service, pk=service_id) return render(request, 'single_service.html', {'service':",
"render(request, \"lab_reports_list.html\", {'message': message}) @login_required def appointments(request): appointments = Appointment.objects.filter(user = request.user) if",
"Date') and request.POST.get('Appointment Time'): disease = request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time') doctor =",
"context) @login_required def appointment_delete(request, appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id) if request.method == 'POST':",
"return render(request, 'single_service.html', {'service': service, 'services_info' : Service.objects.all()}) def single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor,",
"pk=service_id) return render(request, 'single_service.html', {'service': service, 'services_info' : Service.objects.all()}) def single_doctor(request,doctor_id): doctor =",
"def services(request): context = { 'service': Service.objects.all() } return render(request, \"services.html\", context) @login_required",
"Found\" return render(request, \"appointments_list.html\", {'message': message}) def single_report(request, report_id): report = get_object_or_404(Report, pk=report_id)",
"{'message': message}) @login_required def booking(request, doctor_id): if request.method == 'POST' and request.POST.get('Appointment Date')",
"appointment.save() appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) else: appointments",
"service = get_object_or_404(Service, pk=service_id) return render(request, 'single_service.html', {'service': service, 'services_info' : Service.objects.all()}) def",
"def single_report(request, report_id): report = get_object_or_404(Report, pk=report_id) return render(request, \"single_report.html\", {'report': report}) def",
"'POST' and request.POST.get('Appointment Date') and request.POST.get('Appointment Time'): disease = request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment",
"user = request.user appointment = Appointment.objects.create(date=date, time=time, user=user, disease_option=disease, doctor = doctor) appointment.save()",
"disease_option=disease, doctor = doctor) appointment.save() appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html',",
"render(request, \"single_report.html\", {'report': report}) def single_service(request, service_id): service = get_object_or_404(Service, pk=service_id) return render(request,",
"appointment_delete(request, appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id) if request.method == 'POST': appointment.delete() return redirect('appointments_list')",
"request.user) if reports: return render(request, \"lab_reports_list.html\", {'reports': reports}) else: message = \"No records",
"\"profile.html\", {'history': history}) else: message = \"No records Found\" return render(request, \"profile.html\", {'message':",
"\"about.html\", context) def doctor_list(request): context = { 'doctors': Doctor.objects.all() } return render(request, \"doctor_list_booking.html\",",
"render(request, \"about.html\", context) def doctor_list(request): context = { 'doctors': Doctor.objects.all() } return render(request,",
"time=time, user=user, disease_option=disease, doctor = doctor) appointment.save() appointments = Appointment.objects.filter(user = request.user) return",
".models import About,Appointment,Doctor,Report,Service,History from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth.decorators",
"message = \"No records Found\" return render(request, \"profile.html\", {'message': message}) @login_required def booking(request,",
"appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id) if request.method == 'POST': appointment.delete() return redirect('appointments_list') return",
"'POST': lab_report.delete() return redirect('lab_reports') return redirect('lab_reports') @login_required def lab_reports(request): reports = Report.objects.filter(user =",
"\"index.html\", {}) def about(request): context = { 'about': About.objects.all() } return render(request, \"about.html\",",
"appointments}) else: appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) def",
"pk=report_id) return render(request, \"single_report.html\", {'report': report}) def single_service(request, service_id): service = get_object_or_404(Service, pk=service_id)",
"context) def services(request): context = { 'service': Service.objects.all() } return render(request, \"services.html\", context)",
"return redirect('appointments_list') @login_required def lab_report_delete(request, report_id): lab_report = get_object_or_404(Report, pk=report_id) if request.method ==",
"def lab_report_delete(request, report_id): lab_report = get_object_or_404(Report, pk=report_id) if request.method == 'POST': lab_report.delete() return",
"django.contrib.auth.decorators import login_required # Create your views here. def home(request): return render(request, \"index.html\",",
"doctor = doctor) appointment.save() appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments':",
"if request.method == 'POST': appointment.delete() return redirect('appointments_list') return redirect('appointments_list') @login_required def lab_report_delete(request, report_id):",
"redirect('appointments_list') @login_required def lab_report_delete(request, report_id): lab_report = get_object_or_404(Report, pk=report_id) if request.method == 'POST':",
"get_object_or_404(Report, pk=report_id) return render(request, \"single_report.html\", {'report': report}) def single_service(request, service_id): service = get_object_or_404(Service,",
"appointments = Appointment.objects.filter(user = request.user) if appointments: return render(request, \"appointments_list.html\", {'appointments': appointments}) else:",
"# Create your views here. def home(request): return render(request, \"index.html\", {}) def about(request):",
"appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) def contactus(request): pass",
"= { 'doctors': Doctor.objects.all() } return render(request, \"doctor_list_booking.html\", context) def services(request): context =",
"else: message = \"No records Found\" return render(request, \"lab_reports_list.html\", {'message': message}) @login_required def",
"get_object_or_404(Doctor, pk=doctor_id) return render(request, \"single_doctor_booking.html\", {'doctor': doctor}) @login_required def profile(request): history = History.objects.filter(user",
"\"single_doctor_booking.html\", {'doctor': doctor}) @login_required def profile(request): history = History.objects.filter(user = request.user) if history:",
"\"lab_reports_list.html\", {'message': message}) @login_required def appointments(request): appointments = Appointment.objects.filter(user = request.user) if appointments:",
"single_report(request, report_id): report = get_object_or_404(Report, pk=report_id) return render(request, \"single_report.html\", {'report': report}) def single_service(request,",
"reports = Report.objects.filter(user = request.user) if reports: return render(request, \"lab_reports_list.html\", {'reports': reports}) else:",
"message}) def single_report(request, report_id): report = get_object_or_404(Report, pk=report_id) return render(request, \"single_report.html\", {'report': report})",
"@login_required def appointment_delete(request, appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id) if request.method == 'POST': appointment.delete()",
"\"single_report.html\", {'report': report}) def single_service(request, service_id): service = get_object_or_404(Service, pk=service_id) return render(request, 'single_service.html',",
"time=request.POST.get('Appointment Time') doctor = doctor_id user = request.user appointment = Appointment.objects.create(date=date, time=time, user=user,",
"import About,Appointment,Doctor,Report,Service,History from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth.decorators import",
"render(request, \"lab_reports_list.html\", {'reports': reports}) else: message = \"No records Found\" return render(request, \"lab_reports_list.html\",",
"'service': Service.objects.all() } return render(request, \"services.html\", context) @login_required def appointment_delete(request, appointment_id): appointment =",
"Found\" return render(request, \"lab_reports_list.html\", {'message': message}) @login_required def appointments(request): appointments = Appointment.objects.filter(user =",
"if request.method == 'POST': lab_report.delete() return redirect('lab_reports') return redirect('lab_reports') @login_required def lab_reports(request): reports",
"= request.user) if appointments: return render(request, \"appointments_list.html\", {'appointments': appointments}) else: message = \"No",
"\"appointments_list.html\", {'appointments': appointments}) else: message = \"No records Found\" return render(request, \"appointments_list.html\", {'message':",
"user=user, disease_option=disease, doctor = doctor) appointment.save() appointments = Appointment.objects.filter(user = request.user) return render(request,",
"\"No records Found\" return render(request, \"profile.html\", {'message': message}) @login_required def booking(request, doctor_id): if",
"= request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) def contactus(request): pass def patient_info(request): pass",
"def lab_reports(request): reports = Report.objects.filter(user = request.user) if reports: return render(request, \"lab_reports_list.html\", {'reports':",
"return render(request, \"single_report.html\", {'report': report}) def single_service(request, service_id): service = get_object_or_404(Service, pk=service_id) return",
"@login_required def lab_reports(request): reports = Report.objects.filter(user = request.user) if reports: return render(request, \"lab_reports_list.html\",",
"== 'POST': appointment.delete() return redirect('appointments_list') return redirect('appointments_list') @login_required def lab_report_delete(request, report_id): lab_report =",
"request.method == 'POST': lab_report.delete() return redirect('lab_reports') return redirect('lab_reports') @login_required def lab_reports(request): reports =",
"{'doctor': doctor}) @login_required def profile(request): history = History.objects.filter(user = request.user) if history: return",
"{'service': service, 'services_info' : Service.objects.all()}) def single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor, pk=doctor_id) return render(request,",
"doctor}) @login_required def profile(request): history = History.objects.filter(user = request.user) if history: return render(request,",
"from django.contrib.auth.decorators import login_required # Create your views here. def home(request): return render(request,",
"doctor) appointment.save() appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) else:",
"== 'POST' and request.POST.get('Appointment Date') and request.POST.get('Appointment Time'): disease = request.POST.get('issue') date=request.POST.get('Appointment Date')",
"= Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) else: appointments = Appointment.objects.filter(user",
"from .models import About,Appointment,Doctor,Report,Service,History from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import redirect from",
"'appointments_list.html', {'appointments': appointments}) else: appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments':",
"disease = request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time') doctor = doctor_id user = request.user",
"def single_service(request, service_id): service = get_object_or_404(Service, pk=service_id) return render(request, 'single_service.html', {'service': service, 'services_info'",
": Service.objects.all()}) def single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor, pk=doctor_id) return render(request, \"single_doctor_booking.html\", {'doctor': doctor})",
"= request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) else: appointments = Appointment.objects.filter(user = request.user)",
"from django.shortcuts import redirect from django.contrib.auth.decorators import login_required # Create your views here.",
"else: appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) def contactus(request):",
"= Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) def contactus(request): pass def",
"services(request): context = { 'service': Service.objects.all() } return render(request, \"services.html\", context) @login_required def",
"login_required # Create your views here. def home(request): return render(request, \"index.html\", {}) def",
"render(request, \"profile.html\", {'history': history}) else: message = \"No records Found\" return render(request, \"profile.html\",",
"message = \"No records Found\" return render(request, \"lab_reports_list.html\", {'message': message}) @login_required def appointments(request):",
"report = get_object_or_404(Report, pk=report_id) return render(request, \"single_report.html\", {'report': report}) def single_service(request, service_id): service",
"return render(request, \"profile.html\", {'message': message}) @login_required def booking(request, doctor_id): if request.method == 'POST'",
"booking(request, doctor_id): if request.method == 'POST' and request.POST.get('Appointment Date') and request.POST.get('Appointment Time'): disease",
"history = History.objects.filter(user = request.user) if history: return render(request, \"profile.html\", {'history': history}) else:",
"message}) @login_required def appointments(request): appointments = Appointment.objects.filter(user = request.user) if appointments: return render(request,",
"} return render(request, \"doctor_list_booking.html\", context) def services(request): context = { 'service': Service.objects.all() }",
"render(request, \"profile.html\", {'message': message}) @login_required def booking(request, doctor_id): if request.method == 'POST' and",
"= \"No records Found\" return render(request, \"appointments_list.html\", {'message': message}) def single_report(request, report_id): report",
"appointments(request): appointments = Appointment.objects.filter(user = request.user) if appointments: return render(request, \"appointments_list.html\", {'appointments': appointments})",
"About.objects.all() } return render(request, \"about.html\", context) def doctor_list(request): context = { 'doctors': Doctor.objects.all()",
"return redirect('lab_reports') return redirect('lab_reports') @login_required def lab_reports(request): reports = Report.objects.filter(user = request.user) if",
"service, 'services_info' : Service.objects.all()}) def single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor, pk=doctor_id) return render(request, \"single_doctor_booking.html\",",
"django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth.decorators import login_required # Create",
"django.shortcuts import render, get_object_or_404 from .models import About,Appointment,Doctor,Report,Service,History from django.http import HttpResponse,HttpResponseRedirect from",
"Doctor.objects.all() } return render(request, \"doctor_list_booking.html\", context) def services(request): context = { 'service': Service.objects.all()",
"import redirect from django.contrib.auth.decorators import login_required # Create your views here. def home(request):",
"lab_reports(request): reports = Report.objects.filter(user = request.user) if reports: return render(request, \"lab_reports_list.html\", {'reports': reports})",
"\"services.html\", context) @login_required def appointment_delete(request, appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id) if request.method ==",
"render(request, \"doctor_list_booking.html\", context) def services(request): context = { 'service': Service.objects.all() } return render(request,",
"context = { 'service': Service.objects.all() } return render(request, \"services.html\", context) @login_required def appointment_delete(request,",
"= Appointment.objects.filter(user = request.user) if appointments: return render(request, \"appointments_list.html\", {'appointments': appointments}) else: message",
"render, get_object_or_404 from .models import About,Appointment,Doctor,Report,Service,History from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import",
"and request.POST.get('Appointment Date') and request.POST.get('Appointment Time'): disease = request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time')",
"= request.user appointment = Appointment.objects.create(date=date, time=time, user=user, disease_option=disease, doctor = doctor) appointment.save() appointments",
"{ 'service': Service.objects.all() } return render(request, \"services.html\", context) @login_required def appointment_delete(request, appointment_id): appointment",
"= doctor) appointment.save() appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments})",
"return render(request, \"single_doctor_booking.html\", {'doctor': doctor}) @login_required def profile(request): history = History.objects.filter(user = request.user)",
"redirect from django.contrib.auth.decorators import login_required # Create your views here. def home(request): return",
"single_service(request, service_id): service = get_object_or_404(Service, pk=service_id) return render(request, 'single_service.html', {'service': service, 'services_info' :",
"{ 'doctors': Doctor.objects.all() } return render(request, \"doctor_list_booking.html\", context) def services(request): context = {",
"django.shortcuts import redirect from django.contrib.auth.decorators import login_required # Create your views here. def",
"Time') doctor = doctor_id user = request.user appointment = Appointment.objects.create(date=date, time=time, user=user, disease_option=disease,",
"message = \"No records Found\" return render(request, \"appointments_list.html\", {'message': message}) def single_report(request, report_id):",
"{'reports': reports}) else: message = \"No records Found\" return render(request, \"lab_reports_list.html\", {'message': message})",
"{'history': history}) else: message = \"No records Found\" return render(request, \"profile.html\", {'message': message})",
"pk=doctor_id) return render(request, \"single_doctor_booking.html\", {'doctor': doctor}) @login_required def profile(request): history = History.objects.filter(user =",
"from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth.decorators import login_required #",
"here. def home(request): return render(request, \"index.html\", {}) def about(request): context = { 'about':",
"if reports: return render(request, \"lab_reports_list.html\", {'reports': reports}) else: message = \"No records Found\"",
"import render, get_object_or_404 from .models import About,Appointment,Doctor,Report,Service,History from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts",
"def single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor, pk=doctor_id) return render(request, \"single_doctor_booking.html\", {'doctor': doctor}) @login_required def",
"return render(request, 'appointments_list.html', {'appointments': appointments}) else: appointments = Appointment.objects.filter(user = request.user) return render(request,",
"render(request, 'appointments_list.html', {'appointments': appointments}) else: appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html',",
"request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) else: appointments = Appointment.objects.filter(user = request.user) return",
"appointments: return render(request, \"appointments_list.html\", {'appointments': appointments}) else: message = \"No records Found\" return",
"return render(request, \"about.html\", context) def doctor_list(request): context = { 'doctors': Doctor.objects.all() } return",
"return render(request, \"index.html\", {}) def about(request): context = { 'about': About.objects.all() } return",
"= { 'about': About.objects.all() } return render(request, \"about.html\", context) def doctor_list(request): context =",
"{'message': message}) def single_report(request, report_id): report = get_object_or_404(Report, pk=report_id) return render(request, \"single_report.html\", {'report':",
"def about(request): context = { 'about': About.objects.all() } return render(request, \"about.html\", context) def",
"return redirect('appointments_list') return redirect('appointments_list') @login_required def lab_report_delete(request, report_id): lab_report = get_object_or_404(Report, pk=report_id) if",
"def doctor_list(request): context = { 'doctors': Doctor.objects.all() } return render(request, \"doctor_list_booking.html\", context) def",
"def appointments(request): appointments = Appointment.objects.filter(user = request.user) if appointments: return render(request, \"appointments_list.html\", {'appointments':",
"\"No records Found\" return render(request, \"lab_reports_list.html\", {'message': message}) @login_required def appointments(request): appointments =",
"request.user) if appointments: return render(request, \"appointments_list.html\", {'appointments': appointments}) else: message = \"No records",
"else: message = \"No records Found\" return render(request, \"appointments_list.html\", {'message': message}) def single_report(request,",
"if history: return render(request, \"profile.html\", {'history': history}) else: message = \"No records Found\"",
"if request.method == 'POST' and request.POST.get('Appointment Date') and request.POST.get('Appointment Time'): disease = request.POST.get('issue')",
"Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments}) else: appointments = Appointment.objects.filter(user =",
"context = { 'about': About.objects.all() } return render(request, \"about.html\", context) def doctor_list(request): context",
"about(request): context = { 'about': About.objects.all() } return render(request, \"about.html\", context) def doctor_list(request):",
"render(request, \"appointments_list.html\", {'message': message}) def single_report(request, report_id): report = get_object_or_404(Report, pk=report_id) return render(request,",
"lab_report.delete() return redirect('lab_reports') return redirect('lab_reports') @login_required def lab_reports(request): reports = Report.objects.filter(user = request.user)",
"pk=appointment_id) if request.method == 'POST': appointment.delete() return redirect('appointments_list') return redirect('appointments_list') @login_required def lab_report_delete(request,",
"reports: return render(request, \"lab_reports_list.html\", {'reports': reports}) else: message = \"No records Found\" return",
"report_id): report = get_object_or_404(Report, pk=report_id) return render(request, \"single_report.html\", {'report': report}) def single_service(request, service_id):",
"lab_report_delete(request, report_id): lab_report = get_object_or_404(Report, pk=report_id) if request.method == 'POST': lab_report.delete() return redirect('lab_reports')",
"== 'POST': lab_report.delete() return redirect('lab_reports') return redirect('lab_reports') @login_required def lab_reports(request): reports = Report.objects.filter(user",
"= Report.objects.filter(user = request.user) if reports: return render(request, \"lab_reports_list.html\", {'reports': reports}) else: message",
"records Found\" return render(request, \"appointments_list.html\", {'message': message}) def single_report(request, report_id): report = get_object_or_404(Report,",
"= \"No records Found\" return render(request, \"lab_reports_list.html\", {'message': message}) @login_required def appointments(request): appointments",
"home(request): return render(request, \"index.html\", {}) def about(request): context = { 'about': About.objects.all() }",
"request.POST.get('Appointment Date') and request.POST.get('Appointment Time'): disease = request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time') doctor",
"@login_required def appointments(request): appointments = Appointment.objects.filter(user = request.user) if appointments: return render(request, \"appointments_list.html\",",
"return render(request, \"lab_reports_list.html\", {'reports': reports}) else: message = \"No records Found\" return render(request,",
"request.method == 'POST': appointment.delete() return redirect('appointments_list') return redirect('appointments_list') @login_required def lab_report_delete(request, report_id): lab_report",
"'single_service.html', {'service': service, 'services_info' : Service.objects.all()}) def single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor, pk=doctor_id) return",
"appointment = Appointment.objects.create(date=date, time=time, user=user, disease_option=disease, doctor = doctor) appointment.save() appointments = Appointment.objects.filter(user",
"About,Appointment,Doctor,Report,Service,History from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth.decorators import login_required",
"render(request, \"index.html\", {}) def about(request): context = { 'about': About.objects.all() } return render(request,",
"context) def doctor_list(request): context = { 'doctors': Doctor.objects.all() } return render(request, \"doctor_list_booking.html\", context)",
"= get_object_or_404(Report, pk=report_id) if request.method == 'POST': lab_report.delete() return redirect('lab_reports') return redirect('lab_reports') @login_required",
"def booking(request, doctor_id): if request.method == 'POST' and request.POST.get('Appointment Date') and request.POST.get('Appointment Time'):",
"request.POST.get('Appointment Time'): disease = request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time') doctor = doctor_id user",
"return render(request, \"profile.html\", {'history': history}) else: message = \"No records Found\" return render(request,",
"lab_report = get_object_or_404(Report, pk=report_id) if request.method == 'POST': lab_report.delete() return redirect('lab_reports') return redirect('lab_reports')",
"report}) def single_service(request, service_id): service = get_object_or_404(Service, pk=service_id) return render(request, 'single_service.html', {'service': service,",
"redirect('lab_reports') return redirect('lab_reports') @login_required def lab_reports(request): reports = Report.objects.filter(user = request.user) if reports:",
"reports}) else: message = \"No records Found\" return render(request, \"lab_reports_list.html\", {'message': message}) @login_required",
"'doctors': Doctor.objects.all() } return render(request, \"doctor_list_booking.html\", context) def services(request): context = { 'service':",
"return render(request, \"appointments_list.html\", {'message': message}) def single_report(request, report_id): report = get_object_or_404(Report, pk=report_id) return",
"} return render(request, \"services.html\", context) @login_required def appointment_delete(request, appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id)",
"= request.user) if history: return render(request, \"profile.html\", {'history': history}) else: message = \"No",
"= History.objects.filter(user = request.user) if history: return render(request, \"profile.html\", {'history': history}) else: message",
"request.user appointment = Appointment.objects.create(date=date, time=time, user=user, disease_option=disease, doctor = doctor) appointment.save() appointments =",
"get_object_or_404(Appointment, pk=appointment_id) if request.method == 'POST': appointment.delete() return redirect('appointments_list') return redirect('appointments_list') @login_required def",
"render(request, \"single_doctor_booking.html\", {'doctor': doctor}) @login_required def profile(request): history = History.objects.filter(user = request.user) if",
"and request.POST.get('Appointment Time'): disease = request.POST.get('issue') date=request.POST.get('Appointment Date') time=request.POST.get('Appointment Time') doctor = doctor_id",
"= get_object_or_404(Appointment, pk=appointment_id) if request.method == 'POST': appointment.delete() return redirect('appointments_list') return redirect('appointments_list') @login_required",
"render(request, \"services.html\", context) @login_required def appointment_delete(request, appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id) if request.method",
"{'appointments': appointments}) else: message = \"No records Found\" return render(request, \"appointments_list.html\", {'message': message})",
"= request.user) if reports: return render(request, \"lab_reports_list.html\", {'reports': reports}) else: message = \"No",
"Create your views here. def home(request): return render(request, \"index.html\", {}) def about(request): context",
"Service.objects.all() } return render(request, \"services.html\", context) @login_required def appointment_delete(request, appointment_id): appointment = get_object_or_404(Appointment,",
"import HttpResponse,HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth.decorators import login_required # Create your",
"{'appointments': appointments}) else: appointments = Appointment.objects.filter(user = request.user) return render(request, 'appointments_list.html', {'appointments': appointments})",
"doctor_list(request): context = { 'doctors': Doctor.objects.all() } return render(request, \"doctor_list_booking.html\", context) def services(request):",
"message}) @login_required def booking(request, doctor_id): if request.method == 'POST' and request.POST.get('Appointment Date') and",
"appointments}) else: message = \"No records Found\" return render(request, \"appointments_list.html\", {'message': message}) def",
"profile(request): history = History.objects.filter(user = request.user) if history: return render(request, \"profile.html\", {'history': history})",
"{ 'about': About.objects.all() } return render(request, \"about.html\", context) def doctor_list(request): context = {",
"return redirect('lab_reports') @login_required def lab_reports(request): reports = Report.objects.filter(user = request.user) if reports: return",
"pk=report_id) if request.method == 'POST': lab_report.delete() return redirect('lab_reports') return redirect('lab_reports') @login_required def lab_reports(request):",
"= doctor_id user = request.user appointment = Appointment.objects.create(date=date, time=time, user=user, disease_option=disease, doctor =",
"records Found\" return render(request, \"profile.html\", {'message': message}) @login_required def booking(request, doctor_id): if request.method",
"\"doctor_list_booking.html\", context) def services(request): context = { 'service': Service.objects.all() } return render(request, \"services.html\",",
"Found\" return render(request, \"profile.html\", {'message': message}) @login_required def booking(request, doctor_id): if request.method ==",
"\"appointments_list.html\", {'message': message}) def single_report(request, report_id): report = get_object_or_404(Report, pk=report_id) return render(request, \"single_report.html\",",
"doctor_id user = request.user appointment = Appointment.objects.create(date=date, time=time, user=user, disease_option=disease, doctor = doctor)",
"get_object_or_404 from .models import About,Appointment,Doctor,Report,Service,History from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import redirect",
"import login_required # Create your views here. def home(request): return render(request, \"index.html\", {})",
"your views here. def home(request): return render(request, \"index.html\", {}) def about(request): context =",
"single_doctor(request,doctor_id): doctor = get_object_or_404(Doctor, pk=doctor_id) return render(request, \"single_doctor_booking.html\", {'doctor': doctor}) @login_required def profile(request):",
"{'message': message}) @login_required def appointments(request): appointments = Appointment.objects.filter(user = request.user) if appointments: return",
"doctor = get_object_or_404(Doctor, pk=doctor_id) return render(request, \"single_doctor_booking.html\", {'doctor': doctor}) @login_required def profile(request): history",
"return render(request, \"appointments_list.html\", {'appointments': appointments}) else: message = \"No records Found\" return render(request,",
"History.objects.filter(user = request.user) if history: return render(request, \"profile.html\", {'history': history}) else: message ="
] |
[
"{ \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"1\", \"_score\": \"10.114\", \"_source\": { \"title\": \"Test",
"elasticsearch_dsl.connections import add_connection @fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\" client = MagicMock()",
"względów doszli potem się teraz wzrostem dorodniejsza bo tak pan Wojski na nim",
"Francuzi wymowny zrobili wynalazek: iż ludzie są architektury. Choć Sędzia jego bok usiadła",
"Krzyczano na waszych polowaniach łowił? Piękna byłaby sława, ażeby nie było gorąca). wachlarz",
"\"_id\": \"2\", \"_score\": \"12.0\", \"_source\": { \"title\": \"Test elasticsearch numer 2\", \"body\": \"\"\"",
"\"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch\"] }, }, { \"_index\": \"blog\",",
"\"10.114\", \"_source\": { \"title\": \"Test elasticsearch\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś",
"\"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch\"]",
"zbiera się w domu dostatek mieszka i panien nie w nieczynności! a Suwarów",
"zaród. Krzyczano na waszych polowaniach łowił? Piękna byłaby sława, ażeby nie było gorąca).",
"\"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"1\", \"_score\": \"10.114\", \"_source\": { \"title\": \"Test elasticsearch\",",
"ulicę się tajemnie, Ścigany od płaczącej matki pod Turka czy wstydzić, czy na",
"mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\" client = MagicMock() client.search.return_value = dummy_response add_connection(\"mock\", client)",
"rozmowę lecz lekki. odgadniesz, że jacyś Francuzi wymowny zrobili wynalazek: iż ludzie są",
"byłaby sława, ażeby nie było gorąca). wachlarz pozłocist powiewając rozlewał deszcz iskier rzęsisty.",
"fixture_dummy_response(): \"\"\"Returns the dictionary for comparison in tests\"\"\" return { \"_shards\": { \"failed\":",
"\"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch\"] },",
"kryjomu kazał stoły z Paryża a czuł choroby zaród. Krzyczano na waszych polowaniach",
"deszcz iskier rzęsisty. Głowa do Twych świątyń progi iść za zającami nie został",
"\"blog\", \"_type\": \"_doc\", \"_id\": \"1\", \"_score\": \"10.114\", \"_source\": { \"title\": \"Test elasticsearch\", \"body\":",
"między dwie strony: Uciszcie się! woła. Marząc i krwi tonęła, gdy przysięgał na",
"iskier rzęsisty. Głowa do Twych świątyń progi iść za zającami nie został pośmiewiska",
"fixture from elasticsearch_dsl.connections import add_connection @fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\" client",
"też co się przyciągnąć do dworu uprawne dobrze zachowana sklepienie całe wesoło, lecz",
"wzrostem dorodniejsza bo tak pan Wojski na nim ją w ulicę się tajemnie,",
"płaczącej matki pod Turka czy wstydzić, czy na lewo, on rodaków zbiera się",
"client @fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns the dictionary for comparison in tests\"\"\" return {",
"wynalazek: iż ludzie są architektury. Choć Sędzia jego bok usiadła owa piękność zda",
"Zręcznie między dwie strony: Uciszcie się! woła. Marząc i krwi tonęła, gdy przysięgał",
"\"_type\": \"_doc\", \"_id\": \"1\", \"_score\": \"10.114\", \"_source\": { \"title\": \"Test elasticsearch\", \"body\": \"\"\"",
"miał głos miły: Witaj nam, że spod ramion wytknął palce i Asesor, razem,",
"yield client @fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns the dictionary for comparison in tests\"\"\" return",
"dorodniejsza bo tak pan Wojski na nim ją w ulicę się tajemnie, Ścigany",
"jeszcze dobrze na kozłach niemczysko chude na Ojczyzny łono. Tymczasem na nim się",
"ją w ulicę się tajemnie, Ścigany od płaczącej matki pod Turka czy wstydzić,",
"client) yield client @fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns the dictionary for comparison in tests\"\"\"",
"miły: Witaj nam, że spod ramion wytknął palce i Asesor, razem, jakoby zlewa.",
"wachlarz pozłocist powiewając rozlewał deszcz iskier rzęsisty. Głowa do Twych świątyń progi iść",
"import fixture from elasticsearch_dsl.connections import add_connection @fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\"",
"za zającami nie został pośmiewiska celem i niesrogi. Odgadnęła sąsiadka powód jego lata",
"fijołkowe skłonił oczyma ciekawymi po kryjomu kazał stoły z Paryża a czuł choroby",
"do dworu uprawne dobrze zachowana sklepienie całe wesoło, lecz w rozmowę lecz lekki.",
"ażeby nie było gorąca). wachlarz pozłocist powiewając rozlewał deszcz iskier rzęsisty. Głowa do",
"matki pod Turka czy wstydzić, czy na lewo, on rodaków zbiera się w",
"@fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns the dictionary for comparison in tests\"\"\" return { \"_shards\":",
"przyciągnąć do dworu uprawne dobrze zachowana sklepienie całe wesoło, lecz w rozmowę lecz",
"[\"<em>Test</em> elasticsearch\"] }, }, { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"2\", \"_score\": \"12.0\",",
"iż ludzie są architektury. Choć Sędzia jego bok usiadła owa piękność zda się",
"the dictionary for comparison in tests\"\"\" return { \"_shards\": { \"failed\": 0, \"successful\":",
"ludzie są architektury. Choć Sędzia jego bok usiadła owa piękność zda się Gorecki,",
"rodziców i jeszcze dobrze na kozłach niemczysko chude na Ojczyzny łono. Tymczasem na",
"wojna u nas starych więcej godni Wojewody względów doszli potem się teraz wzrostem",
"\"_score\": \"10.114\", \"_source\": { \"title\": \"Test elasticsearch\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty",
"lata wleką w kota się nagle, stronnicy Sokół na kształt deski. Nogi miał",
"i Asesor, razem, jakoby zlewa. I też co się przyciągnąć do dworu uprawne",
"łono. Tymczasem na nim się zdawał małpą lub ławę przeskoczyć. Zręcznie między dwie",
"na kozłach niemczysko chude na Ojczyzny łono. Tymczasem na nim się zdawał małpą",
"pośmiewiska celem i niesrogi. Odgadnęła sąsiadka powód jego lata wleką w kota się",
"wstydzić, czy na lewo, on rodaków zbiera się w domu dostatek mieszka i",
"nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\",",
"\"Test elasticsearch numer 2\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie.",
"gorąca). wachlarz pozłocist powiewając rozlewał deszcz iskier rzęsisty. Głowa do Twych świątyń progi",
"comparison in tests\"\"\" return { \"_shards\": { \"failed\": 0, \"successful\": 10, \"total\": 10",
"Piękna byłaby sława, ażeby nie było gorąca). wachlarz pozłocist powiewając rozlewał deszcz iskier",
"client\"\"\" client = MagicMock() client.search.return_value = dummy_response add_connection(\"mock\", client) yield client @fixture(name=\"dummy_response\") def",
"import add_connection @fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\" client = MagicMock() client.search.return_value",
"domu dostatek mieszka i panien nie w nieczynności! a Suwarów w posiadłość. \"\"\",",
"@fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\" client = MagicMock() client.search.return_value = dummy_response",
"\"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch\"] }, }, { \"_index\": \"blog\", \"_type\":",
"krzaki fijołkowe skłonił oczyma ciekawymi po kryjomu kazał stoły z Paryża a czuł",
"na nim ją w ulicę się tajemnie, Ścigany od płaczącej matki pod Turka",
"rozlewał deszcz iskier rzęsisty. Głowa do Twych świątyń progi iść za zającami nie",
"się zdawał małpą lub ławę przeskoczyć. Zręcznie między dwie strony: Uciszcie się! woła.",
"Pac i opisuję, bo tak nas reformować cywilizować będzie wojna u nas starych",
"zdrowie. Ile cię stracił. Dziś człowieka nie policzę. Opuszczali rodziców i jeszcze dobrze",
"jesteś jak zdrowie. Ile cię stracił. Dziś człowieka nie policzę. Opuszczali rodziców i",
"Uciszcie się! woła. Marząc i krwi tonęła, gdy przysięgał na krzaki fijołkowe skłonił",
"w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\":",
"def mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\" client = MagicMock() client.search.return_value = dummy_response add_connection(\"mock\",",
"ławę przeskoczyć. Zręcznie między dwie strony: Uciszcie się! woła. Marząc i krwi tonęła,",
"w domu dostatek mieszka i panien nie w nieczynności! a Suwarów w posiadłość.",
"\"\"\"Returns the dictionary for comparison in tests\"\"\" return { \"_shards\": { \"failed\": 0,",
"mock client\"\"\" client = MagicMock() client.search.return_value = dummy_response add_connection(\"mock\", client) yield client @fixture(name=\"dummy_response\")",
"nim ją w ulicę się tajemnie, Ścigany od płaczącej matki pod Turka czy",
"in tests\"\"\" return { \"_shards\": { \"failed\": 0, \"successful\": 10, \"total\": 10 },",
"i jeszcze dobrze na kozłach niemczysko chude na Ojczyzny łono. Tymczasem na nim",
"progi iść za zającami nie został pośmiewiska celem i niesrogi. Odgadnęła sąsiadka powód",
"add_connection(\"mock\", client) yield client @fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns the dictionary for comparison in",
"dobrze zachowana sklepienie całe wesoło, lecz w rozmowę lecz lekki. odgadniesz, że jacyś",
"10, \"total\": 10 }, \"hits\": { \"hits\": [ { \"_index\": \"blog\", \"_type\": \"_doc\",",
"u nas starych więcej godni Wojewody względów doszli potem się teraz wzrostem dorodniejsza",
"Ty jesteś jak zdrowie. Ile cię stracił. Dziś człowieka nie policzę. Opuszczali rodziców",
"Odgadnęła sąsiadka powód jego lata wleką w kota się nagle, stronnicy Sokół na",
"dworu uprawne dobrze zachowana sklepienie całe wesoło, lecz w rozmowę lecz lekki. odgadniesz,",
"w posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": {",
"na waszych polowaniach łowił? Piękna byłaby sława, ażeby nie było gorąca). wachlarz pozłocist",
"Sokół na kształt deski. Nogi miał głos miły: Witaj nam, że spod ramion",
"świątyń progi iść za zającami nie został pośmiewiska celem i niesrogi. Odgadnęła sąsiadka",
"są architektury. Choć Sędzia jego bok usiadła owa piękność zda się Gorecki, Pac",
"Marząc i krwi tonęła, gdy przysięgał na krzaki fijołkowe skłonił oczyma ciekawymi po",
"zającami nie został pośmiewiska celem i niesrogi. Odgadnęła sąsiadka powód jego lata wleką",
"return { \"_shards\": { \"failed\": 0, \"successful\": 10, \"total\": 10 }, \"hits\": {",
"zda się Gorecki, Pac i opisuję, bo tak nas reformować cywilizować będzie wojna",
"Nogi miał głos miły: Witaj nam, że spod ramion wytknął palce i Asesor,",
"tajemnie, Ścigany od płaczącej matki pod Turka czy wstydzić, czy na lewo, on",
"dwie strony: Uciszcie się! woła. Marząc i krwi tonęła, gdy przysięgał na krzaki",
"\"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em>",
"uprawne dobrze zachowana sklepienie całe wesoło, lecz w rozmowę lecz lekki. odgadniesz, że",
"Ojczyzno moja! Ty jesteś jak zdrowie. Ile cię stracił. Dziś człowieka nie policzę.",
"cię stracił. Dziś człowieka nie policzę. Opuszczali rodziców i jeszcze dobrze na kozłach",
"w rozmowę lecz lekki. odgadniesz, że jacyś Francuzi wymowny zrobili wynalazek: iż ludzie",
"{ \"title\": [\"<em>Test</em> elasticsearch\"] }, }, { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"2\",",
"policzę. Opuszczali rodziców i jeszcze dobrze na kozłach niemczysko chude na Ojczyzny łono.",
"\"title\": [\"<em>Test</em> elasticsearch\"] }, }, { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"2\", \"_score\":",
"reformować cywilizować będzie wojna u nas starych więcej godni Wojewody względów doszli potem",
"10 }, \"hits\": { \"hits\": [ { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"1\",",
"deski. Nogi miał głos miły: Witaj nam, że spod ramion wytknął palce i",
"posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\":",
"\"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch numer 2\"] }, },",
"sklepienie całe wesoło, lecz w rozmowę lecz lekki. odgadniesz, że jacyś Francuzi wymowny",
"jak zdrowie. Ile cię stracił. Dziś człowieka nie policzę. Opuszczali rodziców i jeszcze",
"i panien nie w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\":",
"numer 2\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie. Ile cię",
"doszli potem się teraz wzrostem dorodniejsza bo tak pan Wojski na nim ją",
"dostatek mieszka i panien nie w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\":",
"woła. Marząc i krwi tonęła, gdy przysięgał na krzaki fijołkowe skłonił oczyma ciekawymi",
"starych więcej godni Wojewody względów doszli potem się teraz wzrostem dorodniejsza bo tak",
"czuł choroby zaród. Krzyczano na waszych polowaniach łowił? Piękna byłaby sława, ażeby nie",
"się w domu dostatek mieszka i panien nie w nieczynności! a Suwarów w",
"polowaniach łowił? Piękna byłaby sława, ażeby nie było gorąca). wachlarz pozłocist powiewając rozlewał",
"Opuszczali rodziców i jeszcze dobrze na kozłach niemczysko chude na Ojczyzny łono. Tymczasem",
"wytknął palce i Asesor, razem, jakoby zlewa. I też co się przyciągnąć do",
"zrobili wynalazek: iż ludzie są architektury. Choć Sędzia jego bok usiadła owa piękność",
"godni Wojewody względów doszli potem się teraz wzrostem dorodniejsza bo tak pan Wojski",
"się teraz wzrostem dorodniejsza bo tak pan Wojski na nim ją w ulicę",
"na lewo, on rodaków zbiera się w domu dostatek mieszka i panien nie",
"Paryża a czuł choroby zaród. Krzyczano na waszych polowaniach łowił? Piękna byłaby sława,",
"tonęła, gdy przysięgał na krzaki fijołkowe skłonił oczyma ciekawymi po kryjomu kazał stoły",
"i krwi tonęła, gdy przysięgał na krzaki fijołkowe skłonił oczyma ciekawymi po kryjomu",
"\"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"2\", \"_score\": \"12.0\", \"_source\": { \"title\": \"Test elasticsearch",
"Turka czy wstydzić, czy na lewo, on rodaków zbiera się w domu dostatek",
"Ścigany od płaczącej matki pod Turka czy wstydzić, czy na lewo, on rodaków",
"że spod ramion wytknął palce i Asesor, razem, jakoby zlewa. I też co",
"\"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch\"] }, }, { \"_index\":",
"mieszka i panien nie w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\",",
"w ulicę się tajemnie, Ścigany od płaczącej matki pod Turka czy wstydzić, czy",
"czy na lewo, on rodaków zbiera się w domu dostatek mieszka i panien",
"0, \"successful\": 10, \"total\": 10 }, \"hits\": { \"hits\": [ { \"_index\": \"blog\",",
"[\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch\"] }, }, {",
"lecz lekki. odgadniesz, że jacyś Francuzi wymowny zrobili wynalazek: iż ludzie są architektury.",
"\"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em>",
"i panien nie w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\":",
"}, }, { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"2\", \"_score\": \"12.0\", \"_source\": {",
"sława, ażeby nie było gorąca). wachlarz pozłocist powiewając rozlewał deszcz iskier rzęsisty. Głowa",
"stracił. Dziś człowieka nie policzę. Opuszczali rodziców i jeszcze dobrze na kozłach niemczysko",
"człowieka nie policzę. Opuszczali rodziców i jeszcze dobrze na kozłach niemczysko chude na",
"owa piękność zda się Gorecki, Pac i opisuję, bo tak nas reformować cywilizować",
"Wojski na nim ją w ulicę się tajemnie, Ścigany od płaczącej matki pod",
"\"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch numer",
"krwi tonęła, gdy przysięgał na krzaki fijołkowe skłonił oczyma ciekawymi po kryjomu kazał",
"architektury. Choć Sędzia jego bok usiadła owa piękność zda się Gorecki, Pac i",
"sąsiadka powód jego lata wleką w kota się nagle, stronnicy Sokół na kształt",
"nie został pośmiewiska celem i niesrogi. Odgadnęła sąsiadka powód jego lata wleką w",
"panien nie w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\",",
"oczyma ciekawymi po kryjomu kazał stoły z Paryża a czuł choroby zaród. Krzyczano",
"MagicMock() client.search.return_value = dummy_response add_connection(\"mock\", client) yield client @fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns the",
"pozłocist powiewając rozlewał deszcz iskier rzęsisty. Głowa do Twych świątyń progi iść za",
"[\"<em>Test</em> elasticsearch numer 2\"] }, }, ] }, \"timed_out\": False, \"took\": 123, }",
"i niesrogi. Odgadnęła sąsiadka powód jego lata wleką w kota się nagle, stronnicy",
"co się przyciągnąć do dworu uprawne dobrze zachowana sklepienie całe wesoło, lecz w",
"na nim się zdawał małpą lub ławę przeskoczyć. Zręcznie między dwie strony: Uciszcie",
"}, { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"2\", \"_score\": \"12.0\", \"_source\": { \"title\":",
"Ojczyzny łono. Tymczasem na nim się zdawał małpą lub ławę przeskoczyć. Zręcznie między",
"\"hits\": [ { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"1\", \"_score\": \"10.114\", \"_source\": {",
"lewo, on rodaków zbiera się w domu dostatek mieszka i panien nie w",
"lub ławę przeskoczyć. Zręcznie między dwie strony: Uciszcie się! woła. Marząc i krwi",
"\"1\", \"_score\": \"10.114\", \"_source\": { \"title\": \"Test elasticsearch\", \"body\": \"\"\" Litwo! Ojczyzno moja!",
"posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\":",
"więcej godni Wojewody względów doszli potem się teraz wzrostem dorodniejsza bo tak pan",
"on rodaków zbiera się w domu dostatek mieszka i panien nie w nieczynności!",
"nie policzę. Opuszczali rodziców i jeszcze dobrze na kozłach niemczysko chude na Ojczyzny",
"bo tak nas reformować cywilizować będzie wojna u nas starych więcej godni Wojewody",
"teraz wzrostem dorodniejsza bo tak pan Wojski na nim ją w ulicę się",
"dictionary for comparison in tests\"\"\" return { \"_shards\": { \"failed\": 0, \"successful\": 10,",
"niesrogi. Odgadnęła sąsiadka powód jego lata wleką w kota się nagle, stronnicy Sokół",
"elasticsearch mock client\"\"\" client = MagicMock() client.search.return_value = dummy_response add_connection(\"mock\", client) yield client",
"Wojewody względów doszli potem się teraz wzrostem dorodniejsza bo tak pan Wojski na",
"\"hits\": { \"hits\": [ { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"1\", \"_score\": \"10.114\",",
"będzie wojna u nas starych więcej godni Wojewody względów doszli potem się teraz",
"import MagicMock from pytest import fixture from elasticsearch_dsl.connections import add_connection @fixture def mock_client(dummy_response):",
"przysięgał na krzaki fijołkowe skłonił oczyma ciekawymi po kryjomu kazał stoły z Paryża",
"\"\"\"Basic test configuration\"\"\" from unittest.mock import MagicMock from pytest import fixture from elasticsearch_dsl.connections",
"\"2\", \"_score\": \"12.0\", \"_source\": { \"title\": \"Test elasticsearch numer 2\", \"body\": \"\"\" Litwo!",
"{ \"hits\": [ { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"1\", \"_score\": \"10.114\", \"_source\":",
"usiadła owa piękność zda się Gorecki, Pac i opisuję, bo tak nas reformować",
"\"title\": [\"<em>Test</em> elasticsearch numer 2\"] }, }, ] }, \"timed_out\": False, \"took\": 123,",
"configuration\"\"\" from unittest.mock import MagicMock from pytest import fixture from elasticsearch_dsl.connections import add_connection",
"wesoło, lecz w rozmowę lecz lekki. odgadniesz, że jacyś Francuzi wymowny zrobili wynalazek:",
"}, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch\"] }, }, { \"_index\": \"blog\", \"_type\": \"_doc\",",
"z Paryża a czuł choroby zaród. Krzyczano na waszych polowaniach łowił? Piękna byłaby",
"test configuration\"\"\" from unittest.mock import MagicMock from pytest import fixture from elasticsearch_dsl.connections import",
"}, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch numer 2\"] }, }, ] }, \"timed_out\":",
"zachowana sklepienie całe wesoło, lecz w rozmowę lecz lekki. odgadniesz, że jacyś Francuzi",
"\"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch",
"iść za zającami nie został pośmiewiska celem i niesrogi. Odgadnęła sąsiadka powód jego",
"skłonił oczyma ciekawymi po kryjomu kazał stoły z Paryża a czuł choroby zaród.",
"Głowa do Twych świątyń progi iść za zającami nie został pośmiewiska celem i",
"\"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie. Ile cię stracił. Dziś człowieka",
"gdy przysięgał na krzaki fijołkowe skłonił oczyma ciekawymi po kryjomu kazał stoły z",
"elasticsearch\"] }, }, { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"2\", \"_score\": \"12.0\", \"_source\":",
"łowił? Piękna byłaby sława, ażeby nie było gorąca). wachlarz pozłocist powiewając rozlewał deszcz",
"\"failed\": 0, \"successful\": 10, \"total\": 10 }, \"hits\": { \"hits\": [ { \"_index\":",
"\"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch\"] }, },",
"MagicMock from pytest import fixture from elasticsearch_dsl.connections import add_connection @fixture def mock_client(dummy_response): \"\"\"Returns",
"całe wesoło, lecz w rozmowę lecz lekki. odgadniesz, że jacyś Francuzi wymowny zrobili",
"dobrze na kozłach niemczysko chude na Ojczyzny łono. Tymczasem na nim się zdawał",
"{ \"title\": \"Test elasticsearch\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie.",
"\"highlight\": { \"title\": [\"<em>Test</em> elasticsearch numer 2\"] }, }, ] }, \"timed_out\": False,",
"w kota się nagle, stronnicy Sokół na kształt deski. Nogi miał głos miły:",
"}, \"hits\": { \"hits\": [ { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"1\", \"_score\":",
"ramion wytknął palce i Asesor, razem, jakoby zlewa. I też co się przyciągnąć",
"nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\",",
"{ \"_shards\": { \"failed\": 0, \"successful\": 10, \"total\": 10 }, \"hits\": { \"hits\":",
"pod Turka czy wstydzić, czy na lewo, on rodaków zbiera się w domu",
"\"_source\": { \"title\": \"Test elasticsearch numer 2\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty",
"głos miły: Witaj nam, że spod ramion wytknął palce i Asesor, razem, jakoby",
"\"\"\"Returns elasticsearch mock client\"\"\" client = MagicMock() client.search.return_value = dummy_response add_connection(\"mock\", client) yield",
"[ { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"1\", \"_score\": \"10.114\", \"_source\": { \"title\":",
"bok usiadła owa piękność zda się Gorecki, Pac i opisuję, bo tak nas",
"\"_type\": \"_doc\", \"_id\": \"2\", \"_score\": \"12.0\", \"_source\": { \"title\": \"Test elasticsearch numer 2\",",
"stronnicy Sokół na kształt deski. Nogi miał głos miły: Witaj nam, że spod",
"tak pan Wojski na nim ją w ulicę się tajemnie, Ścigany od płaczącej",
"nam, że spod ramion wytknął palce i Asesor, razem, jakoby zlewa. I też",
"\"highlight\": { \"title\": [\"<em>Test</em> elasticsearch\"] }, }, { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\":",
"jego lata wleką w kota się nagle, stronnicy Sokół na kształt deski. Nogi",
"rzęsisty. Głowa do Twych świątyń progi iść za zającami nie został pośmiewiska celem",
"i opisuję, bo tak nas reformować cywilizować będzie wojna u nas starych więcej",
"Litwo! Ojczyzno moja! Ty jesteś jak zdrowie. Ile cię stracił. Dziś człowieka nie",
"wymowny zrobili wynalazek: iż ludzie są architektury. Choć Sędzia jego bok usiadła owa",
"strony: Uciszcie się! woła. Marząc i krwi tonęła, gdy przysięgał na krzaki fijołkowe",
"że jacyś Francuzi wymowny zrobili wynalazek: iż ludzie są architektury. Choć Sędzia jego",
"się nagle, stronnicy Sokół na kształt deski. Nogi miał głos miły: Witaj nam,",
"spod ramion wytknął palce i Asesor, razem, jakoby zlewa. I też co się",
"na Ojczyzny łono. Tymczasem na nim się zdawał małpą lub ławę przeskoczyć. Zręcznie",
"do Twych świątyń progi iść za zającami nie został pośmiewiska celem i niesrogi.",
"nie w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"],",
"\"total\": 10 }, \"hits\": { \"hits\": [ { \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\":",
"dummy_response add_connection(\"mock\", client) yield client @fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns the dictionary for comparison",
"odgadniesz, że jacyś Francuzi wymowny zrobili wynalazek: iż ludzie są architektury. Choć Sędzia",
"{ \"title\": \"Test elasticsearch numer 2\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś",
"Suwarów w posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\":",
"potem się teraz wzrostem dorodniejsza bo tak pan Wojski na nim ją w",
"unittest.mock import MagicMock from pytest import fixture from elasticsearch_dsl.connections import add_connection @fixture def",
"tak nas reformować cywilizować będzie wojna u nas starych więcej godni Wojewody względów",
"stoły z Paryża a czuł choroby zaród. Krzyczano na waszych polowaniach łowił? Piękna",
"nagle, stronnicy Sokół na kształt deski. Nogi miał głos miły: Witaj nam, że",
"[\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch numer 2\"] },",
"się tajemnie, Ścigany od płaczącej matki pod Turka czy wstydzić, czy na lewo,",
"panien nie w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\",",
"powód jego lata wleką w kota się nagle, stronnicy Sokół na kształt deski.",
"\"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch numer 2\"] }, }, ]",
"\"_source\": { \"title\": \"Test elasticsearch\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak",
"na krzaki fijołkowe skłonił oczyma ciekawymi po kryjomu kazał stoły z Paryża a",
"{ \"_index\": \"blog\", \"_type\": \"_doc\", \"_id\": \"2\", \"_score\": \"12.0\", \"_source\": { \"title\": \"Test",
"moja! Ty jesteś jak zdrowie. Ile cię stracił. Dziś człowieka nie policzę. Opuszczali",
"się! woła. Marząc i krwi tonęła, gdy przysięgał na krzaki fijołkowe skłonił oczyma",
"choroby zaród. Krzyczano na waszych polowaniach łowił? Piękna byłaby sława, ażeby nie było",
"zlewa. I też co się przyciągnąć do dworu uprawne dobrze zachowana sklepienie całe",
"I też co się przyciągnąć do dworu uprawne dobrze zachowana sklepienie całe wesoło,",
"piękność zda się Gorecki, Pac i opisuję, bo tak nas reformować cywilizować będzie",
"from elasticsearch_dsl.connections import add_connection @fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\" client =",
"= MagicMock() client.search.return_value = dummy_response add_connection(\"mock\", client) yield client @fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns",
"palce i Asesor, razem, jakoby zlewa. I też co się przyciągnąć do dworu",
"się przyciągnąć do dworu uprawne dobrze zachowana sklepienie całe wesoło, lecz w rozmowę",
"Sędzia jego bok usiadła owa piękność zda się Gorecki, Pac i opisuję, bo",
"kształt deski. Nogi miał głos miły: Witaj nam, że spod ramion wytknął palce",
"bo tak pan Wojski na nim ją w ulicę się tajemnie, Ścigany od",
"lecz w rozmowę lecz lekki. odgadniesz, że jacyś Francuzi wymowny zrobili wynalazek: iż",
"\"_doc\", \"_id\": \"2\", \"_score\": \"12.0\", \"_source\": { \"title\": \"Test elasticsearch numer 2\", \"body\":",
"został pośmiewiska celem i niesrogi. Odgadnęła sąsiadka powód jego lata wleką w kota",
"\"_shards\": { \"failed\": 0, \"successful\": 10, \"total\": 10 }, \"hits\": { \"hits\": [",
"from unittest.mock import MagicMock from pytest import fixture from elasticsearch_dsl.connections import add_connection @fixture",
"kozłach niemczysko chude na Ojczyzny łono. Tymczasem na nim się zdawał małpą lub",
"jacyś Francuzi wymowny zrobili wynalazek: iż ludzie są architektury. Choć Sędzia jego bok",
"na kształt deski. Nogi miał głos miły: Witaj nam, że spod ramion wytknął",
"małpą lub ławę przeskoczyć. Zręcznie między dwie strony: Uciszcie się! woła. Marząc i",
"for comparison in tests\"\"\" return { \"_shards\": { \"failed\": 0, \"successful\": 10, \"total\":",
"wleką w kota się nagle, stronnicy Sokół na kształt deski. Nogi miał głos",
"Tymczasem na nim się zdawał małpą lub ławę przeskoczyć. Zręcznie między dwie strony:",
"\"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie. Ile cię stracił. Dziś",
"powiewając rozlewał deszcz iskier rzęsisty. Głowa do Twych świątyń progi iść za zającami",
"się Gorecki, Pac i opisuję, bo tak nas reformować cywilizować będzie wojna u",
"opisuję, bo tak nas reformować cywilizować będzie wojna u nas starych więcej godni",
"client.search.return_value = dummy_response add_connection(\"mock\", client) yield client @fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns the dictionary",
"od płaczącej matki pod Turka czy wstydzić, czy na lewo, on rodaków zbiera",
"nie było gorąca). wachlarz pozłocist powiewając rozlewał deszcz iskier rzęsisty. Głowa do Twych",
"nie w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"],",
"add_connection @fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch mock client\"\"\" client = MagicMock() client.search.return_value =",
"cywilizować będzie wojna u nas starych więcej godni Wojewody względów doszli potem się",
"waszych polowaniach łowił? Piękna byłaby sława, ażeby nie było gorąca). wachlarz pozłocist powiewając",
"jakoby zlewa. I też co się przyciągnąć do dworu uprawne dobrze zachowana sklepienie",
"\"_doc\", \"_id\": \"1\", \"_score\": \"10.114\", \"_source\": { \"title\": \"Test elasticsearch\", \"body\": \"\"\" Litwo!",
"kota się nagle, stronnicy Sokół na kształt deski. Nogi miał głos miły: Witaj",
"razem, jakoby zlewa. I też co się przyciągnąć do dworu uprawne dobrze zachowana",
"\"_score\": \"12.0\", \"_source\": { \"title\": \"Test elasticsearch numer 2\", \"body\": \"\"\" Litwo! Ojczyzno",
"jego bok usiadła owa piękność zda się Gorecki, Pac i opisuję, bo tak",
"nas starych więcej godni Wojewody względów doszli potem się teraz wzrostem dorodniejsza bo",
"czy wstydzić, czy na lewo, on rodaków zbiera się w domu dostatek mieszka",
"było gorąca). wachlarz pozłocist powiewając rozlewał deszcz iskier rzęsisty. Głowa do Twych świątyń",
"lekki. odgadniesz, że jacyś Francuzi wymowny zrobili wynalazek: iż ludzie są architektury. Choć",
"niemczysko chude na Ojczyzny łono. Tymczasem na nim się zdawał małpą lub ławę",
"def fixture_dummy_response(): \"\"\"Returns the dictionary for comparison in tests\"\"\" return { \"_shards\": {",
"a Suwarów w posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", },",
"a Suwarów w posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", },",
"pytest import fixture from elasticsearch_dsl.connections import add_connection @fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch mock",
"\"Test elasticsearch\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie. Ile cię",
"pan Wojski na nim ją w ulicę się tajemnie, Ścigany od płaczącej matki",
"mieszka i panien nie w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2014-02-10T10:31:07.851688\",",
"\"title\": \"Test elasticsearch\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie. Ile",
"Suwarów w posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\":",
"2\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie. Ile cię stracił.",
"\"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch numer 2\"]",
"elasticsearch\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie. Ile cię stracił.",
"nim się zdawał małpą lub ławę przeskoczyć. Zręcznie między dwie strony: Uciszcie się!",
"po kryjomu kazał stoły z Paryża a czuł choroby zaród. Krzyczano na waszych",
"\"_id\": \"1\", \"_score\": \"10.114\", \"_source\": { \"title\": \"Test elasticsearch\", \"body\": \"\"\" Litwo! Ojczyzno",
"tests\"\"\" return { \"_shards\": { \"failed\": 0, \"successful\": 10, \"total\": 10 }, \"hits\":",
"Witaj nam, że spod ramion wytknął palce i Asesor, razem, jakoby zlewa. I",
"celem i niesrogi. Odgadnęła sąsiadka powód jego lata wleką w kota się nagle,",
"przeskoczyć. Zręcznie między dwie strony: Uciszcie się! woła. Marząc i krwi tonęła, gdy",
"from pytest import fixture from elasticsearch_dsl.connections import add_connection @fixture def mock_client(dummy_response): \"\"\"Returns elasticsearch",
"elasticsearch numer 2\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak zdrowie. Ile",
"kazał stoły z Paryża a czuł choroby zaród. Krzyczano na waszych polowaniach łowił?",
"nas reformować cywilizować będzie wojna u nas starych więcej godni Wojewody względów doszli",
"Ile cię stracił. Dziś człowieka nie policzę. Opuszczali rodziców i jeszcze dobrze na",
"Choć Sędzia jego bok usiadła owa piękność zda się Gorecki, Pac i opisuję,",
"{ \"title\": [\"<em>Test</em> elasticsearch numer 2\"] }, }, ] }, \"timed_out\": False, \"took\":",
"{ \"failed\": 0, \"successful\": 10, \"total\": 10 }, \"hits\": { \"hits\": [ {",
"chude na Ojczyzny łono. Tymczasem na nim się zdawał małpą lub ławę przeskoczyć.",
"\"12.0\", \"_source\": { \"title\": \"Test elasticsearch numer 2\", \"body\": \"\"\" Litwo! Ojczyzno moja!",
"= dummy_response add_connection(\"mock\", client) yield client @fixture(name=\"dummy_response\") def fixture_dummy_response(): \"\"\"Returns the dictionary for",
"\"successful\": 10, \"total\": 10 }, \"hits\": { \"hits\": [ { \"_index\": \"blog\", \"_type\":",
"Asesor, razem, jakoby zlewa. I też co się przyciągnąć do dworu uprawne dobrze",
"Twych świątyń progi iść za zającami nie został pośmiewiska celem i niesrogi. Odgadnęła",
"w nieczynności! a Suwarów w posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\":",
"\"blog\", \"_type\": \"_doc\", \"_id\": \"2\", \"_score\": \"12.0\", \"_source\": { \"title\": \"Test elasticsearch numer",
"client = MagicMock() client.search.return_value = dummy_response add_connection(\"mock\", client) yield client @fixture(name=\"dummy_response\") def fixture_dummy_response():",
"Dziś człowieka nie policzę. Opuszczali rodziców i jeszcze dobrze na kozłach niemczysko chude",
"a czuł choroby zaród. Krzyczano na waszych polowaniach łowił? Piękna byłaby sława, ażeby",
"rodaków zbiera się w domu dostatek mieszka i panien nie w nieczynności! a",
"\"1\", }, \"highlight\": { \"title\": [\"<em>Test</em> elasticsearch numer 2\"] }, }, ] },",
"zdawał małpą lub ławę przeskoczyć. Zręcznie między dwie strony: Uciszcie się! woła. Marząc",
"Gorecki, Pac i opisuję, bo tak nas reformować cywilizować będzie wojna u nas",
"\"title\": \"Test elasticsearch numer 2\", \"body\": \"\"\" Litwo! Ojczyzno moja! Ty jesteś jak",
"w posiadłość. \"\"\", \"published_from\": \"2013-02-10T10:31:07.851688\", \"tags\": [\"g1\", \"g2\"], \"lines\": \"1\", }, \"highlight\": {",
"ciekawymi po kryjomu kazał stoły z Paryża a czuł choroby zaród. Krzyczano na"
] |
[
"here char_line = 0 char = {} elif char_line == 1: char['font'] =",
"parse_font_dat(self): self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string = '' char_line = 9999",
"self.parse_font_dat() return self._string def parse_font_dat(self): self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string =",
"if not italic: string += '<i>' italic = True else: if italic: string",
"self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string = '' char_line = 9999 char",
"'</i>' italic = False elif char_line == 2: char['char'] = stripped string +=",
"string += '\\r\\n' if italic: string += '</i>' except IOError: print 'Could not",
"== 1: char['font'] = stripped if not char['font'] in self._fonts: self._fonts.append(char['font']) if \"italic\"",
"10 floats # Todo: Insert detection of slanted text here char_line = 0",
"double line break break string += '\\r\\n' if italic: string += '</i>' except",
"9999 char = {} italic = False try: for line in open(self.path): stripped",
"char['char'] = stripped string += stripped elif char_line < 9999 and re.match('^'+' '.join([float_pattern]",
"on double line break break string += '\\r\\n' if italic: string += '</i>'",
"float_pattern = '[+-]?[0-9]+\\.[0-9]+' string = '' char_line = 9999 char = {} italic",
"italic = False try: for line in open(self.path): stripped = line.strip('\\n\\r') char_line +=",
"= {} elif char_line == 1: char['font'] = stripped if not char['font'] in",
"elif char_line == 1: char['font'] = stripped if not char['font'] in self._fonts: self._fonts.append(char['font'])",
"= stripped if not char['font'] in self._fonts: self._fonts.append(char['font']) if \"italic\" in stripped.lower() or",
"path self._fonts = False self._string = False def __str__(self): return self.name def __repr__(self):",
"# New line: 4 floats if string.endswith('\\r\\n'): # Break on double line break",
"elif char_line < 9999 and re.match('^'+' '.join([float_pattern] * 4)+'$', stripped): # New line:",
"New line: 4 floats if string.endswith('\\r\\n'): # Break on double line break break",
"= False def __str__(self): return self.name def __repr__(self): return self.name @property def fonts(self):",
"string += '<i>' italic = True else: if italic: string += '</i>' italic",
"stripped string += stripped elif char_line < 9999 and re.match('^'+' '.join([float_pattern] * 4)+'$',",
"New character: 10 floats # Todo: Insert detection of slanted text here char_line",
"'[+-]?[0-9]+\\.[0-9]+' string = '' char_line = 9999 char = {} italic = False",
"'.join([float_pattern] * 4)+'$', stripped): # New line: 4 floats if string.endswith('\\r\\n'): # Break",
"< 9999 and re.match('^'+' '.join([float_pattern] * 4)+'$', stripped): # New line: 4 floats",
"\"oblique\" in stripped.lower(): if not italic: string += '<i>' italic = True else:",
"italic: string += '</i>' italic = False elif char_line == 2: char['char'] =",
"+= '</i>' italic = False elif char_line == 2: char['char'] = stripped string",
"if italic: string += '</i>' except IOError: print 'Could not read file: %s'",
"Todo: Insert detection of slanted text here char_line = 0 char = {}",
"def __repr__(self): return self.name @property def fonts(self): if not self._fonts: self.parse_font_dat() return self._fonts",
"# Todo: Insert detection of slanted text here char_line = 0 char =",
"self._string: self.parse_font_dat() return self._string def parse_font_dat(self): self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string",
"char_line = 9999 char = {} italic = False try: for line in",
"stripped = line.strip('\\n\\r') char_line += 1 if re.match('^'+' '.join([float_pattern] * 10)+'$', stripped): #",
"= 0 char = {} elif char_line == 1: char['font'] = stripped if",
"import re class Title(object): def __init__(self, path): self.path = path self._fonts = False",
"in self._fonts: self._fonts.append(char['font']) if \"italic\" in stripped.lower() or \"oblique\" in stripped.lower(): if not",
"__repr__(self): return self.name @property def fonts(self): if not self._fonts: self.parse_font_dat() return self._fonts @property",
"string(self): if not self._string: self.parse_font_dat() return self._string def parse_font_dat(self): self._fonts = [] float_pattern",
"= '' char_line = 9999 char = {} italic = False try: for",
"False elif char_line == 2: char['char'] = stripped string += stripped elif char_line",
"= False try: for line in open(self.path): stripped = line.strip('\\n\\r') char_line += 1",
"string += stripped elif char_line < 9999 and re.match('^'+' '.join([float_pattern] * 4)+'$', stripped):",
"__init__(self, path): self.path = path self._fonts = False self._string = False def __str__(self):",
"self._fonts.append(char['font']) if \"italic\" in stripped.lower() or \"oblique\" in stripped.lower(): if not italic: string",
"self._string def parse_font_dat(self): self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string = '' char_line",
"if string.endswith('\\r\\n'): # Break on double line break break string += '\\r\\n' if",
"# Break on double line break break string += '\\r\\n' if italic: string",
"char_line += 1 if re.match('^'+' '.join([float_pattern] * 10)+'$', stripped): # New character: 10",
"for line in open(self.path): stripped = line.strip('\\n\\r') char_line += 1 if re.match('^'+' '.join([float_pattern]",
"= line.strip('\\n\\r') char_line += 1 if re.match('^'+' '.join([float_pattern] * 10)+'$', stripped): # New",
"self._string = False def __str__(self): return self.name def __repr__(self): return self.name @property def",
"re.match('^'+' '.join([float_pattern] * 4)+'$', stripped): # New line: 4 floats if string.endswith('\\r\\n'): #",
"* 10)+'$', stripped): # New character: 10 floats # Todo: Insert detection of",
"self.name def __repr__(self): return self.name @property def fonts(self): if not self._fonts: self.parse_font_dat() return",
"True else: if italic: string += '</i>' italic = False elif char_line ==",
"if italic: string += '</i>' italic = False elif char_line == 2: char['char']",
"elif char_line == 2: char['char'] = stripped string += stripped elif char_line <",
"not italic: string += '<i>' italic = True else: if italic: string +=",
"4 floats if string.endswith('\\r\\n'): # Break on double line break break string +=",
"else: if italic: string += '</i>' italic = False elif char_line == 2:",
"line: 4 floats if string.endswith('\\r\\n'): # Break on double line break break string",
"IOError: print 'Could not read file: %s' % self.path return self._string = string",
"2: char['char'] = stripped string += stripped elif char_line < 9999 and re.match('^'+'",
"def __str__(self): return self.name def __repr__(self): return self.name @property def fonts(self): if not",
"= path self._fonts = False self._string = False def __str__(self): return self.name def",
"return self.name @property def fonts(self): if not self._fonts: self.parse_font_dat() return self._fonts @property def",
"0 char = {} elif char_line == 1: char['font'] = stripped if not",
"4)+'$', stripped): # New line: 4 floats if string.endswith('\\r\\n'): # Break on double",
"'.join([float_pattern] * 10)+'$', stripped): # New character: 10 floats # Todo: Insert detection",
"if not char['font'] in self._fonts: self._fonts.append(char['font']) if \"italic\" in stripped.lower() or \"oblique\" in",
"string += '</i>' italic = False elif char_line == 2: char['char'] = stripped",
"@property def fonts(self): if not self._fonts: self.parse_font_dat() return self._fonts @property def string(self): if",
"self.path = path self._fonts = False self._string = False def __str__(self): return self.name",
"or \"oblique\" in stripped.lower(): if not italic: string += '<i>' italic = True",
"floats if string.endswith('\\r\\n'): # Break on double line break break string += '\\r\\n'",
"floats # Todo: Insert detection of slanted text here char_line = 0 char",
"stripped.lower() or \"oblique\" in stripped.lower(): if not italic: string += '<i>' italic =",
"'<i>' italic = True else: if italic: string += '</i>' italic = False",
"if re.match('^'+' '.join([float_pattern] * 10)+'$', stripped): # New character: 10 floats # Todo:",
"if \"italic\" in stripped.lower() or \"oblique\" in stripped.lower(): if not italic: string +=",
"slanted text here char_line = 0 char = {} elif char_line == 1:",
"= 9999 char = {} italic = False try: for line in open(self.path):",
"10)+'$', stripped): # New character: 10 floats # Todo: Insert detection of slanted",
"Insert detection of slanted text here char_line = 0 char = {} elif",
"string += '</i>' except IOError: print 'Could not read file: %s' % self.path",
"{} elif char_line == 1: char['font'] = stripped if not char['font'] in self._fonts:",
"in open(self.path): stripped = line.strip('\\n\\r') char_line += 1 if re.match('^'+' '.join([float_pattern] * 10)+'$',",
"False self._string = False def __str__(self): return self.name def __repr__(self): return self.name @property",
"italic = False elif char_line == 2: char['char'] = stripped string += stripped",
"def parse_font_dat(self): self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string = '' char_line =",
"False try: for line in open(self.path): stripped = line.strip('\\n\\r') char_line += 1 if",
"line in open(self.path): stripped = line.strip('\\n\\r') char_line += 1 if re.match('^'+' '.join([float_pattern] *",
"line.strip('\\n\\r') char_line += 1 if re.match('^'+' '.join([float_pattern] * 10)+'$', stripped): # New character:",
"text here char_line = 0 char = {} elif char_line == 1: char['font']",
"= stripped string += stripped elif char_line < 9999 and re.match('^'+' '.join([float_pattern] *",
"stripped if not char['font'] in self._fonts: self._fonts.append(char['font']) if \"italic\" in stripped.lower() or \"oblique\"",
"class Title(object): def __init__(self, path): self.path = path self._fonts = False self._string =",
"+= '</i>' except IOError: print 'Could not read file: %s' % self.path return",
"False def __str__(self): return self.name def __repr__(self): return self.name @property def fonts(self): if",
"+= stripped elif char_line < 9999 and re.match('^'+' '.join([float_pattern] * 4)+'$', stripped): #",
"stripped.lower(): if not italic: string += '<i>' italic = True else: if italic:",
"not char['font'] in self._fonts: self._fonts.append(char['font']) if \"italic\" in stripped.lower() or \"oblique\" in stripped.lower():",
"1 if re.match('^'+' '.join([float_pattern] * 10)+'$', stripped): # New character: 10 floats #",
"# New character: 10 floats # Todo: Insert detection of slanted text here",
"self._fonts = False self._string = False def __str__(self): return self.name def __repr__(self): return",
"def fonts(self): if not self._fonts: self.parse_font_dat() return self._fonts @property def string(self): if not",
"Break on double line break break string += '\\r\\n' if italic: string +=",
"path): self.path = path self._fonts = False self._string = False def __str__(self): return",
"italic: string += '</i>' except IOError: print 'Could not read file: %s' %",
"= [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string = '' char_line = 9999 char =",
"char_line < 9999 and re.match('^'+' '.join([float_pattern] * 4)+'$', stripped): # New line: 4",
"1: char['font'] = stripped if not char['font'] in self._fonts: self._fonts.append(char['font']) if \"italic\" in",
"and re.match('^'+' '.join([float_pattern] * 4)+'$', stripped): # New line: 4 floats if string.endswith('\\r\\n'):",
"break string += '\\r\\n' if italic: string += '</i>' except IOError: print 'Could",
"+= '<i>' italic = True else: if italic: string += '</i>' italic =",
"[] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string = '' char_line = 9999 char = {}",
"in stripped.lower(): if not italic: string += '<i>' italic = True else: if",
"open(self.path): stripped = line.strip('\\n\\r') char_line += 1 if re.match('^'+' '.join([float_pattern] * 10)+'$', stripped):",
"string.endswith('\\r\\n'): # Break on double line break break string += '\\r\\n' if italic:",
"= False elif char_line == 2: char['char'] = stripped string += stripped elif",
"self.name @property def fonts(self): if not self._fonts: self.parse_font_dat() return self._fonts @property def string(self):",
"string = '' char_line = 9999 char = {} italic = False try:",
"+= 1 if re.match('^'+' '.join([float_pattern] * 10)+'$', stripped): # New character: 10 floats",
"if not self._fonts: self.parse_font_dat() return self._fonts @property def string(self): if not self._string: self.parse_font_dat()",
"'' char_line = 9999 char = {} italic = False try: for line",
"char = {} elif char_line == 1: char['font'] = stripped if not char['font']",
"def string(self): if not self._string: self.parse_font_dat() return self._string def parse_font_dat(self): self._fonts = []",
"re class Title(object): def __init__(self, path): self.path = path self._fonts = False self._string",
"character: 10 floats # Todo: Insert detection of slanted text here char_line =",
"stripped elif char_line < 9999 and re.match('^'+' '.join([float_pattern] * 4)+'$', stripped): # New",
"char['font'] in self._fonts: self._fonts.append(char['font']) if \"italic\" in stripped.lower() or \"oblique\" in stripped.lower(): if",
"re.match('^'+' '.join([float_pattern] * 10)+'$', stripped): # New character: 10 floats # Todo: Insert",
"== 2: char['char'] = stripped string += stripped elif char_line < 9999 and",
"line break break string += '\\r\\n' if italic: string += '</i>' except IOError:",
"= {} italic = False try: for line in open(self.path): stripped = line.strip('\\n\\r')",
"char_line = 0 char = {} elif char_line == 1: char['font'] = stripped",
"italic: string += '<i>' italic = True else: if italic: string += '</i>'",
"stripped): # New line: 4 floats if string.endswith('\\r\\n'): # Break on double line",
"not self._fonts: self.parse_font_dat() return self._fonts @property def string(self): if not self._string: self.parse_font_dat() return",
"break break string += '\\r\\n' if italic: string += '</i>' except IOError: print",
"Title(object): def __init__(self, path): self.path = path self._fonts = False self._string = False",
"def __init__(self, path): self.path = path self._fonts = False self._string = False def",
"italic = True else: if italic: string += '</i>' italic = False elif",
"+= '\\r\\n' if italic: string += '</i>' except IOError: print 'Could not read",
"python import re class Title(object): def __init__(self, path): self.path = path self._fonts =",
"fonts(self): if not self._fonts: self.parse_font_dat() return self._fonts @property def string(self): if not self._string:",
"__str__(self): return self.name def __repr__(self): return self.name @property def fonts(self): if not self._fonts:",
"if not self._string: self.parse_font_dat() return self._string def parse_font_dat(self): self._fonts = [] float_pattern =",
"char['font'] = stripped if not char['font'] in self._fonts: self._fonts.append(char['font']) if \"italic\" in stripped.lower()",
"char_line == 1: char['font'] = stripped if not char['font'] in self._fonts: self._fonts.append(char['font']) if",
"except IOError: print 'Could not read file: %s' % self.path return self._string =",
"self._fonts: self.parse_font_dat() return self._fonts @property def string(self): if not self._string: self.parse_font_dat() return self._string",
"* 4)+'$', stripped): # New line: 4 floats if string.endswith('\\r\\n'): # Break on",
"@property def string(self): if not self._string: self.parse_font_dat() return self._string def parse_font_dat(self): self._fonts =",
"detection of slanted text here char_line = 0 char = {} elif char_line",
"= True else: if italic: string += '</i>' italic = False elif char_line",
"self._fonts: self._fonts.append(char['font']) if \"italic\" in stripped.lower() or \"oblique\" in stripped.lower(): if not italic:",
"return self.name def __repr__(self): return self.name @property def fonts(self): if not self._fonts: self.parse_font_dat()",
"char_line == 2: char['char'] = stripped string += stripped elif char_line < 9999",
"in stripped.lower() or \"oblique\" in stripped.lower(): if not italic: string += '<i>' italic",
"#!/usr/bin/env python import re class Title(object): def __init__(self, path): self.path = path self._fonts",
"self.parse_font_dat() return self._fonts @property def string(self): if not self._string: self.parse_font_dat() return self._string def",
"return self._fonts @property def string(self): if not self._string: self.parse_font_dat() return self._string def parse_font_dat(self):",
"char = {} italic = False try: for line in open(self.path): stripped =",
"try: for line in open(self.path): stripped = line.strip('\\n\\r') char_line += 1 if re.match('^'+'",
"= False self._string = False def __str__(self): return self.name def __repr__(self): return self.name",
"self._fonts @property def string(self): if not self._string: self.parse_font_dat() return self._string def parse_font_dat(self): self._fonts",
"\"italic\" in stripped.lower() or \"oblique\" in stripped.lower(): if not italic: string += '<i>'",
"{} italic = False try: for line in open(self.path): stripped = line.strip('\\n\\r') char_line",
"of slanted text here char_line = 0 char = {} elif char_line ==",
"= '[+-]?[0-9]+\\.[0-9]+' string = '' char_line = 9999 char = {} italic =",
"9999 and re.match('^'+' '.join([float_pattern] * 4)+'$', stripped): # New line: 4 floats if",
"return self._string def parse_font_dat(self): self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+' string = ''",
"'\\r\\n' if italic: string += '</i>' except IOError: print 'Could not read file:",
"'</i>' except IOError: print 'Could not read file: %s' % self.path return self._string",
"not self._string: self.parse_font_dat() return self._string def parse_font_dat(self): self._fonts = [] float_pattern = '[+-]?[0-9]+\\.[0-9]+'",
"stripped): # New character: 10 floats # Todo: Insert detection of slanted text"
] |
[
"build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using",
"with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\"",
"def fixtureToAbsolute(fixture_file): # where is _this_ file? thisScriptDir = os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__',",
"= fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out,",
"as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('Unknown field set', console_output)",
"# Classes # ------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def setUp(self): self.actual_file = fixtureToAbsolute('a.txt') self.positional =",
"self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file,",
"complaints.ccdb.choose_field_map as sut from common.tests import build_argv, captured_output, validate_files def fieldsToAbsolute(mapping_file): # where",
"fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print",
"self.actual_file = fixtureToAbsolute('a.txt') self.positional = [ None, self.actual_file ] def tearDown(self): try: os.remove(self.actual_file)",
"(out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping',",
"common.tests import build_argv, captured_output, validate_files def fieldsToAbsolute(mapping_file): # where is _this_ file? and",
"err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print)",
"fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'CSV' ] argv = build_argv(optional, self.positional) with captured_output(argv)",
"sut from common.tests import build_argv, captured_output, validate_files def fieldsToAbsolute(mapping_file): # where is _this_",
"= fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt'))",
"self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv =",
"with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('usage: choose_field_map',",
"import os import unittest import complaints.ccdb.choose_field_map as sut from common.tests import build_argv, captured_output,",
"TestMain(unittest.TestCase): def setUp(self): self.actual_file = fixtureToAbsolute('a.txt') self.positional = [ None, self.actual_file ] def",
"def tearDown(self): try: os.remove(self.actual_file) except Exception: pass def test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv",
"# where is _this_ file? thisScriptDir = os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__', fixture_file) #",
"= build_argv(optional, self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print =",
"<filename>complaints/ccdb/tests/test_choose_field_map.py import os import unittest import complaints.ccdb.choose_field_map as sut from common.tests import build_argv,",
"sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def",
"actual_print) def test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out,",
"field mapping', actual_print) def test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv)",
"Exception: pass def test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as",
"fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_v2_public(self): self.positional[0]",
"_this_ file? thisScriptDir = os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__', fixture_file) # ------------------------------------------------------------------------------ # Classes",
"mapping', actual_print) def test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as",
"self.actual_file ] def tearDown(self): try: os.remove(self.actual_file) except Exception: pass def test_v1_intake_json(self): self.positional[0] =",
"= fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt'))",
"argv = build_argv(positional=self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err): sut.main()",
"actual_print) def test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out,",
"field mapping', actual_print) def test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv)",
"2) console_output = err.getvalue() self.assertIn('Unknown field set', console_output) def test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv')",
"test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main()",
"self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2)",
"'tsv' ] argv = build_argv(optional, self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as",
"captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for",
"self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional =",
"self.positional = [ None, self.actual_file ] def tearDown(self): try: os.remove(self.actual_file) except Exception: pass",
"from common.tests import build_argv, captured_output, validate_files def fieldsToAbsolute(mapping_file): # where is _this_ file?",
"def setUp(self): self.actual_file = fixtureToAbsolute('a.txt') self.positional = [ None, self.actual_file ] def tearDown(self):",
"os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__', fixture_file) # ------------------------------------------------------------------------------ # Classes # ------------------------------------------------------------------------------ class TestMain(unittest.TestCase):",
"def fieldsToAbsolute(mapping_file): # where is _this_ file? and one level up thisScriptDir =",
"'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file): # where is _this_ file? thisScriptDir = os.path.dirname(__file__) return",
"actual_print) def test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out,",
"as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field",
"validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_v2_public(self):",
"field mapping', actual_print) def test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv)",
"level up thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file): # where",
"validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v1_intake_csv(self):",
"fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v1_intake_csv(self): self.positional[0]",
"test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main()",
"up thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file): # where is",
"actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_v2_public(self): self.positional[0] =",
"def test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional) with self.assertRaises(SystemExit) as ex: with",
"'__fixtures__', fixture_file) # ------------------------------------------------------------------------------ # Classes # ------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def setUp(self): self.actual_file",
"(out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('usage: choose_field_map', console_output) self.assertIn('--target-format: invalid",
"validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v2_intake(self):",
"is _this_ file? thisScriptDir = os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__', fixture_file) # ------------------------------------------------------------------------------ #",
"\"v1-json.txt\" for field mapping', actual_print) def test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [",
"------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def setUp(self): self.actual_file = fixtureToAbsolute('a.txt') self.positional = [ None, self.actual_file",
"thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file): # where is _this_",
"self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output =",
"fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'tsv' ] argv = build_argv(optional, self.positional) with self.assertRaises(SystemExit)",
"'--target-format', 'CSV' ] argv = build_argv(optional, self.positional) with captured_output(argv) as (out, err): sut.main()",
"actual_print) def test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'CSV' ] argv",
"mapping_file) def fixtureToAbsolute(fixture_file): # where is _this_ file? thisScriptDir = os.path.dirname(__file__) return os.path.join(thisScriptDir,",
"try: os.remove(self.actual_file) except Exception: pass def test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional)",
"\"v1-json.txt\" for field mapping', actual_print) def test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional)",
"= out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv')",
"def test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'tsv' ] argv =",
"optional = [ '--target-format', 'tsv' ] argv = build_argv(optional, self.positional) with self.assertRaises(SystemExit) as",
"out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional",
"None, self.actual_file ] def tearDown(self): try: os.remove(self.actual_file) except Exception: pass def test_v1_intake_json(self): self.positional[0]",
"for field mapping', actual_print) def test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional) with",
"(out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping',",
"def test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err):",
"captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for",
"\"v2-json.txt\" for field mapping', actual_print) def test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional)",
"os.path.join(thisScriptDir, '__fixtures__', fixture_file) # ------------------------------------------------------------------------------ # Classes # ------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def setUp(self):",
"# ------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def setUp(self): self.actual_file = fixtureToAbsolute('a.txt') self.positional = [ None,",
"= out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv')",
"] argv = build_argv(optional, self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt'))",
"test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'tsv' ] argv = build_argv(optional,",
"field set', console_output) def test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'tsv'",
"tearDown(self): try: os.remove(self.actual_file) except Exception: pass def test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv =",
"validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_bad_input(self):",
"'--target-format', 'tsv' ] argv = build_argv(optional, self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv)",
"except Exception: pass def test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv)",
"mapping', actual_print) def test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'CSV' ]",
"self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv') argv =",
"fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_bad_input(self): self.positional[0]",
"self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'tsv' ] argv = build_argv(optional, self.positional)",
"captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for",
"\"v2-json.txt\" for field mapping', actual_print) def test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional)",
"validate_files def fieldsToAbsolute(mapping_file): # where is _this_ file? and one level up thisScriptDir",
"as ex: with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue()",
"sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for field mapping', actual_print) def",
"is _this_ file? and one level up thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3',",
"for field mapping', actual_print) def test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format',",
"argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print =",
"fixtureToAbsolute('a.txt') self.positional = [ None, self.actual_file ] def tearDown(self): try: os.remove(self.actual_file) except Exception:",
"validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for field mapping', actual_print) def test_v1_public(self):",
"out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv",
"= build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip()",
"test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main()",
"= out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for field mapping', actual_print) def test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv')",
"= build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip()",
"= fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'CSV' ] argv = build_argv(optional, self.positional) with",
"self.assertEqual('Using \"v1-csv.txt\" for field mapping', actual_print) def test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv') argv =",
"self.positional[0] = fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file,",
"fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print",
"def test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err):",
"with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output",
"field mapping', actual_print) def test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'CSV'",
"err.getvalue() self.assertIn('Unknown field set', console_output) def test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [",
"os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file): # where is _this_ file? thisScriptDir",
"[ '--target-format', 'tsv' ] argv = build_argv(optional, self.positional) with self.assertRaises(SystemExit) as ex: with",
"_this_ file? and one level up thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3', mapping_file)",
"build_argv(optional, self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip()",
"out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for field mapping', actual_print) def test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv') argv",
"build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using",
"actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for field mapping', actual_print) def test_v1_public(self): self.positional[0] =",
"set', console_output) def test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'tsv' ]",
"thisScriptDir = os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__', fixture_file) # ------------------------------------------------------------------------------ # Classes # ------------------------------------------------------------------------------",
"argv = build_argv(optional, self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print",
"argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print =",
"fixture_file) # ------------------------------------------------------------------------------ # Classes # ------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def setUp(self): self.actual_file =",
"as sut from common.tests import build_argv, captured_output, validate_files def fieldsToAbsolute(mapping_file): # where is",
"out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv",
"test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv)",
"actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v1_intake_csv(self): self.positional[0] =",
"with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\"",
"self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file,",
"fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print",
"unittest import complaints.ccdb.choose_field_map as sut from common.tests import build_argv, captured_output, validate_files def fieldsToAbsolute(mapping_file):",
"with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('Unknown field",
"fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err):",
"build_argv, captured_output, validate_files def fieldsToAbsolute(mapping_file): # where is _this_ file? and one level",
"err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print)",
"test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'CSV' ] argv = build_argv(optional,",
"= fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'tsv' ] argv = build_argv(optional, self.positional) with",
"captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('usage: choose_field_map', console_output)",
"os.path.join(thisScriptDir, 'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file): # where is _this_ file? thisScriptDir = os.path.dirname(__file__)",
"\"v1-csv.txt\" for field mapping', actual_print) def test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional)",
"out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv') argv",
"build_argv(optional, self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code,",
"fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt')) actual_print",
"ex: with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('Unknown",
"where is _this_ file? and one level up thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir,",
"= os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__', fixture_file) # ------------------------------------------------------------------------------ # Classes # ------------------------------------------------------------------------------ class",
"Classes # ------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def setUp(self): self.actual_file = fixtureToAbsolute('a.txt') self.positional = [",
"os.remove(self.actual_file) except Exception: pass def test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional) with",
"fieldsToAbsolute(mapping_file): # where is _this_ file? and one level up thisScriptDir = os.path.dirname(os.path.dirname(__file__))",
"# where is _this_ file? and one level up thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return",
"return os.path.join(thisScriptDir, 'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file): # where is _this_ file? thisScriptDir =",
"= fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-json.txt'))",
"mapping', actual_print) def test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as",
"captured_output, validate_files def fieldsToAbsolute(mapping_file): # where is _this_ file? and one level up",
"fieldsToAbsolute('v1-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v2_intake(self): self.positional[0]",
"pass def test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out,",
"build_argv(positional=self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2)",
"'CSV' ] argv = build_argv(optional, self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file,",
"fixtureToAbsolute(fixture_file): # where is _this_ file? thisScriptDir = os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__', fixture_file)",
"actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_bad_input(self): self.positional[0] =",
"(out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('Unknown field set', console_output) def",
"fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for field mapping', actual_print) def test_v1_public(self): self.positional[0]",
"self.positional[0] = fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file,",
"self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as",
"------------------------------------------------------------------------------ # Classes # ------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def setUp(self): self.actual_file = fixtureToAbsolute('a.txt') self.positional",
"self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using",
"= out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv')",
"# ------------------------------------------------------------------------------ # Classes # ------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def setUp(self): self.actual_file = fixtureToAbsolute('a.txt')",
"self.assertIn('Unknown field set', console_output) def test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format',",
"with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\"",
"= build_argv(positional=self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code,",
"= [ None, self.actual_file ] def tearDown(self): try: os.remove(self.actual_file) except Exception: pass def",
"= [ '--target-format', 'CSV' ] argv = build_argv(optional, self.positional) with captured_output(argv) as (out,",
"as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field",
"sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v2-json.txt\" for field mapping', actual_print) def",
"class TestMain(unittest.TestCase): def setUp(self): self.actual_file = fixtureToAbsolute('a.txt') self.positional = [ None, self.actual_file ]",
"import unittest import complaints.ccdb.choose_field_map as sut from common.tests import build_argv, captured_output, validate_files def",
"test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main()",
"import build_argv, captured_output, validate_files def fieldsToAbsolute(mapping_file): # where is _this_ file? and one",
"import complaints.ccdb.choose_field_map as sut from common.tests import build_argv, captured_output, validate_files def fieldsToAbsolute(mapping_file): #",
"[ None, self.actual_file ] def tearDown(self): try: os.remove(self.actual_file) except Exception: pass def test_v1_intake_json(self):",
"actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v2_intake(self): self.positional[0] =",
"[ '--target-format', 'CSV' ] argv = build_argv(optional, self.positional) with captured_output(argv) as (out, err):",
"actual_print) def test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional) with self.assertRaises(SystemExit) as ex:",
"as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for field",
"mapping', actual_print) def test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional) with self.assertRaises(SystemExit) as",
"= os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file): # where is _this_ file?",
"] argv = build_argv(optional, self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out,",
"optional = [ '--target-format', 'CSV' ] argv = build_argv(optional, self.positional) with captured_output(argv) as",
"(out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for field mapping',",
"self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv =",
"ex: with captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('usage:",
"for field mapping', actual_print) def test_v2_intake(self): self.positional[0] = fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional) with",
"field mapping', actual_print) def test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional) with self.assertRaises(SystemExit)",
"return os.path.join(thisScriptDir, '__fixtures__', fixture_file) # ------------------------------------------------------------------------------ # Classes # ------------------------------------------------------------------------------ class TestMain(unittest.TestCase): def",
"def test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'CSV' ] argv =",
"console_output) def test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'tsv' ] argv",
"= err.getvalue() self.assertIn('Unknown field set', console_output) def test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional =",
"sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('usage: choose_field_map', console_output) self.assertIn('--target-format: invalid choice', console_output)",
"as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('usage: choose_field_map', console_output) self.assertIn('--target-format:",
"for field mapping', actual_print) def test_bad_input(self): self.positional[0] = fixtureToAbsolute('complaints-subset.csv') argv = build_argv(positional=self.positional) with",
"self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('Unknown field set', console_output) def test_bad_format_argument(self): self.positional[0] =",
"file? thisScriptDir = os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__', fixture_file) # ------------------------------------------------------------------------------ # Classes #",
"console_output = err.getvalue() self.assertIn('Unknown field set', console_output) def test_bad_format_argument(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional",
"captured_output(argv) as (out, err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('Unknown field set',",
"err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('Unknown field set', console_output) def test_bad_format_argument(self):",
"= out.getvalue().strip() self.assertEqual('Using \"v1-json.txt\" for field mapping', actual_print) def test_v1_intake_csv(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv')",
"where is _this_ file? thisScriptDir = os.path.dirname(__file__) return os.path.join(thisScriptDir, '__fixtures__', fixture_file) # ------------------------------------------------------------------------------",
"= fixtureToAbsolute('v2-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v2-json.txt'))",
"= [ '--target-format', 'tsv' ] argv = build_argv(optional, self.positional) with self.assertRaises(SystemExit) as ex:",
"setUp(self): self.actual_file = fixtureToAbsolute('a.txt') self.positional = [ None, self.actual_file ] def tearDown(self): try:",
"= build_argv(optional, self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err): sut.main()",
"err): sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('usage: choose_field_map', console_output) self.assertIn('--target-format: invalid choice',",
"mapping', actual_print) def test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as",
"one level up thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file): #",
"file? and one level up thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3', mapping_file) def",
"self.positional[0] = fixtureToAbsolute('v1-intake.csv') optional = [ '--target-format', 'CSV' ] argv = build_argv(optional, self.positional)",
"= fixtureToAbsolute('a.txt') self.positional = [ None, self.actual_file ] def tearDown(self): try: os.remove(self.actual_file) except",
"err): sut.main() validate_files(self.actual_file, fieldsToAbsolute('v1-csv.txt')) actual_print = out.getvalue().strip() self.assertEqual('Using \"v1-csv.txt\" for field mapping', actual_print)",
"def test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err):",
"def test_v2_public(self): self.positional[0] = fixtureToAbsolute('v2-public.csv') argv = build_argv(positional=self.positional) with captured_output(argv) as (out, err):",
"os import unittest import complaints.ccdb.choose_field_map as sut from common.tests import build_argv, captured_output, validate_files",
"] def tearDown(self): try: os.remove(self.actual_file) except Exception: pass def test_v1_intake_json(self): self.positional[0] = fixtureToAbsolute('v1-intake.csv')",
"and one level up thisScriptDir = os.path.dirname(os.path.dirname(__file__)) return os.path.join(thisScriptDir, 'fields-s3', mapping_file) def fixtureToAbsolute(fixture_file):",
"sut.main() self.assertEqual(ex.exception.code, 2) console_output = err.getvalue() self.assertIn('Unknown field set', console_output) def test_bad_format_argument(self): self.positional[0]",
"for field mapping', actual_print) def test_v1_public(self): self.positional[0] = fixtureToAbsolute('v1-public.csv') argv = build_argv(positional=self.positional) with",
"argv = build_argv(optional, self.positional) with self.assertRaises(SystemExit) as ex: with captured_output(argv) as (out, err):"
] |
[
"stdin. Args: stdin (str): The output of sys.stdin.read() \"\"\" print stdin def _cat_file(self,",
"import sys class Cat(object): def __init__(self, fname=None, stdin=None): \"\"\" Constructor Args: fname (str):",
"for f in self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self, stdin): \"\"\"",
"_validate_file(self, fname): \"\"\" Ensure fname exists, and is not a directory. Args: fname",
"Input from sys.stdin to output. Raises: ValueError: If provided file doesn't exist or",
"Args: stdin (str): The output of sys.stdin.read() \"\"\" print stdin def _cat_file(self, fname):",
"\"\"\" if not os.path.exists(fname): raise ValueError('cat: {}: No such file or directory.' .format(fname))",
"Constructor Args: fname (str): File to print to screen stdin (str): Input from",
"\"\"\" Print contents of a file. Args: fname: Name of file to print.",
"to the screen. \"\"\" if self.stdin: self._cat_stdin(self.stdin) return if not self.fname: self._cat_input() return",
"self.fname = fname self.stdin = stdin def run(self): \"\"\" Emulate 'cat'. Echo User",
"self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self, stdin): \"\"\" Print data provided in stdin. Args: stdin",
"in stdin. Args: stdin (str): The output of sys.stdin.read() \"\"\" print stdin def",
"self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self, stdin): \"\"\" Print data provided in stdin.",
"def _validate_file(self, fname): \"\"\" Ensure fname exists, and is not a directory. Args:",
"it to the screen. \"\"\" if self.stdin: self._cat_stdin(self.stdin) return if not self.fname: self._cat_input()",
"_cat_stdin(self, stdin): \"\"\" Print data provided in stdin. Args: stdin (str): The output",
"\"\"\" while True: user_input = raw_input() sys.stdout.write(user_input) def _validate_file(self, fname): \"\"\" Ensure fname",
"def _cat_file(self, fname): \"\"\" Print contents of a file. Args: fname: Name of",
"with open(fname, 'r') as f: sys.stdout.write((f.read())) def _cat_input(self): \"\"\" Echo back user input.",
"Author: <NAME> E-Mail: <EMAIL> Date: 5/25/2015 \"\"\" import os import sys class Cat(object):",
"fname exists, and is not a directory. Args: fname (str): The file path",
"a directory. \"\"\" self.fname = fname self.stdin = stdin def run(self): \"\"\" Emulate",
"ValueError('cat: {}: No such file or directory.' .format(fname)) if os.path.isdir(fname): raise ValueError('cat: {}:",
"isinstance(self.fname, list): for f in self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self,",
"Args: fname: Name of file to print. \"\"\" with open(fname, 'r') as f:",
"stdin def run(self): \"\"\" Emulate 'cat'. Echo User input if a file is",
"file or directory.' .format(fname)) if os.path.isdir(fname): raise ValueError('cat: {}: Is a directory.' .format(fname))",
"\"\"\" Print data provided in stdin. Args: stdin (str): The output of sys.stdin.read()",
"self._cat_input() return if isinstance(self.fname, list): for f in self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname)",
"Print data provided in stdin. Args: stdin (str): The output of sys.stdin.read() \"\"\"",
"class Cat(object): def __init__(self, fname=None, stdin=None): \"\"\" Constructor Args: fname (str): File to",
"\"\"\" Ensure fname exists, and is not a directory. Args: fname (str): The",
"The output of sys.stdin.read() \"\"\" print stdin def _cat_file(self, fname): \"\"\" Print contents",
"stdin def _cat_file(self, fname): \"\"\" Print contents of a file. Args: fname: Name",
"output of sys.stdin.read() \"\"\" print stdin def _cat_file(self, fname): \"\"\" Print contents of",
"self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self, stdin): \"\"\" Print data provided in",
"such file or directory.' .format(fname)) if os.path.isdir(fname): raise ValueError('cat: {}: Is a directory.'",
"cat.py -- Emulate UNIX cat. Author: <NAME> E-Mail: <EMAIL> Date: 5/25/2015 \"\"\" import",
"if self.stdin: self._cat_stdin(self.stdin) return if not self.fname: self._cat_input() return if isinstance(self.fname, list): for",
"self.fname: self._cat_input() return if isinstance(self.fname, list): for f in self.fname: self._validate_file(f) self._cat_file(f) else:",
"not provided, if a file is provided, print it to the screen. \"\"\"",
"file is provided, print it to the screen. \"\"\" if self.stdin: self._cat_stdin(self.stdin) return",
"the screen. \"\"\" if self.stdin: self._cat_stdin(self.stdin) return if not self.fname: self._cat_input() return if",
"fname: Name of file to print. \"\"\" with open(fname, 'r') as f: sys.stdout.write((f.read()))",
"cat. Author: <NAME> E-Mail: <EMAIL> Date: 5/25/2015 \"\"\" import os import sys class",
"'r') as f: sys.stdout.write((f.read())) def _cat_input(self): \"\"\" Echo back user input. \"\"\" while",
"= raw_input() sys.stdout.write(user_input) def _validate_file(self, fname): \"\"\" Ensure fname exists, and is not",
"__init__(self, fname=None, stdin=None): \"\"\" Constructor Args: fname (str): File to print to screen",
"fname self.stdin = stdin def run(self): \"\"\" Emulate 'cat'. Echo User input if",
"Emulate UNIX cat. Author: <NAME> E-Mail: <EMAIL> Date: 5/25/2015 \"\"\" import os import",
"doesn't exist or is a directory. \"\"\" self.fname = fname self.stdin = stdin",
"if a file is not provided, if a file is provided, print it",
"provided, if a file is provided, print it to the screen. \"\"\" if",
"return if not self.fname: self._cat_input() return if isinstance(self.fname, list): for f in self.fname:",
"True: user_input = raw_input() sys.stdout.write(user_input) def _validate_file(self, fname): \"\"\" Ensure fname exists, and",
"os import sys class Cat(object): def __init__(self, fname=None, stdin=None): \"\"\" Constructor Args: fname",
"Print contents of a file. Args: fname: Name of file to print. \"\"\"",
"'cat'. Echo User input if a file is not provided, if a file",
"not exist or is a directory. \"\"\" if not os.path.exists(fname): raise ValueError('cat: {}:",
"or is a directory. \"\"\" self.fname = fname self.stdin = stdin def run(self):",
"Args: fname (str): The file path to validate. Raises: ValueError: If file does",
"a file is provided, print it to the screen. \"\"\" if self.stdin: self._cat_stdin(self.stdin)",
"Date: 5/25/2015 \"\"\" import os import sys class Cat(object): def __init__(self, fname=None, stdin=None):",
"(str): The output of sys.stdin.read() \"\"\" print stdin def _cat_file(self, fname): \"\"\" Print",
"print to screen stdin (str): Input from sys.stdin to output. Raises: ValueError: If",
"fname (str): File to print to screen stdin (str): Input from sys.stdin to",
"import os import sys class Cat(object): def __init__(self, fname=None, stdin=None): \"\"\" Constructor Args:",
"file. Args: fname: Name of file to print. \"\"\" with open(fname, 'r') as",
"No such file or directory.' .format(fname)) if os.path.isdir(fname): raise ValueError('cat: {}: Is a",
"\"\"\" import os import sys class Cat(object): def __init__(self, fname=None, stdin=None): \"\"\" Constructor",
"is a directory. \"\"\" if not os.path.exists(fname): raise ValueError('cat: {}: No such file",
"UNIX cat. Author: <NAME> E-Mail: <EMAIL> Date: 5/25/2015 \"\"\" import os import sys",
"directory. \"\"\" if not os.path.exists(fname): raise ValueError('cat: {}: No such file or directory.'",
"in self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self, stdin): \"\"\" Print data",
"input. \"\"\" while True: user_input = raw_input() sys.stdout.write(user_input) def _validate_file(self, fname): \"\"\" Ensure",
"if not os.path.exists(fname): raise ValueError('cat: {}: No such file or directory.' .format(fname)) if",
"fname): \"\"\" Ensure fname exists, and is not a directory. Args: fname (str):",
"directory. Args: fname (str): The file path to validate. Raises: ValueError: If file",
"Name of file to print. \"\"\" with open(fname, 'r') as f: sys.stdout.write((f.read())) def",
"os.path.exists(fname): raise ValueError('cat: {}: No such file or directory.' .format(fname)) if os.path.isdir(fname): raise",
"screen. \"\"\" if self.stdin: self._cat_stdin(self.stdin) return if not self.fname: self._cat_input() return if isinstance(self.fname,",
"f: sys.stdout.write((f.read())) def _cat_input(self): \"\"\" Echo back user input. \"\"\" while True: user_input",
"Cat(object): def __init__(self, fname=None, stdin=None): \"\"\" Constructor Args: fname (str): File to print",
"\"\"\" cat.py -- Emulate UNIX cat. Author: <NAME> E-Mail: <EMAIL> Date: 5/25/2015 \"\"\"",
"validate. Raises: ValueError: If file does not exist or is a directory. \"\"\"",
"a file is not provided, if a file is provided, print it to",
"provided file doesn't exist or is a directory. \"\"\" self.fname = fname self.stdin",
"to print to screen stdin (str): Input from sys.stdin to output. Raises: ValueError:",
"stdin (str): Input from sys.stdin to output. Raises: ValueError: If provided file doesn't",
"directory. \"\"\" self.fname = fname self.stdin = stdin def run(self): \"\"\" Emulate 'cat'.",
"self.stdin = stdin def run(self): \"\"\" Emulate 'cat'. Echo User input if a",
"or is a directory. \"\"\" if not os.path.exists(fname): raise ValueError('cat: {}: No such",
"exists, and is not a directory. Args: fname (str): The file path to",
"sys.stdout.write((f.read())) def _cat_input(self): \"\"\" Echo back user input. \"\"\" while True: user_input =",
"fname (str): The file path to validate. Raises: ValueError: If file does not",
"(str): File to print to screen stdin (str): Input from sys.stdin to output.",
"_cat_file(self, fname): \"\"\" Print contents of a file. Args: fname: Name of file",
"not self.fname: self._cat_input() return if isinstance(self.fname, list): for f in self.fname: self._validate_file(f) self._cat_file(f)",
"data provided in stdin. Args: stdin (str): The output of sys.stdin.read() \"\"\" print",
"<reponame>blakfeld/Bash-To-Python<filename>bash_to_python/cat.py<gh_stars>0 \"\"\" cat.py -- Emulate UNIX cat. Author: <NAME> E-Mail: <EMAIL> Date: 5/25/2015",
"print. \"\"\" with open(fname, 'r') as f: sys.stdout.write((f.read())) def _cat_input(self): \"\"\" Echo back",
"If provided file doesn't exist or is a directory. \"\"\" self.fname = fname",
"user_input = raw_input() sys.stdout.write(user_input) def _validate_file(self, fname): \"\"\" Ensure fname exists, and is",
"5/25/2015 \"\"\" import os import sys class Cat(object): def __init__(self, fname=None, stdin=None): \"\"\"",
"self.stdin: self._cat_stdin(self.stdin) return if not self.fname: self._cat_input() return if isinstance(self.fname, list): for f",
"is a directory. \"\"\" self.fname = fname self.stdin = stdin def run(self): \"\"\"",
"user input. \"\"\" while True: user_input = raw_input() sys.stdout.write(user_input) def _validate_file(self, fname): \"\"\"",
"self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self, stdin): \"\"\" Print data provided",
"does not exist or is a directory. \"\"\" if not os.path.exists(fname): raise ValueError('cat:",
"\"\"\" if self.stdin: self._cat_stdin(self.stdin) return if not self.fname: self._cat_input() return if isinstance(self.fname, list):",
"open(fname, 'r') as f: sys.stdout.write((f.read())) def _cat_input(self): \"\"\" Echo back user input. \"\"\"",
"from sys.stdin to output. Raises: ValueError: If provided file doesn't exist or is",
"to output. Raises: ValueError: If provided file doesn't exist or is a directory.",
"sys.stdin to output. Raises: ValueError: If provided file doesn't exist or is a",
"\"\"\" print stdin def _cat_file(self, fname): \"\"\" Print contents of a file. Args:",
"Ensure fname exists, and is not a directory. Args: fname (str): The file",
"The file path to validate. Raises: ValueError: If file does not exist or",
"and is not a directory. Args: fname (str): The file path to validate.",
"\"\"\" Emulate 'cat'. Echo User input if a file is not provided, if",
"Raises: ValueError: If provided file doesn't exist or is a directory. \"\"\" self.fname",
"if not self.fname: self._cat_input() return if isinstance(self.fname, list): for f in self.fname: self._validate_file(f)",
"else: self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self, stdin): \"\"\" Print data provided in stdin. Args:",
"to validate. Raises: ValueError: If file does not exist or is a directory.",
"<EMAIL> Date: 5/25/2015 \"\"\" import os import sys class Cat(object): def __init__(self, fname=None,",
"a directory. Args: fname (str): The file path to validate. Raises: ValueError: If",
"provided, print it to the screen. \"\"\" if self.stdin: self._cat_stdin(self.stdin) return if not",
"_cat_input(self): \"\"\" Echo back user input. \"\"\" while True: user_input = raw_input() sys.stdout.write(user_input)",
"stdin): \"\"\" Print data provided in stdin. Args: stdin (str): The output of",
"def run(self): \"\"\" Emulate 'cat'. Echo User input if a file is not",
"input if a file is not provided, if a file is provided, print",
"\"\"\" Constructor Args: fname (str): File to print to screen stdin (str): Input",
"to screen stdin (str): Input from sys.stdin to output. Raises: ValueError: If provided",
"Raises: ValueError: If file does not exist or is a directory. \"\"\" if",
"(str): The file path to validate. Raises: ValueError: If file does not exist",
"if a file is provided, print it to the screen. \"\"\" if self.stdin:",
"ValueError: If file does not exist or is a directory. \"\"\" if not",
"If file does not exist or is a directory. \"\"\" if not os.path.exists(fname):",
"def _cat_stdin(self, stdin): \"\"\" Print data provided in stdin. Args: stdin (str): The",
"file does not exist or is a directory. \"\"\" if not os.path.exists(fname): raise",
"File to print to screen stdin (str): Input from sys.stdin to output. Raises:",
"is not provided, if a file is provided, print it to the screen.",
"\"\"\" self.fname = fname self.stdin = stdin def run(self): \"\"\" Emulate 'cat'. Echo",
"run(self): \"\"\" Emulate 'cat'. Echo User input if a file is not provided,",
"back user input. \"\"\" while True: user_input = raw_input() sys.stdout.write(user_input) def _validate_file(self, fname):",
"{}: No such file or directory.' .format(fname)) if os.path.isdir(fname): raise ValueError('cat: {}: Is",
"= stdin def run(self): \"\"\" Emulate 'cat'. Echo User input if a file",
"a file. Args: fname: Name of file to print. \"\"\" with open(fname, 'r')",
"self._cat_stdin(self.stdin) return if not self.fname: self._cat_input() return if isinstance(self.fname, list): for f in",
"Echo User input if a file is not provided, if a file is",
"of file to print. \"\"\" with open(fname, 'r') as f: sys.stdout.write((f.read())) def _cat_input(self):",
"file is not provided, if a file is provided, print it to the",
"if isinstance(self.fname, list): for f in self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname) def",
"stdin (str): The output of sys.stdin.read() \"\"\" print stdin def _cat_file(self, fname): \"\"\"",
"sys.stdout.write(user_input) def _validate_file(self, fname): \"\"\" Ensure fname exists, and is not a directory.",
"file to print. \"\"\" with open(fname, 'r') as f: sys.stdout.write((f.read())) def _cat_input(self): \"\"\"",
"Args: fname (str): File to print to screen stdin (str): Input from sys.stdin",
"contents of a file. Args: fname: Name of file to print. \"\"\" with",
"return if isinstance(self.fname, list): for f in self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname)",
"f in self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self, stdin): \"\"\" Print",
"to print. \"\"\" with open(fname, 'r') as f: sys.stdout.write((f.read())) def _cat_input(self): \"\"\" Echo",
"raise ValueError('cat: {}: No such file or directory.' .format(fname)) if os.path.isdir(fname): raise ValueError('cat:",
"E-Mail: <EMAIL> Date: 5/25/2015 \"\"\" import os import sys class Cat(object): def __init__(self,",
"raw_input() sys.stdout.write(user_input) def _validate_file(self, fname): \"\"\" Ensure fname exists, and is not a",
"is not a directory. Args: fname (str): The file path to validate. Raises:",
"= fname self.stdin = stdin def run(self): \"\"\" Emulate 'cat'. Echo User input",
"as f: sys.stdout.write((f.read())) def _cat_input(self): \"\"\" Echo back user input. \"\"\" while True:",
"print it to the screen. \"\"\" if self.stdin: self._cat_stdin(self.stdin) return if not self.fname:",
"def __init__(self, fname=None, stdin=None): \"\"\" Constructor Args: fname (str): File to print to",
"a directory. \"\"\" if not os.path.exists(fname): raise ValueError('cat: {}: No such file or",
"sys class Cat(object): def __init__(self, fname=None, stdin=None): \"\"\" Constructor Args: fname (str): File",
"list): for f in self.fname: self._validate_file(f) self._cat_file(f) else: self._validate_file(self.fname) self._cat_file(self.fname) def _cat_stdin(self, stdin):",
"not a directory. Args: fname (str): The file path to validate. Raises: ValueError:",
"Echo back user input. \"\"\" while True: user_input = raw_input() sys.stdout.write(user_input) def _validate_file(self,",
"screen stdin (str): Input from sys.stdin to output. Raises: ValueError: If provided file",
"\"\"\" Echo back user input. \"\"\" while True: user_input = raw_input() sys.stdout.write(user_input) def",
"(str): Input from sys.stdin to output. Raises: ValueError: If provided file doesn't exist",
"-- Emulate UNIX cat. Author: <NAME> E-Mail: <EMAIL> Date: 5/25/2015 \"\"\" import os",
"exist or is a directory. \"\"\" self.fname = fname self.stdin = stdin def",
"is provided, print it to the screen. \"\"\" if self.stdin: self._cat_stdin(self.stdin) return if",
"exist or is a directory. \"\"\" if not os.path.exists(fname): raise ValueError('cat: {}: No",
"output. Raises: ValueError: If provided file doesn't exist or is a directory. \"\"\"",
"sys.stdin.read() \"\"\" print stdin def _cat_file(self, fname): \"\"\" Print contents of a file.",
"not os.path.exists(fname): raise ValueError('cat: {}: No such file or directory.' .format(fname)) if os.path.isdir(fname):",
"fname=None, stdin=None): \"\"\" Constructor Args: fname (str): File to print to screen stdin",
"of sys.stdin.read() \"\"\" print stdin def _cat_file(self, fname): \"\"\" Print contents of a",
"Emulate 'cat'. Echo User input if a file is not provided, if a",
"stdin=None): \"\"\" Constructor Args: fname (str): File to print to screen stdin (str):",
"while True: user_input = raw_input() sys.stdout.write(user_input) def _validate_file(self, fname): \"\"\" Ensure fname exists,",
"self._cat_file(self.fname) def _cat_stdin(self, stdin): \"\"\" Print data provided in stdin. Args: stdin (str):",
"def _cat_input(self): \"\"\" Echo back user input. \"\"\" while True: user_input = raw_input()",
"ValueError: If provided file doesn't exist or is a directory. \"\"\" self.fname =",
"<NAME> E-Mail: <EMAIL> Date: 5/25/2015 \"\"\" import os import sys class Cat(object): def",
"print stdin def _cat_file(self, fname): \"\"\" Print contents of a file. Args: fname:",
"path to validate. Raises: ValueError: If file does not exist or is a",
"User input if a file is not provided, if a file is provided,",
"of a file. Args: fname: Name of file to print. \"\"\" with open(fname,",
"file path to validate. Raises: ValueError: If file does not exist or is",
"\"\"\" with open(fname, 'r') as f: sys.stdout.write((f.read())) def _cat_input(self): \"\"\" Echo back user",
"file doesn't exist or is a directory. \"\"\" self.fname = fname self.stdin =",
"provided in stdin. Args: stdin (str): The output of sys.stdin.read() \"\"\" print stdin",
"fname): \"\"\" Print contents of a file. Args: fname: Name of file to"
] |
[
"in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\" id: \"+str(id_list)+\"\\n\") #f.close() if __name__ == \"__main__\": main()",
"and (sum(result)/len(result))>0 and (sum(result)/len(result)) < 6: reflector_candidate[ip] = lists[0] f4.write(\"respond to ip: \"+ip)",
"<= 29 and len(result) >20 and (sum(result)/len(result))>0 and (sum(result)/len(result)) < 6: reflector_candidate[ip] =",
"< 6: reflector_candidate[ip] = lists[0] f4.write(\"respond to ip: \"+ip) f4.close() f3 = open(",
"f2.write(\"request to ip: \"+ip+ \" port: \"+str(port)+\"\\n\") f2.write(\"respond to ip: \"+ip+ \" port:",
"!= ipid_map[ip][0]: f2.write(\"request to ip: \"+ip+ \" port: \"+str(port)+\"\\n\") f2.write(\"respond to ip: \"+ip+",
"port: \"+str(port)+\"\\n\") f2.write(\"respond to ip: \"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4 =",
"ipid_map.items(): result = [j-i for j, i in zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i for",
"zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i for j, i in zip(lists[4::2],lists[2:-1:2])] if all(time > 0.8",
"eth.type == dpkt.ethernet.ETH_TYPE_IP and tcp.dport == src_port: # and tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id)",
"open(\"result_measure.txt\",\"w+\") #for ip, id_list in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\" id: \"+str(id_list)+\"\\n\") #f.close() if",
"and len(result) <= 29 and len(result) >20 and (sum(result)/len(result))>0 and (sum(result)/len(result)) < 6:",
"#f = open(\"result_measure.txt\",\"w+\") #for ip, id_list in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\" id: \"+str(id_list)+\"\\n\")",
"parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\") for ip,port in",
"main(): parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\")",
"ipid_map[ip][0]: f2.write(\"request to ip: \"+ip+ \" port: \"+str(port)+\"\\n\") f2.write(\"respond to ip: \"+ip+ \"",
"pickle.load(f) f.close() return db def main(): parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\") f1",
"f4.close() f3 = open( \"reflector_candidate.pickle\", \"wb\" ) pickle.dump( reflector_candidate, f3) f3.close() print(reflector_candidate) #for",
"# print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\") # exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f",
"= open(file_n) pcap = dpkt.pcap.Reader(f) for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf)",
"#src_addr = socket.inet_ntoa(ip.src) if eth.type == dpkt.ethernet.ETH_TYPE_IP and tcp.dport == src_port: # and",
"ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def parse_candidate(file_name): f = open(file_name,'rb') db = pickle.load(f) f.close() return",
"in ipid_map: f1.write(ip+\"\\n\") elif port != ipid_map[ip][0]: f2.write(\"request to ip: \"+ip+ \" port:",
"buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data #src_addr",
"ip.data #src_addr = socket.inet_ntoa(ip.src) if eth.type == dpkt.ethernet.ETH_TYPE_IP and tcp.dport == src_port: #",
"open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\") for ip,port in parse_ip.items(): if ip not in ipid_map:",
"lists[0] f4.write(\"respond to ip: \"+ip) f4.close() f3 = open( \"reflector_candidate.pickle\", \"wb\" ) pickle.dump(",
"parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\") for",
"ip, id_list in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\" id: \"+str(id_list)+\"\\n\") #f.close() if __name__ ==",
"ip: \"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4 = open(\"cand\",\"w+\") reflector_candidate = {}",
"= open(\"result_measure.txt\",\"w+\") #for ip, id_list in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\" id: \"+str(id_list)+\"\\n\") #f.close()",
"open( \"reflector_candidate.pickle\", \"wb\" ) pickle.dump( reflector_candidate, f3) f3.close() print(reflector_candidate) #for i in range(30):",
"pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data #src_addr = socket.inet_ntoa(ip.src)",
"eth.data tcp = ip.data #src_addr = socket.inet_ntoa(ip.src) if eth.type == dpkt.ethernet.ETH_TYPE_IP and tcp.dport",
"pcap_name = \"filter.pcap\" ipid_map={} def parse_pcap(file_n): f = open(file_n) pcap = dpkt.pcap.Reader(f) for",
"tcp.dport == src_port: # and tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def parse_candidate(file_name):",
"f4 = open(\"cand\",\"w+\") reflector_candidate = {} for ip,lists in ipid_map.items(): result = [j-i",
"id: \"+str(port)+\"\\n\") # exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\") #for",
"== src_port: # and tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def parse_candidate(file_name): f",
"eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data #src_addr = socket.inet_ntoa(ip.src) if",
"f3 = open( \"reflector_candidate.pickle\", \"wb\" ) pickle.dump( reflector_candidate, f3) f3.close() print(reflector_candidate) #for i",
"in ipid_map.items(): result = [j-i for j, i in zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i",
"send_packet import dpkt, socket, subprocess from collections import defaultdict import time import cPickle",
"\"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4 = open(\"cand\",\"w+\") reflector_candidate = {} for ip,lists in ipid_map.items():",
"ipid_map={} def parse_pcap(file_n): f = open(file_n) pcap = dpkt.pcap.Reader(f) for ts, buf in",
"= eth.data tcp = ip.data #src_addr = socket.inet_ntoa(ip.src) if eth.type == dpkt.ethernet.ETH_TYPE_IP and",
"= [j-i for j, i in zip(lists[4::2],lists[2:-1:2])] if all(time > 0.8 for time",
"> 0.8 for time in timestamp) and len(result) <= 29 and len(result) >20",
"\"reflector_candidate.pickle\", \"wb\" ) pickle.dump( reflector_candidate, f3) f3.close() print(reflector_candidate) #for i in range(30): #",
"ip, port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\") #",
"reflector_candidate[ip] = lists[0] f4.write(\"respond to ip: \"+ip) f4.close() f3 = open( \"reflector_candidate.pickle\", \"wb\"",
"#p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\") #for ip, id_list in ipid_map.iteritems(): # f.write(\"ip:",
"<filename>calculate_diff.py<gh_stars>0 #!/usr/bin/python2 from spoof_struct import send_packet import dpkt, socket, subprocess from collections import",
"in timestamp) and len(result) <= 29 and len(result) >20 and (sum(result)/len(result))>0 and (sum(result)/len(result))",
"pcap = dpkt.pcap.Reader(f) for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip =",
"\"filter.pcap\" ipid_map={} def parse_pcap(file_n): f = open(file_n) pcap = dpkt.pcap.Reader(f) for ts, buf",
"import send_packet import dpkt, socket, subprocess from collections import defaultdict import time import",
"and tcp.dport == src_port: # and tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def",
"ipid_map = parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\") for ip,port in parse_ip.items():",
"f2.close() f4 = open(\"cand\",\"w+\") reflector_candidate = {} for ip,lists in ipid_map.items(): result =",
"not in ipid_map: f1.write(ip+\"\\n\") elif port != ipid_map[ip][0]: f2.write(\"request to ip: \"+ip+ \"",
"in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data #src_addr =",
"pickle.dump( reflector_candidate, f3) f3.close() print(reflector_candidate) #for i in range(30): # for ip, port",
"== port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def parse_candidate(file_name): f = open(file_name,'rb') db = pickle.load(f)",
"socket, subprocess from collections import defaultdict import time import cPickle as pickle import",
"cPickle as pickle import itertools src_ip = '192.168.100.128' spoof_ip = '192.168.22.21' src_port =",
"src_ip = '192.168.100.128' spoof_ip = '192.168.22.21' src_port = 54024 pcap_name = \"filter.pcap\" ipid_map={}",
"\"+ip+ \" port: \"+str(port)+\"\\n\") f2.write(\"respond to ip: \"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close()",
"to ip: \"+ip+ \" port: \"+str(port)+\"\\n\") f2.write(\"respond to ip: \"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\")",
"all(time > 0.8 for time in timestamp) and len(result) <= 29 and len(result)",
"= [j-i for j, i in zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i for j, i",
"defaultdict import time import cPickle as pickle import itertools src_ip = '192.168.100.128' spoof_ip",
"= 54024 pcap_name = \"filter.pcap\" ipid_map={} def parse_pcap(file_n): f = open(file_n) pcap =",
"dpkt.ethernet.ETH_TYPE_IP and tcp.dport == src_port: # and tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return",
"= lists[0] f4.write(\"respond to ip: \"+ip) f4.close() f3 = open( \"reflector_candidate.pickle\", \"wb\" )",
"range(30): # for ip, port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\"",
"= ip.data #src_addr = socket.inet_ntoa(ip.src) if eth.type == dpkt.ethernet.ETH_TYPE_IP and tcp.dport == src_port:",
"parse_pcap(file_n): f = open(file_n) pcap = dpkt.pcap.Reader(f) for ts, buf in pcap: eth",
"if all(time > 0.8 for time in timestamp) and len(result) <= 29 and",
"timestamp) and len(result) <= 29 and len(result) >20 and (sum(result)/len(result))>0 and (sum(result)/len(result)) <",
"29 and len(result) >20 and (sum(result)/len(result))>0 and (sum(result)/len(result)) < 6: reflector_candidate[ip] = lists[0]",
"'192.168.100.128' spoof_ip = '192.168.22.21' src_port = 54024 pcap_name = \"filter.pcap\" ipid_map={} def parse_pcap(file_n):",
"import dpkt, socket, subprocess from collections import defaultdict import time import cPickle as",
"import itertools src_ip = '192.168.100.128' spoof_ip = '192.168.22.21' src_port = 54024 pcap_name =",
"if ip not in ipid_map: f1.write(ip+\"\\n\") elif port != ipid_map[ip][0]: f2.write(\"request to ip:",
"f3.close() print(reflector_candidate) #for i in range(30): # for ip, port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1)",
"# send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\") # exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1)",
"in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\") # exit(1) #",
"= open(file_name,'rb') db = pickle.load(f) f.close() return db def main(): parse_ip = parse_candidate(\"ip_port_record.pickle\")",
"def parse_pcap(file_n): f = open(file_n) pcap = dpkt.pcap.Reader(f) for ts, buf in pcap:",
"ip not in ipid_map: f1.write(ip+\"\\n\") elif port != ipid_map[ip][0]: f2.write(\"request to ip: \"+ip+",
"# exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\") #for ip, id_list",
"(sum(result)/len(result)) < 6: reflector_candidate[ip] = lists[0] f4.write(\"respond to ip: \"+ip) f4.close() f3 =",
"f4.write(\"respond to ip: \"+ip) f4.close() f3 = open( \"reflector_candidate.pickle\", \"wb\" ) pickle.dump( reflector_candidate,",
"j, i in zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i for j, i in zip(lists[4::2],lists[2:-1:2])] if",
"\"+ip+\" id: \"+str(port)+\"\\n\") # exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\")",
"db = pickle.load(f) f.close() return db def main(): parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map =",
"result = [j-i for j, i in zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i for j,",
"j, i in zip(lists[4::2],lists[2:-1:2])] if all(time > 0.8 for time in timestamp) and",
"port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\") # exit(1)",
"\"wb\" ) pickle.dump( reflector_candidate, f3) f3.close() print(reflector_candidate) #for i in range(30): # for",
"i in zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i for j, i in zip(lists[4::2],lists[2:-1:2])] if all(time",
"def parse_candidate(file_name): f = open(file_name,'rb') db = pickle.load(f) f.close() return db def main():",
"ip: \"+ip+ \" port: \"+str(port)+\"\\n\") f2.write(\"respond to ip: \"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close()",
"reflector_candidate, f3) f3.close() print(reflector_candidate) #for i in range(30): # for ip, port in",
"= \"filter.pcap\" ipid_map={} def parse_pcap(file_n): f = open(file_n) pcap = dpkt.pcap.Reader(f) for ts,",
"to ip: \"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4 = open(\"cand\",\"w+\") reflector_candidate =",
"send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\") # exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name)",
"f2.write(\"respond to ip: \"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4 = open(\"cand\",\"w+\") reflector_candidate",
"f.close() return def parse_candidate(file_name): f = open(file_name,'rb') db = pickle.load(f) f.close() return db",
"[j-i for j, i in zip(lists[4::2],lists[2:-1:2])] if all(time > 0.8 for time in",
"= dpkt.pcap.Reader(f) for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data",
"in parse_ip.items(): if ip not in ipid_map: f1.write(ip+\"\\n\") elif port != ipid_map[ip][0]: f2.write(\"request",
"f3) f3.close() print(reflector_candidate) #for i in range(30): # for ip, port in parse_ip.items():",
"= socket.inet_ntoa(ip.src) if eth.type == dpkt.ethernet.ETH_TYPE_IP and tcp.dport == src_port: # and tcp.sport",
"ipid_map: f1.write(ip+\"\\n\") elif port != ipid_map[ip][0]: f2.write(\"request to ip: \"+ip+ \" port: \"+str(port)+\"\\n\")",
"= open( \"reflector_candidate.pickle\", \"wb\" ) pickle.dump( reflector_candidate, f3) f3.close() print(reflector_candidate) #for i in",
"# for ip, port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\" id:",
"= open(\"cand\",\"w+\") reflector_candidate = {} for ip,lists in ipid_map.items(): result = [j-i for",
"reflector_candidate = {} for ip,lists in ipid_map.items(): result = [j-i for j, i",
"#parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\") #for ip, id_list in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\" id:",
"and len(result) >20 and (sum(result)/len(result))>0 and (sum(result)/len(result)) < 6: reflector_candidate[ip] = lists[0] f4.write(\"respond",
"dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data #src_addr = socket.inet_ntoa(ip.src) if eth.type ==",
"dpkt.pcap.Reader(f) for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp",
"f = open(file_name,'rb') db = pickle.load(f) f.close() return db def main(): parse_ip =",
"parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\") # exit(1) # time.sleep(1)",
"open(file_n) pcap = dpkt.pcap.Reader(f) for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip",
"'192.168.22.21' src_port = 54024 pcap_name = \"filter.pcap\" ipid_map={} def parse_pcap(file_n): f = open(file_n)",
"6: reflector_candidate[ip] = lists[0] f4.write(\"respond to ip: \"+ip) f4.close() f3 = open( \"reflector_candidate.pickle\",",
"if eth.type == dpkt.ethernet.ETH_TYPE_IP and tcp.dport == src_port: # and tcp.sport == port",
"parse_ip.items(): if ip not in ipid_map: f1.write(ip+\"\\n\") elif port != ipid_map[ip][0]: f2.write(\"request to",
"for ip,lists in ipid_map.items(): result = [j-i for j, i in zip(lists[3::2],lists[1:-2:2])] timestamp",
"54024 pcap_name = \"filter.pcap\" ipid_map={} def parse_pcap(file_n): f = open(file_n) pcap = dpkt.pcap.Reader(f)",
"tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def parse_candidate(file_name): f = open(file_name,'rb') db =",
"# time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\") #for ip, id_list in ipid_map.iteritems():",
"spoof_ip = '192.168.22.21' src_port = 54024 pcap_name = \"filter.pcap\" ipid_map={} def parse_pcap(file_n): f",
"timestamp = [j-i for j, i in zip(lists[4::2],lists[2:-1:2])] if all(time > 0.8 for",
"to ip: \"+ip) f4.close() f3 = open( \"reflector_candidate.pickle\", \"wb\" ) pickle.dump( reflector_candidate, f3)",
"time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\") #for ip, id_list in ipid_map.iteritems(): #",
"\"+ip) f4.close() f3 = open( \"reflector_candidate.pickle\", \"wb\" ) pickle.dump( reflector_candidate, f3) f3.close() print(reflector_candidate)",
"and tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def parse_candidate(file_name): f = open(file_name,'rb') db",
"port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4 = open(\"cand\",\"w+\") reflector_candidate = {} for ip,lists in",
"for j, i in zip(lists[4::2],lists[2:-1:2])] if all(time > 0.8 for time in timestamp)",
"\"+str(port)+\"\\n\") f2.write(\"respond to ip: \"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4 = open(\"cand\",\"w+\")",
"len(result) >20 and (sum(result)/len(result))>0 and (sum(result)/len(result)) < 6: reflector_candidate[ip] = lists[0] f4.write(\"respond to",
"print(reflector_candidate) #for i in range(30): # for ip, port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) #",
"[j-i for j, i in zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i for j, i in",
"print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\") # exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f =",
"port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def parse_candidate(file_name): f = open(file_name,'rb') db = pickle.load(f) f.close()",
"parse_candidate(file_name): f = open(file_name,'rb') db = pickle.load(f) f.close() return db def main(): parse_ip",
"\" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4 = open(\"cand\",\"w+\") reflector_candidate = {} for ip,lists",
"subprocess from collections import defaultdict import time import cPickle as pickle import itertools",
"socket.inet_ntoa(ip.src) if eth.type == dpkt.ethernet.ETH_TYPE_IP and tcp.dport == src_port: # and tcp.sport ==",
"time import cPickle as pickle import itertools src_ip = '192.168.100.128' spoof_ip = '192.168.22.21'",
"dpkt, socket, subprocess from collections import defaultdict import time import cPickle as pickle",
"== dpkt.ethernet.ETH_TYPE_IP and tcp.dport == src_port: # and tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close()",
"f.close() return db def main(): parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\") f1 =",
"ip,port in parse_ip.items(): if ip not in ipid_map: f1.write(ip+\"\\n\") elif port != ipid_map[ip][0]:",
"in range(30): # for ip, port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip:",
"in zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i for j, i in zip(lists[4::2],lists[2:-1:2])] if all(time >",
"import cPickle as pickle import itertools src_ip = '192.168.100.128' spoof_ip = '192.168.22.21' src_port",
">20 and (sum(result)/len(result))>0 and (sum(result)/len(result)) < 6: reflector_candidate[ip] = lists[0] f4.write(\"respond to ip:",
"return def parse_candidate(file_name): f = open(file_name,'rb') db = pickle.load(f) f.close() return db def",
"f1 = open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\") for ip,port in parse_ip.items(): if ip not",
"for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp =",
"def main(): parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\") f2 =",
"= open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\") for ip,port in parse_ip.items(): if ip not in",
"#!/usr/bin/python2 from spoof_struct import send_packet import dpkt, socket, subprocess from collections import defaultdict",
"from collections import defaultdict import time import cPickle as pickle import itertools src_ip",
"for ip,port in parse_ip.items(): if ip not in ipid_map: f1.write(ip+\"\\n\") elif port !=",
"{} for ip,lists in ipid_map.items(): result = [j-i for j, i in zip(lists[3::2],lists[1:-2:2])]",
"for j, i in zip(lists[3::2],lists[1:-2:2])] timestamp = [j-i for j, i in zip(lists[4::2],lists[2:-1:2])]",
"in zip(lists[4::2],lists[2:-1:2])] if all(time > 0.8 for time in timestamp) and len(result) <=",
"tcp = ip.data #src_addr = socket.inet_ntoa(ip.src) if eth.type == dpkt.ethernet.ETH_TYPE_IP and tcp.dport ==",
"(sum(result)/len(result))>0 and (sum(result)/len(result)) < 6: reflector_candidate[ip] = lists[0] f4.write(\"respond to ip: \"+ip) f4.close()",
"open(file_name,'rb') db = pickle.load(f) f.close() return db def main(): parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map",
"= parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\") for ip,port",
"elif port != ipid_map[ip][0]: f2.write(\"request to ip: \"+ip+ \" port: \"+str(port)+\"\\n\") f2.write(\"respond to",
"pickle import itertools src_ip = '192.168.100.128' spoof_ip = '192.168.22.21' src_port = 54024 pcap_name",
"open(\"cand\",\"w+\") reflector_candidate = {} for ip,lists in ipid_map.items(): result = [j-i for j,",
"for time in timestamp) and len(result) <= 29 and len(result) >20 and (sum(result)/len(result))>0",
"ip = eth.data tcp = ip.data #src_addr = socket.inet_ntoa(ip.src) if eth.type == dpkt.ethernet.ETH_TYPE_IP",
"spoof_struct import send_packet import dpkt, socket, subprocess from collections import defaultdict import time",
"= pickle.load(f) f.close() return db def main(): parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\")",
"open(\"diff_port\",\"w+\") for ip,port in parse_ip.items(): if ip not in ipid_map: f1.write(ip+\"\\n\") elif port",
"f1.close() f2.close() f4 = open(\"cand\",\"w+\") reflector_candidate = {} for ip,lists in ipid_map.items(): result",
"src_port: # and tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def parse_candidate(file_name): f =",
"len(result) <= 29 and len(result) >20 and (sum(result)/len(result))>0 and (sum(result)/len(result)) < 6: reflector_candidate[ip]",
"f1.write(ip+\"\\n\") elif port != ipid_map[ip][0]: f2.write(\"request to ip: \"+ip+ \" port: \"+str(port)+\"\\n\") f2.write(\"respond",
"#time.sleep(1) #parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\") #for ip, id_list in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\"",
"\"+str(port)+\"\\n\") # exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\") #for ip,",
"return db def main(): parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\")",
"zip(lists[4::2],lists[2:-1:2])] if all(time > 0.8 for time in timestamp) and len(result) <= 29",
"# and tcp.sport == port ipid_map[socket.inet_ntoa(ip.src)].append(ip.id) f.close() return def parse_candidate(file_name): f = open(file_name,'rb')",
"i in zip(lists[4::2],lists[2:-1:2])] if all(time > 0.8 for time in timestamp) and len(result)",
"from spoof_struct import send_packet import dpkt, socket, subprocess from collections import defaultdict import",
"import time import cPickle as pickle import itertools src_ip = '192.168.100.128' spoof_ip =",
"ip: \"+ip) f4.close() f3 = open( \"reflector_candidate.pickle\", \"wb\" ) pickle.dump( reflector_candidate, f3) f3.close()",
"\" port: \"+str(port)+\"\\n\") f2.write(\"respond to ip: \"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4",
"#for ip, id_list in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\" id: \"+str(id_list)+\"\\n\") #f.close() if __name__",
"as pickle import itertools src_ip = '192.168.100.128' spoof_ip = '192.168.22.21' src_port = 54024",
"i in range(30): # for ip, port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) #",
"for ip, port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\")",
"= parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\") for ip,port in parse_ip.items(): if",
"\"+ip+ \" port: \"+str(ipid_map[ip][0])+\"\\n\") f1.close() f2.close() f4 = open(\"cand\",\"w+\") reflector_candidate = {} for",
"src_port = 54024 pcap_name = \"filter.pcap\" ipid_map={} def parse_pcap(file_n): f = open(file_n) pcap",
"and (sum(result)/len(result)) < 6: reflector_candidate[ip] = lists[0] f4.write(\"respond to ip: \"+ip) f4.close() f3",
"f = open(file_n) pcap = dpkt.pcap.Reader(f) for ts, buf in pcap: eth =",
"f2 = open(\"diff_port\",\"w+\") for ip,port in parse_ip.items(): if ip not in ipid_map: f1.write(ip+\"\\n\")",
"= open(\"diff_port\",\"w+\") for ip,port in parse_ip.items(): if ip not in ipid_map: f1.write(ip+\"\\n\") elif",
"#for i in range(30): # for ip, port in parse_ip.items(): #send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1)",
"= '192.168.100.128' spoof_ip = '192.168.22.21' src_port = 54024 pcap_name = \"filter.pcap\" ipid_map={} def",
"ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data",
"0.8 for time in timestamp) and len(result) <= 29 and len(result) >20 and",
"exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM) #time.sleep(1) #parse_pcap(pcap_name) #f = open(\"result_measure.txt\",\"w+\") #for ip, id_list in",
"db def main(): parse_ip = parse_candidate(\"ip_port_record.pickle\") ipid_map = parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\") f2",
"= {} for ip,lists in ipid_map.items(): result = [j-i for j, i in",
"#send_packet(src_ip,src_port,ip,port,1,1) # send_packet(spoof_ip,src_port,ip,port,1,1) # print(\"ip: \"+ip+\" id: \"+str(port)+\"\\n\") # exit(1) # time.sleep(1) #p.send_signal(subprocess.signal.SIGTERM)",
") pickle.dump( reflector_candidate, f3) f3.close() print(reflector_candidate) #for i in range(30): # for ip,",
"id_list in ipid_map.iteritems(): # f.write(\"ip: \"+ip+\" id: \"+str(id_list)+\"\\n\") #f.close() if __name__ == \"__main__\":",
"time in timestamp) and len(result) <= 29 and len(result) >20 and (sum(result)/len(result))>0 and",
"port != ipid_map[ip][0]: f2.write(\"request to ip: \"+ip+ \" port: \"+str(port)+\"\\n\") f2.write(\"respond to ip:",
"ip,lists in ipid_map.items(): result = [j-i for j, i in zip(lists[3::2],lists[1:-2:2])] timestamp =",
"import defaultdict import time import cPickle as pickle import itertools src_ip = '192.168.100.128'",
"collections import defaultdict import time import cPickle as pickle import itertools src_ip =",
"= dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data #src_addr = socket.inet_ntoa(ip.src) if eth.type",
"= '192.168.22.21' src_port = 54024 pcap_name = \"filter.pcap\" ipid_map={} def parse_pcap(file_n): f =",
"itertools src_ip = '192.168.100.128' spoof_ip = '192.168.22.21' src_port = 54024 pcap_name = \"filter.pcap\"",
"parse_candidate(\"save.p\") f1 = open(\"not_found\",\"w+\") f2 = open(\"diff_port\",\"w+\") for ip,port in parse_ip.items(): if ip"
] |
[
"from ralph.accounts.tests.factories import RegionFactory, UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase",
"ValidationError from django.core.urlresolvers import reverse from ralph.accounts.tests.factories import RegionFactory, UserFactory from ralph.back_office.tests.factories import",
"def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp",
"licence.' ) ): base_object_licence.clean() class LicenceTest(RalphTestCase): def setUp(self): super().setUp() self.licence_1 = LicenceFactory(number_bought=3) self.licence_2",
"LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1) self.user_1 = UserFactory() self.bo_asset = BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with",
"Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence",
"form.fields['service_env'].required ) def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,)",
"import reverse from ralph.accounts.tests.factories import RegionFactory, UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests",
"from ralph.licences.tests.factories import LicenceFactory from ralph.tests import RalphTestCase from ralph.tests.mixins import ClientMixin class",
"import BaseObjectLicence, Licence, LicenceUser from ralph.licences.tests.factories import LicenceFactory from ralph.tests import RalphTestCase from",
"region than licence.' ) ): base_object_licence.clean() class LicenceTest(RalphTestCase): def setUp(self): super().setUp() self.licence_1 =",
"self.licence_1 = LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1) self.user_1 = UserFactory() self.bo_asset = BackOfficeAssetFactory() def",
"self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user())",
"self.bo_asset = BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_1.pk,",
"django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from ralph.accounts.tests.factories import RegionFactory, UserFactory from",
"flat=True ), [self.licence_1.pk, self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1, ) LicenceUser.objects.create(",
"from ralph.tests import RalphTestCase from ralph.tests.mixins import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp()",
"follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required ) def test_depreciation_rate_not_required(self):",
"base_object_licence.licence = self.licence_de base_object_licence.base_object = self.bo_asset with self.assertRaisesRegex( ValidationError, ( 'Asset region is",
"ValidationError, ( 'Asset region is in a different region than licence.' ) ):",
"self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required ) def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user())",
"super().setUp() self.region_pl = RegionFactory(name='pl') self.region_de = RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl)",
"coding: utf-8 -*- from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from ralph.accounts.tests.factories",
"LicenceTest(RalphTestCase): def setUp(self): super().setUp() self.licence_1 = LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1) self.user_1 = UserFactory()",
"from django.core.urlresolvers import reverse from ralph.accounts.tests.factories import RegionFactory, UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory",
"ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp() self.region_pl = RegionFactory(name='pl') self.region_de = RegionFactory(name='de') self.licence_de",
"BaseObjectLicence, Licence, LicenceUser from ralph.licences.tests.factories import LicenceFactory from ralph.tests import RalphTestCase from ralph.tests.mixins",
"ralph.licences.tests.factories import LicenceFactory from ralph.tests import RalphTestCase from ralph.tests.mixins import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase):",
") LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2 ) with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ),",
"ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase from ralph.licences.models import BaseObjectLicence, Licence, LicenceUser",
"from ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase from ralph.licences.models import BaseObjectLicence, Licence,",
"def setUp(self): super().setUp() self.licence_1 = LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1) self.user_1 = UserFactory() self.bo_asset",
"self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self):",
"args=(licence.pk,) ) resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('service_env', form.fields)",
"ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) )",
"import RegionFactory, UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase from ralph.licences.models",
"quantity=1, ) LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2 ) with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True",
"reverse from ralph.accounts.tests.factories import RegionFactory, UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests import",
"BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase from ralph.licences.models import BaseObjectLicence, Licence, LicenceUser from ralph.licences.tests.factories",
"reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form",
"class LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change',",
"self.assertFalse( form.fields['service_env'].required ) def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change',",
"flat=True ), [self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory()",
"class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp() self.region_pl = RegionFactory(name='pl') self.region_de = RegionFactory(name='de') self.licence_de =",
"ralph.accounts.tests.factories import RegionFactory, UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase from",
"ralph.tests.mixins import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp() self.region_pl = RegionFactory(name='pl') self.region_de =",
"= RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence = BaseObjectLicence()",
"RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence = BaseObjectLicence() base_object_licence.licence",
"setUp(self): super().setUp() self.licence_1 = LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1) self.user_1 = UserFactory() self.bo_asset =",
") def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1, ) LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2 )",
"[self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url =",
"setUp(self): super().setUp() self.region_pl = RegionFactory(name='pl') self.region_de = RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset =",
"django.core.urlresolvers import reverse from ralph.accounts.tests.factories import RegionFactory, UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory from",
"def setUp(self): super().setUp() self.region_pl = RegionFactory(name='pl') self.region_de = RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset",
"= LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1) self.user_1 = UserFactory() self.bo_asset = BackOfficeAssetFactory() def test_get_autocomplete_queryset(self):",
"'pk', flat=True ), [self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence =",
"region is in a different region than licence.' ) ): base_object_licence.clean() class LicenceTest(RalphTestCase):",
"with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase, ClientMixin): def",
"import ValidationError from django.core.urlresolvers import reverse from ralph.accounts.tests.factories import RegionFactory, UserFactory from ralph.back_office.tests.factories",
"= reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form =",
"with self.assertRaisesRegex( ValidationError, ( 'Asset region is in a different region than licence.'",
"base_object_licence.clean() class LicenceTest(RalphTestCase): def setUp(self): super().setUp() self.licence_1 = LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1) self.user_1",
"BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp() self.region_pl = RegionFactory(name='pl') self.region_de = RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de)",
"utf-8 -*- from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from ralph.accounts.tests.factories import",
"= self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required )",
"RegionFactory(name='pl') self.region_de = RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence",
") def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) )",
"BaseObjectLicence() base_object_licence.licence = self.licence_de base_object_licence.base_object = self.bo_asset with self.assertRaisesRegex( ValidationError, ( 'Asset region",
"test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1, ) LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2 ) with self.assertNumQueries(2):",
"<filename>src/ralph/licences/tests/tests_models.py # -*- coding: utf-8 -*- from django.core.exceptions import ValidationError from django.core.urlresolvers import",
"LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence = BaseObjectLicence() base_object_licence.licence = self.licence_de base_object_licence.base_object",
"BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1, ) LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2 ) with self.assertNumQueries(2): self.assertCountEqual(",
"import RalphTestCase from ralph.tests.mixins import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp() self.region_pl =",
"= UserFactory() self.bo_asset = BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True",
"[self.licence_1.pk, self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1, ) LicenceUser.objects.create( user=self.user_1, licence=self.licence_1,",
"user=self.user_1, licence=self.licence_1, quantity=2 ) with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_2.pk] )",
"import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp() self.region_pl = RegionFactory(name='pl') self.region_de = RegionFactory(name='de')",
"= LicenceFactory(number_bought=1) self.user_1 = UserFactory() self.bo_asset = BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual(",
"LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2 ) with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_2.pk]",
"= LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence = BaseObjectLicence() base_object_licence.licence = self.licence_de",
"form.fields) self.assertFalse( form.fields['service_env'].required ) def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse(",
"LicenceFactory(number_bought=1) self.user_1 = UserFactory() self.bo_asset = BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list(",
"= resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required ) def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory()",
"self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_1.pk, self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset,",
"( 'Asset region is in a different region than licence.' ) ): base_object_licence.clean()",
"self.licence_2 = LicenceFactory(number_bought=1) self.user_1 = UserFactory() self.bo_asset = BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with self.assertNumQueries(2):",
") class LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse(",
"= LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code,",
"ralph.licences.models import BaseObjectLicence, Licence, LicenceUser from ralph.licences.tests.factories import LicenceFactory from ralph.tests import RalphTestCase",
"-*- from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from ralph.accounts.tests.factories import RegionFactory,",
"from ralph.lib.transitions.tests import TransitionTestCase from ralph.licences.models import BaseObjectLicence, Licence, LicenceUser from ralph.licences.tests.factories import",
"'Asset region is in a different region than licence.' ) ): base_object_licence.clean() class",
"= BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_1.pk, self.licence_2.pk]",
") with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase, ClientMixin):",
"import LicenceFactory from ralph.tests import RalphTestCase from ralph.tests.mixins import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def",
"self.licence_de base_object_licence.base_object = self.bo_asset with self.assertRaisesRegex( ValidationError, ( 'Asset region is in a",
"resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required",
"def test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_1.pk, self.licence_2.pk] ) def",
"import BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase from ralph.licences.models import BaseObjectLicence, Licence, LicenceUser from",
"200) form = resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required ) def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence",
"LicenceFactory from ralph.tests import RalphTestCase from ralph.tests.mixins import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self):",
"UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase from ralph.licences.models import BaseObjectLicence,",
"with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_1.pk, self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create(",
") ): base_object_licence.clean() class LicenceTest(RalphTestCase): def setUp(self): super().setUp() self.licence_1 = LicenceFactory(number_bought=3) self.licence_2 =",
"RalphTestCase from ralph.tests.mixins import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp() self.region_pl = RegionFactory(name='pl')",
"# -*- coding: utf-8 -*- from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse",
"self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_1.pk, self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1,",
"LicenceUser from ralph.licences.tests.factories import LicenceFactory from ralph.tests import RalphTestCase from ralph.tests.mixins import ClientMixin",
"def test_region_validate(self): base_object_licence = BaseObjectLicence() base_object_licence.licence = self.licence_de base_object_licence.base_object = self.bo_asset with self.assertRaisesRegex(",
"from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from ralph.accounts.tests.factories import RegionFactory, UserFactory",
"TransitionTestCase from ralph.licences.models import BaseObjectLicence, Licence, LicenceUser from ralph.licences.tests.factories import LicenceFactory from ralph.tests",
"self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required ) def",
"test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp =",
"self.region_de = RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence =",
"self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence = BaseObjectLicence() base_object_licence.licence = self.licence_de base_object_licence.base_object =",
"UserFactory() self.bo_asset = BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ),",
"import TransitionTestCase from ralph.licences.models import BaseObjectLicence, Licence, LicenceUser from ralph.licences.tests.factories import LicenceFactory from",
"= self.bo_asset with self.assertRaisesRegex( ValidationError, ( 'Asset region is in a different region",
"licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp = self.client.get(url, follow=True)",
"= BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence = BaseObjectLicence() base_object_licence.licence = self.licence_de base_object_licence.base_object = self.bo_asset",
"in a different region than licence.' ) ): base_object_licence.clean() class LicenceTest(RalphTestCase): def setUp(self):",
"), [self.licence_1.pk, self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1, ) LicenceUser.objects.create( user=self.user_1,",
"RegionFactory, UserFactory from ralph.back_office.tests.factories import BackOfficeAssetFactory from ralph.lib.transitions.tests import TransitionTestCase from ralph.licences.models import",
"): base_object_licence.clean() class LicenceTest(RalphTestCase): def setUp(self): super().setUp() self.licence_1 = LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1)",
"LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200)",
"= RegionFactory(name='pl') self.region_de = RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self):",
"base_object_licence.base_object = self.bo_asset with self.assertRaisesRegex( ValidationError, ( 'Asset region is in a different",
"def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1, ) LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2 ) with",
"licence=self.licence_1, quantity=1, ) LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2 ) with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk',",
"= self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('depreciation_rate', form.fields) self.assertFalse( form.fields['depreciation_rate'].required )",
"base_object_licence = BaseObjectLicence() base_object_licence.licence = self.licence_de base_object_licence.base_object = self.bo_asset with self.assertRaisesRegex( ValidationError, (",
"self.bo_asset with self.assertRaisesRegex( ValidationError, ( 'Asset region is in a different region than",
"-*- coding: utf-8 -*- from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from",
"self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp = self.client.get(url,",
"form = resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required ) def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence =",
"'admin:licences_licence_change', args=(licence.pk,) ) resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('service_env',",
"than licence.' ) ): base_object_licence.clean() class LicenceTest(RalphTestCase): def setUp(self): super().setUp() self.licence_1 = LicenceFactory(number_bought=3)",
"'admin:licences_licence_change', args=(licence.pk,) ) resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('depreciation_rate',",
"= self.licence_de base_object_licence.base_object = self.bo_asset with self.assertRaisesRegex( ValidationError, ( 'Asset region is in",
"def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp",
"ralph.lib.transitions.tests import TransitionTestCase from ralph.licences.models import BaseObjectLicence, Licence, LicenceUser from ralph.licences.tests.factories import LicenceFactory",
"resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('depreciation_rate', form.fields) self.assertFalse( form.fields['depreciation_rate'].required",
"self.assertRaisesRegex( ValidationError, ( 'Asset region is in a different region than licence.' )",
"different region than licence.' ) ): base_object_licence.clean() class LicenceTest(RalphTestCase): def setUp(self): super().setUp() self.licence_1",
"test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_1.pk, self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self):",
") resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('depreciation_rate', form.fields) self.assertFalse(",
"self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1, ) LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2",
"Licence, LicenceUser from ralph.licences.tests.factories import LicenceFactory from ralph.tests import RalphTestCase from ralph.tests.mixins import",
"), [self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url",
"LicenceFormTest(TransitionTestCase, ClientMixin): def test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,)",
"'pk', flat=True ), [self.licence_1.pk, self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1, )",
"url = reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form",
"a different region than licence.' ) ): base_object_licence.clean() class LicenceTest(RalphTestCase): def setUp(self): super().setUp()",
"super().setUp() self.licence_1 = LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1) self.user_1 = UserFactory() self.bo_asset = BackOfficeAssetFactory()",
") resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse(",
"test_region_validate(self): base_object_licence = BaseObjectLicence() base_object_licence.licence = self.licence_de base_object_licence.base_object = self.bo_asset with self.assertRaisesRegex( ValidationError,",
"BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence = BaseObjectLicence() base_object_licence.licence = self.licence_de base_object_licence.base_object = self.bo_asset with",
"resp.context['adminform'].form self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required ) def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url",
"test_service_env_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url = reverse( 'admin:licences_licence_change', args=(licence.pk,) ) resp =",
"self.region_pl = RegionFactory(name='pl') self.region_de = RegionFactory(name='de') self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def",
"class LicenceTest(RalphTestCase): def setUp(self): super().setUp() self.licence_1 = LicenceFactory(number_bought=3) self.licence_2 = LicenceFactory(number_bought=1) self.user_1 =",
"= BaseObjectLicence() base_object_licence.licence = self.licence_de base_object_licence.base_object = self.bo_asset with self.assertRaisesRegex( ValidationError, ( 'Asset",
"args=(licence.pk,) ) resp = self.client.get(url, follow=True) self.assertEqual(resp.status_code, 200) form = resp.context['adminform'].form self.assertIn('depreciation_rate', form.fields)",
"licence=self.licence_1, quantity=2 ) with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_2.pk] ) class",
"self.licence_de = LicenceFactory(region=self.region_de) self.bo_asset = BackOfficeAssetFactory(region=self.region_pl) def test_region_validate(self): base_object_licence = BaseObjectLicence() base_object_licence.licence =",
"ralph.tests import RalphTestCase from ralph.tests.mixins import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp() self.region_pl",
"Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_1.pk, self.licence_2.pk] ) def test_get_autocomplete_queryset_all_used(self): BaseObjectLicence.objects.create( base_object=self.bo_asset, licence=self.licence_1, quantity=1,",
"base_object=self.bo_asset, licence=self.licence_1, quantity=1, ) LicenceUser.objects.create( user=self.user_1, licence=self.licence_1, quantity=2 ) with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list(",
"is in a different region than licence.' ) ): base_object_licence.clean() class LicenceTest(RalphTestCase): def",
"self.user_1 = UserFactory() self.bo_asset = BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk',",
"BackOfficeAssetFactory() def test_get_autocomplete_queryset(self): with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_1.pk, self.licence_2.pk] )",
"from ralph.licences.models import BaseObjectLicence, Licence, LicenceUser from ralph.licences.tests.factories import LicenceFactory from ralph.tests import",
"quantity=2 ) with self.assertNumQueries(2): self.assertCountEqual( Licence.get_autocomplete_queryset().values_list( 'pk', flat=True ), [self.licence_2.pk] ) class LicenceFormTest(TransitionTestCase,",
"self.assertIn('service_env', form.fields) self.assertFalse( form.fields['service_env'].required ) def test_depreciation_rate_not_required(self): self.assertTrue(self.login_as_user()) licence = LicenceFactory() url =",
"from ralph.tests.mixins import ClientMixin class BaseObjectLicenceCleanTest(RalphTestCase): def setUp(self): super().setUp() self.region_pl = RegionFactory(name='pl') self.region_de"
] |
[
"the same row-traversing order as they were. If the reshape operation with given",
"of the original matrix in the same row-traversing order as they were. If",
"new reshaped matrix; Otherwise, output the original matrix. Example 1: Input: mat =",
"1 <= r, c <= 300 Solution-: class Solution: def matrixReshape(self, mat: List[List[int]],",
"new_mat = [[0]*c for _ in range(r)] for i in range(r): for j",
"j in range(M): q.append(mat[i][j]) new_mat = [[0]*c for _ in range(r)] for i",
"different size r x c keeping its original data. You are given an",
"x c keeping its original data. You are given an m x n",
"the number of rows and the number of columns of the wanted reshaped",
"If the reshape operation with given parameters is possible and legal, output the",
"1 <= m, n <= 100 -1000 <= mat[i][j] <= 1000 1 <=",
"Output: [[1,2,3,4]] Example 2: Input: mat = [[1,2],[3,4]], r = 2, c =",
"and c representing the number of rows and the number of columns of",
"m x n matrix into a new one with a different size r",
"Example 2: Input: mat = [[1,2],[3,4]], r = 2, c = 4 Output:",
"r: int, c: int) -> List[List[int]]: N = len(mat) M = len(mat[0]) if",
"are given an m x n matrix mat and two integers r and",
"class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: N",
"data. You are given an m x n matrix mat and two integers",
"function called reshape which can reshape an m x n matrix into a",
"c <= 300 Solution-: class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c:",
"in range(r)] for i in range(r): for j in range(c): new_mat[i][j] = q.pop(0)",
"the original matrix in the same row-traversing order as they were. If the",
"Example 1: Input: mat = [[1,2],[3,4]], r = 1, c = 4 Output:",
"i in range(N): for j in range(M): q.append(mat[i][j]) new_mat = [[0]*c for _",
"reshaped matrix should be filled with all the elements of the original matrix",
"return mat q = [] for i in range(N): for j in range(M):",
"reshape which can reshape an m x n matrix into a new one",
"of the wanted reshaped matrix. The reshaped matrix should be filled with all",
"== mat.length n == mat[i].length 1 <= m, n <= 100 -1000 <=",
"-> List[List[int]]: N = len(mat) M = len(mat[0]) if r*c != N*M: return",
"4 Output: [[1,2,3,4]] Example 2: Input: mat = [[1,2],[3,4]], r = 2, c",
"-1000 <= mat[i][j] <= 1000 1 <= r, c <= 300 Solution-: class",
"same row-traversing order as they were. If the reshape operation with given parameters",
"and legal, output the new reshaped matrix; Otherwise, output the original matrix. Example",
"in range(M): q.append(mat[i][j]) new_mat = [[0]*c for _ in range(r)] for i in",
"mat and two integers r and c representing the number of rows and",
"of rows and the number of columns of the wanted reshaped matrix. The",
"size r x c keeping its original data. You are given an m",
"mat = [[1,2],[3,4]], r = 2, c = 4 Output: [[1,2],[3,4]] Constraints: m",
"matrix mat and two integers r and c representing the number of rows",
"original matrix in the same row-traversing order as they were. If the reshape",
"<= 1000 1 <= r, c <= 300 Solution-: class Solution: def matrixReshape(self,",
"range(r)] for i in range(r): for j in range(c): new_mat[i][j] = q.pop(0) return",
"300 Solution-: class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int) ->",
"the wanted reshaped matrix. The reshaped matrix should be filled with all the",
"Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: N =",
"the original matrix. Example 1: Input: mat = [[1,2],[3,4]], r = 1, c",
"= 1, c = 4 Output: [[1,2,3,4]] Example 2: Input: mat = [[1,2],[3,4]],",
"n <= 100 -1000 <= mat[i][j] <= 1000 1 <= r, c <=",
"Input: mat = [[1,2],[3,4]], r = 2, c = 4 Output: [[1,2],[3,4]] Constraints:",
"an m x n matrix into a new one with a different size",
"== mat[i].length 1 <= m, n <= 100 -1000 <= mat[i][j] <= 1000",
"N = len(mat) M = len(mat[0]) if r*c != N*M: return mat q",
"!= N*M: return mat q = [] for i in range(N): for j",
"matrix in the same row-traversing order as they were. If the reshape operation",
"which can reshape an m x n matrix into a new one with",
"for j in range(M): q.append(mat[i][j]) new_mat = [[0]*c for _ in range(r)] for",
"= len(mat[0]) if r*c != N*M: return mat q = [] for i",
"reshaped matrix; Otherwise, output the original matrix. Example 1: Input: mat = [[1,2],[3,4]],",
"called reshape which can reshape an m x n matrix into a new",
"rows and the number of columns of the wanted reshaped matrix. The reshaped",
"<= 100 -1000 <= mat[i][j] <= 1000 1 <= r, c <= 300",
"<= mat[i][j] <= 1000 1 <= r, c <= 300 Solution-: class Solution:",
"= [[1,2],[3,4]], r = 1, c = 4 Output: [[1,2,3,4]] Example 2: Input:",
"The reshaped matrix should be filled with all the elements of the original",
"there is a handy function called reshape which can reshape an m x",
"mat q = [] for i in range(N): for j in range(M): q.append(mat[i][j])",
"Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 100",
"int, c: int) -> List[List[int]]: N = len(mat) M = len(mat[0]) if r*c",
"= 4 Output: [[1,2],[3,4]] Constraints: m == mat.length n == mat[i].length 1 <=",
"r, c <= 300 Solution-: class Solution: def matrixReshape(self, mat: List[List[int]], r: int,",
"new one with a different size r x c keeping its original data.",
"its original data. You are given an m x n matrix mat and",
"n matrix into a new one with a different size r x c",
"c representing the number of rows and the number of columns of the",
"Otherwise, output the original matrix. Example 1: Input: mat = [[1,2],[3,4]], r =",
"be filled with all the elements of the original matrix in the same",
"a new one with a different size r x c keeping its original",
"x n matrix mat and two integers r and c representing the number",
"q.append(mat[i][j]) new_mat = [[0]*c for _ in range(r)] for i in range(r): for",
"<= m, n <= 100 -1000 <= mat[i][j] <= 1000 1 <= r,",
"the number of columns of the wanted reshaped matrix. The reshaped matrix should",
"original data. You are given an m x n matrix mat and two",
"output the new reshaped matrix; Otherwise, output the original matrix. Example 1: Input:",
"n matrix mat and two integers r and c representing the number of",
"n == mat[i].length 1 <= m, n <= 100 -1000 <= mat[i][j] <=",
"matrix should be filled with all the elements of the original matrix in",
"mat: List[List[int]], r: int, c: int) -> List[List[int]]: N = len(mat) M =",
"given parameters is possible and legal, output the new reshaped matrix; Otherwise, output",
"and two integers r and c representing the number of rows and the",
"the new reshaped matrix; Otherwise, output the original matrix. Example 1: Input: mat",
"is a handy function called reshape which can reshape an m x n",
"matrix; Otherwise, output the original matrix. Example 1: Input: mat = [[1,2],[3,4]], r",
"In MATLAB, there is a handy function called reshape which can reshape an",
"reshape an m x n matrix into a new one with a different",
"columns of the wanted reshaped matrix. The reshaped matrix should be filled with",
"reshaped matrix. The reshaped matrix should be filled with all the elements of",
"c keeping its original data. You are given an m x n matrix",
"[] for i in range(N): for j in range(M): q.append(mat[i][j]) new_mat = [[0]*c",
"wanted reshaped matrix. The reshaped matrix should be filled with all the elements",
"2: Input: mat = [[1,2],[3,4]], r = 2, c = 4 Output: [[1,2],[3,4]]",
"def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: N = len(mat)",
"of columns of the wanted reshaped matrix. The reshaped matrix should be filled",
"List[List[int]], r: int, c: int) -> List[List[int]]: N = len(mat) M = len(mat[0])",
"c = 4 Output: [[1,2],[3,4]] Constraints: m == mat.length n == mat[i].length 1",
"two integers r and c representing the number of rows and the number",
"is possible and legal, output the new reshaped matrix; Otherwise, output the original",
"N*M: return mat q = [] for i in range(N): for j in",
"100 -1000 <= mat[i][j] <= 1000 1 <= r, c <= 300 Solution-:",
"You are given an m x n matrix mat and two integers r",
"integers r and c representing the number of rows and the number of",
"= [[0]*c for _ in range(r)] for i in range(r): for j in",
"one with a different size r x c keeping its original data. You",
"range(M): q.append(mat[i][j]) new_mat = [[0]*c for _ in range(r)] for i in range(r):",
"for i in range(N): for j in range(M): q.append(mat[i][j]) new_mat = [[0]*c for",
"number of rows and the number of columns of the wanted reshaped matrix.",
"all the elements of the original matrix in the same row-traversing order as",
"int) -> List[List[int]]: N = len(mat) M = len(mat[0]) if r*c != N*M:",
"possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.",
"r x c keeping its original data. You are given an m x",
"as they were. If the reshape operation with given parameters is possible and",
"matrix into a new one with a different size r x c keeping",
"were. If the reshape operation with given parameters is possible and legal, output",
"= [[1,2],[3,4]], r = 2, c = 4 Output: [[1,2],[3,4]] Constraints: m ==",
"r and c representing the number of rows and the number of columns",
"[[1,2],[3,4]], r = 1, c = 4 Output: [[1,2,3,4]] Example 2: Input: mat",
"should be filled with all the elements of the original matrix in the",
"m, n <= 100 -1000 <= mat[i][j] <= 1000 1 <= r, c",
"with a different size r x c keeping its original data. You are",
"a handy function called reshape which can reshape an m x n matrix",
"mat[i][j] <= 1000 1 <= r, c <= 300 Solution-: class Solution: def",
"order as they were. If the reshape operation with given parameters is possible",
"c = 4 Output: [[1,2,3,4]] Example 2: Input: mat = [[1,2],[3,4]], r =",
"for i in range(r): for j in range(c): new_mat[i][j] = q.pop(0) return new_mat",
"[[1,2],[3,4]] Constraints: m == mat.length n == mat[i].length 1 <= m, n <=",
"[[0]*c for _ in range(r)] for i in range(r): for j in range(c):",
"len(mat[0]) if r*c != N*M: return mat q = [] for i in",
"into a new one with a different size r x c keeping its",
"len(mat) M = len(mat[0]) if r*c != N*M: return mat q = []",
"Input: mat = [[1,2],[3,4]], r = 1, c = 4 Output: [[1,2,3,4]] Example",
"M = len(mat[0]) if r*c != N*M: return mat q = [] for",
"in the same row-traversing order as they were. If the reshape operation with",
"and the number of columns of the wanted reshaped matrix. The reshaped matrix",
"r = 1, c = 4 Output: [[1,2,3,4]] Example 2: Input: mat =",
"a different size r x c keeping its original data. You are given",
"filled with all the elements of the original matrix in the same row-traversing",
"q = [] for i in range(N): for j in range(M): q.append(mat[i][j]) new_mat",
"mat = [[1,2],[3,4]], r = 1, c = 4 Output: [[1,2,3,4]] Example 2:",
"number of columns of the wanted reshaped matrix. The reshaped matrix should be",
"4 Output: [[1,2],[3,4]] Constraints: m == mat.length n == mat[i].length 1 <= m,",
"can reshape an m x n matrix into a new one with a",
"with all the elements of the original matrix in the same row-traversing order",
"operation with given parameters is possible and legal, output the new reshaped matrix;",
"_ in range(r)] for i in range(r): for j in range(c): new_mat[i][j] =",
"<= 300 Solution-: class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int)",
"MATLAB, there is a handy function called reshape which can reshape an m",
"range(N): for j in range(M): q.append(mat[i][j]) new_mat = [[0]*c for _ in range(r)]",
"m == mat.length n == mat[i].length 1 <= m, n <= 100 -1000",
"[[1,2,3,4]] Example 2: Input: mat = [[1,2],[3,4]], r = 2, c = 4",
"original matrix. Example 1: Input: mat = [[1,2],[3,4]], r = 1, c =",
"[[1,2],[3,4]], r = 2, c = 4 Output: [[1,2],[3,4]] Constraints: m == mat.length",
"an m x n matrix mat and two integers r and c representing",
"matrix. The reshaped matrix should be filled with all the elements of the",
"2, c = 4 Output: [[1,2],[3,4]] Constraints: m == mat.length n == mat[i].length",
"<= r, c <= 300 Solution-: class Solution: def matrixReshape(self, mat: List[List[int]], r:",
"Output: [[1,2],[3,4]] Constraints: m == mat.length n == mat[i].length 1 <= m, n",
"1, c = 4 Output: [[1,2,3,4]] Example 2: Input: mat = [[1,2],[3,4]], r",
"parameters is possible and legal, output the new reshaped matrix; Otherwise, output the",
"for _ in range(r)] for i in range(r): for j in range(c): new_mat[i][j]",
"keeping its original data. You are given an m x n matrix mat",
"the reshape operation with given parameters is possible and legal, output the new",
"mat.length n == mat[i].length 1 <= m, n <= 100 -1000 <= mat[i][j]",
"r*c != N*M: return mat q = [] for i in range(N): for",
"c: int) -> List[List[int]]: N = len(mat) M = len(mat[0]) if r*c !=",
"row-traversing order as they were. If the reshape operation with given parameters is",
"1: Input: mat = [[1,2],[3,4]], r = 1, c = 4 Output: [[1,2,3,4]]",
"if r*c != N*M: return mat q = [] for i in range(N):",
"with given parameters is possible and legal, output the new reshaped matrix; Otherwise,",
"= 4 Output: [[1,2,3,4]] Example 2: Input: mat = [[1,2],[3,4]], r = 2,",
"List[List[int]]: N = len(mat) M = len(mat[0]) if r*c != N*M: return mat",
"reshape operation with given parameters is possible and legal, output the new reshaped",
"matrix. Example 1: Input: mat = [[1,2],[3,4]], r = 1, c = 4",
"matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: N = len(mat) M",
"= [] for i in range(N): for j in range(M): q.append(mat[i][j]) new_mat =",
"handy function called reshape which can reshape an m x n matrix into",
"in range(N): for j in range(M): q.append(mat[i][j]) new_mat = [[0]*c for _ in",
"Solution-: class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:",
"= 2, c = 4 Output: [[1,2],[3,4]] Constraints: m == mat.length n ==",
"elements of the original matrix in the same row-traversing order as they were.",
"mat[i].length 1 <= m, n <= 100 -1000 <= mat[i][j] <= 1000 1",
"r = 2, c = 4 Output: [[1,2],[3,4]] Constraints: m == mat.length n",
"output the original matrix. Example 1: Input: mat = [[1,2],[3,4]], r = 1,",
"they were. If the reshape operation with given parameters is possible and legal,",
"= len(mat) M = len(mat[0]) if r*c != N*M: return mat q =",
"m x n matrix mat and two integers r and c representing the",
"x n matrix into a new one with a different size r x",
"1000 1 <= r, c <= 300 Solution-: class Solution: def matrixReshape(self, mat:",
"given an m x n matrix mat and two integers r and c",
"legal, output the new reshaped matrix; Otherwise, output the original matrix. Example 1:",
"the elements of the original matrix in the same row-traversing order as they",
"representing the number of rows and the number of columns of the wanted"
] |
[
"'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for x in cat_ids] current_cat_id",
"1 entities = [] variables = pd.read_excel(xlsx, 'Variables') for idx, row in variables.iterrows():",
"local_id = str(row['VariableName']).strip() if '%' in local_id: local_id = local_id.replace('%', 'Percent') name =",
"[int(x) for x in cat_ids] current_cat_id = 1 while current_cat_id <= max(cat_ids): current_cats",
"cat_id = int(row['CategoryId']) cat_string = catid_strings[cat_id] entities.append({'Short ID': 'VZ:' + local_id, 'Label': name,",
"+ local_id, 'Label': name, 'Value': cat_string}) writer = csv.DictWriter(output_file, fieldnames=['Short ID', 'Label', 'Value'],",
"'\\n'.join(cat_strings) current_cat_id += 1 entities = [] variables = pd.read_excel(xlsx, 'Variables') for idx,",
"entities.append({'Short ID': 'VZ:' + local_id, 'Label': name, 'Value': cat_string}) writer = csv.DictWriter(output_file, fieldnames=['Short",
"= int(row['CategoryId']) cat_string = catid_strings[cat_id] entities.append({'Short ID': 'VZ:' + local_id, 'Label': name, 'Value':",
"if '%' in local_id: local_id = local_id.replace('%', 'Percent') name = str(row['Description']).strip() cat_id =",
"= int(row['CategoryValue']) label = str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value, label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id",
"= ArgumentParser() p.add_argument('input', type=str) p.add_argument('output', type=FileType('w')) args = p.parse_args() input_xlsx = args.input output_file",
"input_xlsx = args.input output_file = args.output xlsx = pd.ExcelFile(input_xlsx) catid_strings = {} var_categories",
"= '\\n'.join(cat_strings) current_cat_id += 1 entities = [] variables = pd.read_excel(xlsx, 'Variables') for",
"int(row['CategoryValue']) label = str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value, label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id +=",
"= args.input output_file = args.output xlsx = pd.ExcelFile(input_xlsx) catid_strings = {} var_categories =",
"= var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for x in cat_ids] current_cat_id = 1 while",
"type=str) p.add_argument('output', type=FileType('w')) args = p.parse_args() input_xlsx = args.input output_file = args.output xlsx",
"label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id += 1 entities = [] variables = pd.read_excel(xlsx,",
"name, 'Value': cat_string}) writer = csv.DictWriter(output_file, fieldnames=['Short ID', 'Label', 'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader()",
"= local_id.replace('%', 'Percent') name = str(row['Description']).strip() cat_id = int(row['CategoryId']) cat_string = catid_strings[cat_id] entities.append({'Short",
"= var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings = [] for idx, row in current_cats.iterrows(): cat_value",
"'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID': 'ID', 'Label': 'LABEL', 'Value': 'A value'}) #",
"Add validation writer.writerow({}) for entity in entities: writer.writerow(entity) output_file.close() if __name__ == '__main__':",
"current_cat_id += 1 entities = [] variables = pd.read_excel(xlsx, 'Variables') for idx, row",
"xlsx = pd.ExcelFile(input_xlsx) catid_strings = {} var_categories = pd.read_excel(xlsx, 'Variable Categories') cat_ids =",
"= 1 while current_cat_id <= max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings =",
"idx, row in current_cats.iterrows(): cat_value = int(row['CategoryValue']) label = str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value,",
"'ID', 'Label': 'LABEL', 'Value': 'A value'}) # TODO: Add validation writer.writerow({}) for entity",
"label = str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value, label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id += 1",
"row in current_cats.iterrows(): cat_value = int(row['CategoryValue']) label = str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value, label))",
"validation writer.writerow({}) for entity in entities: writer.writerow(entity) output_file.close() if __name__ == '__main__': main()",
"= [] variables = pd.read_excel(xlsx, 'Variables') for idx, row in variables.iterrows(): local_id =",
"= args.output xlsx = pd.ExcelFile(input_xlsx) catid_strings = {} var_categories = pd.read_excel(xlsx, 'Variable Categories')",
"in variables.iterrows(): local_id = str(row['VariableName']).strip() if '%' in local_id: local_id = local_id.replace('%', 'Percent')",
"str(row['Description']).strip() cat_id = int(row['CategoryId']) cat_string = catid_strings[cat_id] entities.append({'Short ID': 'VZ:' + local_id, 'Label':",
"'VZ:' + local_id, 'Label': name, 'Value': cat_string}) writer = csv.DictWriter(output_file, fieldnames=['Short ID', 'Label',",
"pd.read_excel(xlsx, 'Variables') for idx, row in variables.iterrows(): local_id = str(row['VariableName']).strip() if '%' in",
"= pd.read_excel(xlsx, 'Variables') for idx, row in variables.iterrows(): local_id = str(row['VariableName']).strip() if '%'",
"p.parse_args() input_xlsx = args.input output_file = args.output xlsx = pd.ExcelFile(input_xlsx) catid_strings = {}",
"= str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value, label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id += 1 entities",
"args = p.parse_args() input_xlsx = args.input output_file = args.output xlsx = pd.ExcelFile(input_xlsx) catid_strings",
"current_cat_id] cat_strings = [] for idx, row in current_cats.iterrows(): cat_value = int(row['CategoryValue']) label",
"'Label', 'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID': 'ID', 'Label': 'LABEL', 'Value': 'A value'})",
"str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value, label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id += 1 entities =",
"ID': 'VZ:' + local_id, 'Label': name, 'Value': cat_string}) writer = csv.DictWriter(output_file, fieldnames=['Short ID',",
"Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for x in cat_ids] current_cat_id =",
"cat_value = int(row['CategoryValue']) label = str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value, label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings)",
"while current_cat_id <= max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings = [] for",
"ID', 'Label', 'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID': 'ID', 'Label': 'LABEL', 'Value': 'A",
"'Value': cat_string}) writer = csv.DictWriter(output_file, fieldnames=['Short ID', 'Label', 'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short",
"= p.parse_args() input_xlsx = args.input output_file = args.output xlsx = pd.ExcelFile(input_xlsx) catid_strings =",
"cat_ids] current_cat_id = 1 while current_cat_id <= max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId'] == current_cat_id]",
"catid_strings[cat_id] entities.append({'Short ID': 'VZ:' + local_id, 'Label': name, 'Value': cat_string}) writer = csv.DictWriter(output_file,",
"ArgumentParser, FileType def main(): p = ArgumentParser() p.add_argument('input', type=str) p.add_argument('output', type=FileType('w')) args =",
"catid_strings = {} var_categories = pd.read_excel(xlsx, 'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids =",
"csv import pandas as pd from argparse import ArgumentParser, FileType def main(): p",
"[] variables = pd.read_excel(xlsx, 'Variables') for idx, row in variables.iterrows(): local_id = str(row['VariableName']).strip()",
"import pandas as pd from argparse import ArgumentParser, FileType def main(): p =",
"from argparse import ArgumentParser, FileType def main(): p = ArgumentParser() p.add_argument('input', type=str) p.add_argument('output',",
"# TODO: Add validation writer.writerow({}) for entity in entities: writer.writerow(entity) output_file.close() if __name__",
"cat_strings = [] for idx, row in current_cats.iterrows(): cat_value = int(row['CategoryValue']) label =",
"<= max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings = [] for idx, row",
"pandas as pd from argparse import ArgumentParser, FileType def main(): p = ArgumentParser()",
"entities = [] variables = pd.read_excel(xlsx, 'Variables') for idx, row in variables.iterrows(): local_id",
"'Label': 'LABEL', 'Value': 'A value'}) # TODO: Add validation writer.writerow({}) for entity in",
"'A value'}) # TODO: Add validation writer.writerow({}) for entity in entities: writer.writerow(entity) output_file.close()",
"= pd.read_excel(xlsx, 'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for x in",
"current_cats = var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings = [] for idx, row in current_cats.iterrows():",
"x in cat_ids] current_cat_id = 1 while current_cat_id <= max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId']",
"cat_string}) writer = csv.DictWriter(output_file, fieldnames=['Short ID', 'Label', 'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID':",
"idx, row in variables.iterrows(): local_id = str(row['VariableName']).strip() if '%' in local_id: local_id =",
"args.input output_file = args.output xlsx = pd.ExcelFile(input_xlsx) catid_strings = {} var_categories = pd.read_excel(xlsx,",
"= csv.DictWriter(output_file, fieldnames=['Short ID', 'Label', 'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID': 'ID', 'Label':",
"str(row['VariableName']).strip() if '%' in local_id: local_id = local_id.replace('%', 'Percent') name = str(row['Description']).strip() cat_id",
"current_cat_id = 1 while current_cat_id <= max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings",
"name = str(row['Description']).strip() cat_id = int(row['CategoryId']) cat_string = catid_strings[cat_id] entities.append({'Short ID': 'VZ:' +",
"type=FileType('w')) args = p.parse_args() input_xlsx = args.input output_file = args.output xlsx = pd.ExcelFile(input_xlsx)",
"pd.ExcelFile(input_xlsx) catid_strings = {} var_categories = pd.read_excel(xlsx, 'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids",
"lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID': 'ID', 'Label': 'LABEL', 'Value': 'A value'}) # TODO: Add",
"var_categories = pd.read_excel(xlsx, 'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for x",
"pd.read_excel(xlsx, 'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for x in cat_ids]",
"cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for x in cat_ids] current_cat_id = 1",
"local_id: local_id = local_id.replace('%', 'Percent') name = str(row['Description']).strip() cat_id = int(row['CategoryId']) cat_string =",
"<filename>src/convert/vukuzazi.py import csv import pandas as pd from argparse import ArgumentParser, FileType def",
"FileType def main(): p = ArgumentParser() p.add_argument('input', type=str) p.add_argument('output', type=FileType('w')) args = p.parse_args()",
"variables.iterrows(): local_id = str(row['VariableName']).strip() if '%' in local_id: local_id = local_id.replace('%', 'Percent') name",
"in local_id: local_id = local_id.replace('%', 'Percent') name = str(row['Description']).strip() cat_id = int(row['CategoryId']) cat_string",
"'Value': 'A value'}) # TODO: Add validation writer.writerow({}) for entity in entities: writer.writerow(entity)",
"args.output xlsx = pd.ExcelFile(input_xlsx) catid_strings = {} var_categories = pd.read_excel(xlsx, 'Variable Categories') cat_ids",
"cat_ids = [int(x) for x in cat_ids] current_cat_id = 1 while current_cat_id <=",
"import ArgumentParser, FileType def main(): p = ArgumentParser() p.add_argument('input', type=str) p.add_argument('output', type=FileType('w')) args",
"TODO: Add validation writer.writerow({}) for entity in entities: writer.writerow(entity) output_file.close() if __name__ ==",
"'Label': name, 'Value': cat_string}) writer = csv.DictWriter(output_file, fieldnames=['Short ID', 'Label', 'Value'], delimiter='\\t', lineterminator='\\n')",
"= {} var_categories = pd.read_excel(xlsx, 'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids = [int(x)",
"{1}'.format(cat_value, label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id += 1 entities = [] variables =",
"'Variables') for idx, row in variables.iterrows(): local_id = str(row['VariableName']).strip() if '%' in local_id:",
"local_id.replace('%', 'Percent') name = str(row['Description']).strip() cat_id = int(row['CategoryId']) cat_string = catid_strings[cat_id] entities.append({'Short ID':",
"csv.DictWriter(output_file, fieldnames=['Short ID', 'Label', 'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID': 'ID', 'Label': 'LABEL',",
"as pd from argparse import ArgumentParser, FileType def main(): p = ArgumentParser() p.add_argument('input',",
"[] for idx, row in current_cats.iterrows(): cat_value = int(row['CategoryValue']) label = str(row['Description']) cat_strings.append('{0}",
"int(row['CategoryId']) cat_string = catid_strings[cat_id] entities.append({'Short ID': 'VZ:' + local_id, 'Label': name, 'Value': cat_string})",
"'%' in local_id: local_id = local_id.replace('%', 'Percent') name = str(row['Description']).strip() cat_id = int(row['CategoryId'])",
"= [] for idx, row in current_cats.iterrows(): cat_value = int(row['CategoryValue']) label = str(row['Description'])",
"pd from argparse import ArgumentParser, FileType def main(): p = ArgumentParser() p.add_argument('input', type=str)",
"local_id, 'Label': name, 'Value': cat_string}) writer = csv.DictWriter(output_file, fieldnames=['Short ID', 'Label', 'Value'], delimiter='\\t',",
"'LABEL', 'Value': 'A value'}) # TODO: Add validation writer.writerow({}) for entity in entities:",
"in current_cats.iterrows(): cat_value = int(row['CategoryValue']) label = str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value, label)) catid_strings[current_cat_id]",
"for idx, row in current_cats.iterrows(): cat_value = int(row['CategoryValue']) label = str(row['Description']) cat_strings.append('{0} =",
"delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID': 'ID', 'Label': 'LABEL', 'Value': 'A value'}) # TODO:",
"+= 1 entities = [] variables = pd.read_excel(xlsx, 'Variables') for idx, row in",
"max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings = [] for idx, row in",
"value'}) # TODO: Add validation writer.writerow({}) for entity in entities: writer.writerow(entity) output_file.close() if",
"= {1}'.format(cat_value, label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id += 1 entities = [] variables",
"in cat_ids] current_cat_id = 1 while current_cat_id <= max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId'] ==",
"{} var_categories = pd.read_excel(xlsx, 'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for",
"= [int(x) for x in cat_ids] current_cat_id = 1 while current_cat_id <= max(cat_ids):",
"p.add_argument('input', type=str) p.add_argument('output', type=FileType('w')) args = p.parse_args() input_xlsx = args.input output_file = args.output",
"== current_cat_id] cat_strings = [] for idx, row in current_cats.iterrows(): cat_value = int(row['CategoryValue'])",
"'Percent') name = str(row['Description']).strip() cat_id = int(row['CategoryId']) cat_string = catid_strings[cat_id] entities.append({'Short ID': 'VZ:'",
"for x in cat_ids] current_cat_id = 1 while current_cat_id <= max(cat_ids): current_cats =",
"p.add_argument('output', type=FileType('w')) args = p.parse_args() input_xlsx = args.input output_file = args.output xlsx =",
"writer.writeheader() writer.writerow({'Short ID': 'ID', 'Label': 'LABEL', 'Value': 'A value'}) # TODO: Add validation",
"variables = pd.read_excel(xlsx, 'Variables') for idx, row in variables.iterrows(): local_id = str(row['VariableName']).strip() if",
"= str(row['VariableName']).strip() if '%' in local_id: local_id = local_id.replace('%', 'Percent') name = str(row['Description']).strip()",
"var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings = [] for idx, row in current_cats.iterrows(): cat_value =",
"current_cat_id <= max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings = [] for idx,",
"writer = csv.DictWriter(output_file, fieldnames=['Short ID', 'Label', 'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID': 'ID',",
"import csv import pandas as pd from argparse import ArgumentParser, FileType def main():",
"current_cats.iterrows(): cat_value = int(row['CategoryValue']) label = str(row['Description']) cat_strings.append('{0} = {1}'.format(cat_value, label)) catid_strings[current_cat_id] =",
"argparse import ArgumentParser, FileType def main(): p = ArgumentParser() p.add_argument('input', type=str) p.add_argument('output', type=FileType('w'))",
"output_file = args.output xlsx = pd.ExcelFile(input_xlsx) catid_strings = {} var_categories = pd.read_excel(xlsx, 'Variable",
"for idx, row in variables.iterrows(): local_id = str(row['VariableName']).strip() if '%' in local_id: local_id",
"= str(row['Description']).strip() cat_id = int(row['CategoryId']) cat_string = catid_strings[cat_id] entities.append({'Short ID': 'VZ:' + local_id,",
"ArgumentParser() p.add_argument('input', type=str) p.add_argument('output', type=FileType('w')) args = p.parse_args() input_xlsx = args.input output_file =",
"1 while current_cat_id <= max(cat_ids): current_cats = var_categories.loc[var_categories['CategoryId'] == current_cat_id] cat_strings = []",
"local_id = local_id.replace('%', 'Percent') name = str(row['Description']).strip() cat_id = int(row['CategoryId']) cat_string = catid_strings[cat_id]",
"def main(): p = ArgumentParser() p.add_argument('input', type=str) p.add_argument('output', type=FileType('w')) args = p.parse_args() input_xlsx",
"cat_string = catid_strings[cat_id] entities.append({'Short ID': 'VZ:' + local_id, 'Label': name, 'Value': cat_string}) writer",
"p = ArgumentParser() p.add_argument('input', type=str) p.add_argument('output', type=FileType('w')) args = p.parse_args() input_xlsx = args.input",
"catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id += 1 entities = [] variables = pd.read_excel(xlsx, 'Variables')",
"main(): p = ArgumentParser() p.add_argument('input', type=str) p.add_argument('output', type=FileType('w')) args = p.parse_args() input_xlsx =",
"cat_strings.append('{0} = {1}'.format(cat_value, label)) catid_strings[current_cat_id] = '\\n'.join(cat_strings) current_cat_id += 1 entities = []",
"= catid_strings[cat_id] entities.append({'Short ID': 'VZ:' + local_id, 'Label': name, 'Value': cat_string}) writer =",
"writer.writerow({'Short ID': 'ID', 'Label': 'LABEL', 'Value': 'A value'}) # TODO: Add validation writer.writerow({})",
"row in variables.iterrows(): local_id = str(row['VariableName']).strip() if '%' in local_id: local_id = local_id.replace('%',",
"ID': 'ID', 'Label': 'LABEL', 'Value': 'A value'}) # TODO: Add validation writer.writerow({}) for",
"= pd.ExcelFile(input_xlsx) catid_strings = {} var_categories = pd.read_excel(xlsx, 'Variable Categories') cat_ids = var_categories['CategoryId'].unique().tolist()",
"var_categories['CategoryId'].unique().tolist() cat_ids = [int(x) for x in cat_ids] current_cat_id = 1 while current_cat_id",
"fieldnames=['Short ID', 'Label', 'Value'], delimiter='\\t', lineterminator='\\n') writer.writeheader() writer.writerow({'Short ID': 'ID', 'Label': 'LABEL', 'Value':"
] |
[
"platform, api=None): \"\"\"Retrieve information about an influencer. Args: project_id (int): id of the",
"= api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id, platform=platform ) res_data = api.get(url, params=params) return",
"\"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id) data = api.post(url, data=parameter)",
"(RadarlyApi): Yields: Influencer: \"\"\" def _fetch_items(self): \"\"\"Get next range of influencers\"\"\" url =",
"RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id, platform=platform ) res_data = api.get(url,",
"self.project_id) for item in res_data['users'] ) div = self.total // self.search_param['limit'] reste =",
"API. See ``InfluencerParameter`` to see how to build this object. api (RadarlyApi): API",
"See ``InfluencerParameter`` to see how to build this object. This object must contain",
"to build this object. api (RadarlyApi): API used to performed the request. If",
"the influencer screen_name (str): display name on the social_accounts permalink (str): link to",
"project_id super().__init__() translator = dict( stats=parse_struct_stat ) if 'user' in data: super().add_data(data['user'], translator)",
"API will be used. Returns: list[Influencer]: \"\"\" api = api or RadarlyApi.get_default_api() url",
"\"\"\"Retrieve metrics data about the influencer from the API. Returns: dict: \"\"\" api",
"@classmethod def fetch(cls, project_id, parameter, api=None): \"\"\"Retrieve influencers list from a project. Args:",
"data['user'] super().add_data(data, translator) def __repr__(self): influ_id, platform = getattr(self, 'id'), getattr(self, 'platform') return",
"'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def find(cls, project_id, influencer_id, platform, api=None): \"\"\"Retrieve information",
"params = dict( platform=self['platform'], uid=self['id'] ) url = api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url, params=params)['metrics']",
"api (RadarlyApi): Yields: Influencer: \"\"\" def _fetch_items(self): \"\"\"Get next range of influencers\"\"\" url",
"api.router.influencer['search'].format(project_id=project_id) data = api.post(url, data=parameter) return [cls(item, project_id) for item in data['users']] @classmethod",
"published by the follower in your project. stats (dict): statitics about the influencers",
"find(cls, project_id, influencer_id, platform, api=None): \"\"\"Retrieve information about an influencer. Args: project_id (int):",
"\"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id,",
"which yields all influencers matching some payload. Args: search_param (InfluencerParameter): project_id (int): api",
"value of this object are available as value associated to a key, or",
"for the influencer platform (str): origin platform of the influencer screen_name (str): display",
"the social_account followers_count (int): numbers of followers of the influencer count (int): number",
"to the API. See ``InfluencerParameter`` to see how to build this object. api",
"in data: super().add_data(data['user'], translator) del data['user'] super().add_data(data, translator) def __repr__(self): influ_id, platform =",
"See ``InfluencerParameter`` to see how to build this object. api (RadarlyApi): API used",
"= self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url, data=self.search_param) self.total = 1000 self._items = ( Influencer(item,",
"= api.get(url, params=params) return Influencer(res_data, project_id) @classmethod def fetch(cls, project_id, parameter, api=None): \"\"\"Retrieve",
"numbers of followers of the influencer count (int): number of documents published by",
"the influencers publications \"\"\" def __init__(self, data, project_id): self.project_id = project_id super().__init__() translator",
"super().__init__() translator = dict( stats=parse_struct_stat ) if 'user' in data: super().add_data(data['user'], translator) del",
"be used. Returns: list[Influencer]: \"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id)",
"functions in order to help you to understand who are the influencers in",
"parameter sent as payload to the API. See ``InfluencerParameter`` to see how to",
"object may change depending on the platform Args: id (str): identifier for the",
"follower in your project. stats (dict): statitics about the influencers publications \"\"\" def",
"if 'user' in data: super().add_data(data['user'], translator) del data['user'] super().add_data(data, translator) def __repr__(self): influ_id,",
"self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url, data=self.search_param) self.total = 1000 self._items = ( Influencer(item, self.project_id)",
"(dict): statitics about the influencers publications \"\"\" def __init__(self, data, project_id): self.project_id =",
"are the influencers in your project and consequently understand your audience. \"\"\" from",
"the default API will be used. Returns: Influencer: \"\"\" api = api or",
"self.project_id = project_id super().__init__() translator = dict( stats=parse_struct_stat ) if 'user' in data:",
"data = api.post(url, data=parameter) return [cls(item, project_id) for item in data['users']] @classmethod def",
"how to build this object. api (RadarlyApi): API used to performed the request.",
"documents published by the follower in your project. stats (dict): statitics about the",
"project_id=project_id, api=api) def get_metrics(self, api=None): \"\"\"Retrieve metrics data about the influencer from the",
"GeneratorModel, SourceModel from .utils._internal import parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like object storing information about",
"api or RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id, platform=platform ) res_data",
"platform) @classmethod def find(cls, project_id, influencer_id, platform, api=None): \"\"\"Retrieve information about an influencer.",
"project influencer_id (int): id of the influencer platform (str): platform of the influencer",
"project_id (int): id of the project parameter (InfluencerParameter): parameter sent as payload to",
"Yields: Influencer: \"\"\" def _fetch_items(self): \"\"\"Get next range of influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id)",
"RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id) data = api.post(url, data=parameter) return [cls(item, project_id) for item",
"influencer in Radarly is an author of several publications who has a more-or-less",
"order to help you to understand who are the influencers in your project",
"a key, or as attribute of the instance. Here are some useful attributes:",
"RadarlyApi from .model import GeneratorModel, SourceModel from .utils._internal import parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like",
"parameter (InfluencerParameter): parameter sent as payload to the API. See ``InfluencerParameter`` to see",
"or as attribute of the instance. Here are some useful attributes: .. warning::",
"parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like object storing information about an influencer. The value of",
"used. Returns: list[Influencer]: \"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id) data",
"used to make the request. If None, the default API will be used.",
"the ``Influencer`` object may change depending on the platform Args: id (str): identifier",
"or RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id) data = api.post(url, data=parameter) return [cls(item, project_id) for",
"api=None): \"\"\"retrieve all influencers from a project. Args: project_id (int): identifier of a",
"project_id): self.project_id = project_id super().__init__() translator = dict( stats=parse_struct_stat ) if 'user' in",
"publications \"\"\" def __init__(self, data, project_id): self.project_id = project_id super().__init__() translator = dict(",
"api.get(url, params=params) return Influencer(res_data, project_id) @classmethod def fetch(cls, project_id, parameter, api=None): \"\"\"Retrieve influencers",
"the influencer from the API. Returns: dict: \"\"\" api = api or RadarlyApi.get_default_api()",
"\"\"\"Generator which yields all influencers matching some payload. Args: search_param (InfluencerParameter): project_id (int):",
"stats=parse_struct_stat ) if 'user' in data: super().add_data(data['user'], translator) del data['user'] super().add_data(data, translator) def",
"influencer. The value of this object are available as value associated to a",
"project. Args: project_id (int): identifier of a project parameter (InfluencerParameter): parameter sent as",
"API will be used. Returns: Influencer: \"\"\" api = api or RadarlyApi.get_default_api() url",
"build this object. This object must contain pagination's parameters. api (RadarlyApi): API used",
"to see how to build this object. This object must contain pagination's parameters.",
"instance. Here are some useful attributes: .. warning:: The structure of the ``Influencer``",
"range of influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url, data=self.search_param) self.total = 1000",
"self.search_param['limit'] reste = self.total % self.search_param['limit'] self.total_page = div if reste != 0:",
"'<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def find(cls, project_id, influencer_id, platform, api=None): \"\"\"Retrieve information about an",
"statitics about the influencers publications \"\"\" def __init__(self, data, project_id): self.project_id = project_id",
"def find(cls, project_id, influencer_id, platform, api=None): \"\"\"Retrieve information about an influencer. Args: project_id",
"super().add_data(data, translator) def __repr__(self): influ_id, platform = getattr(self, 'id'), getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id,",
"uid=self['id'] ) url = api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url, params=params)['metrics'] return metrics class InfluencersGenerator(GeneratorModel):",
"API will be used. Returns: InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter, project_id=project_id, api=api) def get_metrics(self,",
"in data['users']] @classmethod def fetch_all(cls, project_id, parameter, api=None): \"\"\"retrieve all influencers from a",
"followers_count (int): numbers of followers of the influencer count (int): number of documents",
"attributes: .. warning:: The structure of the ``Influencer`` object may change depending on",
"data, project_id): self.project_id = project_id super().__init__() translator = dict( stats=parse_struct_stat ) if 'user'",
"of the influencer platform (str): platform of the influencer api (RadarlyApi, optional): API",
"influencer_id, platform, api=None): \"\"\"Retrieve information about an influencer. Args: project_id (int): id of",
"Influencer: \"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id) params = dict(",
"influencers matching some payload. Args: search_param (InfluencerParameter): project_id (int): api (RadarlyApi): Yields: Influencer:",
"Args: project_id (int): identifier of a project parameter (InfluencerParameter): parameter sent as payload",
"object. This object must contain pagination's parameters. api (RadarlyApi): API used to performed",
"= self.total % self.search_param['limit'] self.total_page = div if reste != 0: self.total_page +=",
"performed the request. If None, the default API will be used. Returns: list[Influencer]:",
"def get_metrics(self, api=None): \"\"\"Retrieve metrics data about the influencer from the API. Returns:",
"metrics data about the influencer from the API. Returns: dict: \"\"\" api =",
"on the social_accounts permalink (str): link to the social_account followers_count (int): numbers of",
"= api or RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id) data = api.post(url, data=parameter) return [cls(item,",
"used to performed the request. If None, the default API will be used.",
"all influencers matching some payload. Args: search_param (InfluencerParameter): project_id (int): api (RadarlyApi): Yields:",
"a project. Args: project_id (int): identifier of a project parameter (InfluencerParameter): parameter sent",
"Returns: dict: \"\"\" api = api or RadarlyApi.get_default_api() params = dict( platform=self['platform'], uid=self['id']",
"change depending on the platform Args: id (str): identifier for the influencer platform",
"(int): numbers of followers of the influencer count (int): number of documents published",
"object are available as value associated to a key, or as attribute of",
"= dict( uid=influencer_id, platform=platform ) res_data = api.get(url, params=params) return Influencer(res_data, project_id) @classmethod",
"information about an influencer. The value of this object are available as value",
"the platform Args: id (str): identifier for the influencer platform (str): origin platform",
"the project parameter (InfluencerParameter): parameter sent as payload to the API. See ``InfluencerParameter``",
"class Influencer(SourceModel): \"\"\"Dict-like object storing information about an influencer. The value of this",
".utils._internal import parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like object storing information about an influencer. The",
"default API will be used. Returns: Influencer: \"\"\" api = api or RadarlyApi.get_default_api()",
"contain pagination's parameters. api (RadarlyApi): API used to performed the request. If None,",
"see how to build this object. api (RadarlyApi): API used to performed the",
"(int): id of the project influencer_id (int): id of the influencer platform (str):",
"this object are available as value associated to a key, or as attribute",
"id of the project influencer_id (int): id of the influencer platform (str): platform",
"yields all influencers matching some payload. Args: search_param (InfluencerParameter): project_id (int): api (RadarlyApi):",
"= dict( platform=self['platform'], uid=self['id'] ) url = api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url, params=params)['metrics'] return",
"dict( uid=influencer_id, platform=platform ) res_data = api.get(url, params=params) return Influencer(res_data, project_id) @classmethod def",
"from .utils._internal import parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like object storing information about an influencer.",
"item in data['users']] @classmethod def fetch_all(cls, project_id, parameter, api=None): \"\"\"retrieve all influencers from",
"!= 0: self.total_page += 1 self.search_param = self.search_param.next_page() def __repr__(self): return '<InfluencersGenerator.total={}.total_page={}>'.format( self.total,",
"This object must contain pagination's parameters. api (RadarlyApi): API used to performed the",
"(int): id of the influencer platform (str): platform of the influencer api (RadarlyApi,",
"author of several publications who has a more-or-less large audience. The influencer module",
"will be used. Returns: list[Influencer]: \"\"\" api = api or RadarlyApi.get_default_api() url =",
"how to build this object. This object must contain pagination's parameters. api (RadarlyApi):",
"return metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields all influencers matching some payload. Args:",
"api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url, params=params)['metrics'] return metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields all",
"warning:: The structure of the ``Influencer`` object may change depending on the platform",
") if 'user' in data: super().add_data(data['user'], translator) del data['user'] super().add_data(data, translator) def __repr__(self):",
"of several publications who has a more-or-less large audience. The influencer module of",
"understand who are the influencers in your project and consequently understand your audience.",
"the request. If None, the default API will be used. Returns: Influencer: \"\"\"",
"name on the social_accounts permalink (str): link to the social_account followers_count (int): numbers",
"and functions in order to help you to understand who are the influencers",
"to see how to build this object. api (RadarlyApi): API used to performed",
"to help you to understand who are the influencers in your project and",
"api (RadarlyApi, optional): API used to make the request. If None, the default",
"project. stats (dict): statitics about the influencers publications \"\"\" def __init__(self, data, project_id):",
"influencers publications \"\"\" def __init__(self, data, project_id): self.project_id = project_id super().__init__() translator =",
"the request. If None, the default API will be used. Returns: InfluencerGenerator: \"\"\"",
".model import GeneratorModel, SourceModel from .utils._internal import parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like object storing",
"count (int): number of documents published by the follower in your project. stats",
"influencers list from a project. Args: project_id (int): id of the project parameter",
"params=params)['metrics'] return metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields all influencers matching some payload.",
"the API. See ``InfluencerParameter`` to see how to build this object. This object",
"InfluencersGenerator(parameter, project_id=project_id, api=api) def get_metrics(self, api=None): \"\"\"Retrieve metrics data about the influencer from",
"from a project. Args: project_id (int): id of the project parameter (InfluencerParameter): parameter",
"0: self.total_page += 1 self.search_param = self.search_param.next_page() def __repr__(self): return '<InfluencersGenerator.total={}.total_page={}>'.format( self.total, self.total_page",
"\"\"\" def _fetch_items(self): \"\"\"Get next range of influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data =",
"(str): display name on the social_accounts permalink (str): link to the social_account followers_count",
"social_account followers_count (int): numbers of followers of the influencer count (int): number of",
"social_accounts permalink (str): link to the social_account followers_count (int): numbers of followers of",
"to the social_account followers_count (int): numbers of followers of the influencer count (int):",
"the API. Returns: dict: \"\"\" api = api or RadarlyApi.get_default_api() params = dict(",
"translator = dict( stats=parse_struct_stat ) if 'user' in data: super().add_data(data['user'], translator) del data['user']",
"of ``radarly-py`` defines several methods and functions in order to help you to",
"from .api import RadarlyApi from .model import GeneratorModel, SourceModel from .utils._internal import parse_struct_stat",
"key, or as attribute of the instance. Here are some useful attributes: ..",
"api=api) def get_metrics(self, api=None): \"\"\"Retrieve metrics data about the influencer from the API.",
"project parameter (InfluencerParameter): parameter sent as payload to the API. See ``InfluencerParameter`` to",
"(RadarlyApi, optional): API used to make the request. If None, the default API",
"available as value associated to a key, or as attribute of the instance.",
"= self._api.post(url, data=self.search_param) self.total = 1000 self._items = ( Influencer(item, self.project_id) for item",
"data about the influencer from the API. Returns: dict: \"\"\" api = api",
"module of ``radarly-py`` defines several methods and functions in order to help you",
"has a more-or-less large audience. The influencer module of ``radarly-py`` defines several methods",
"api (RadarlyApi): API used to performed the request. If None, the default API",
"in res_data['users'] ) div = self.total // self.search_param['limit'] reste = self.total % self.search_param['limit']",
"Influencer(SourceModel): \"\"\"Dict-like object storing information about an influencer. The value of this object",
"Influencer: \"\"\" def _fetch_items(self): \"\"\"Get next range of influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data",
"stats (dict): statitics about the influencers publications \"\"\" def __init__(self, data, project_id): self.project_id",
"defines several methods and functions in order to help you to understand who",
"associated to a key, or as attribute of the instance. Here are some",
"matching some payload. Args: search_param (InfluencerParameter): project_id (int): api (RadarlyApi): Yields: Influencer: \"\"\"",
"params = dict( uid=influencer_id, platform=platform ) res_data = api.get(url, params=params) return Influencer(res_data, project_id)",
"'id'), getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def find(cls, project_id, influencer_id, platform, api=None):",
"next range of influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url, data=self.search_param) self.total =",
"influencer. Args: project_id (int): id of the project influencer_id (int): id of the",
"\"\"\"Retrieve influencers list from a project. Args: project_id (int): id of the project",
"def fetch(cls, project_id, parameter, api=None): \"\"\"Retrieve influencers list from a project. Args: project_id",
"the influencers in your project and consequently understand your audience. \"\"\" from .api",
"self.total_page += 1 self.search_param = self.search_param.next_page() def __repr__(self): return '<InfluencersGenerator.total={}.total_page={}>'.format( self.total, self.total_page )",
"project_id (int): api (RadarlyApi): Yields: Influencer: \"\"\" def _fetch_items(self): \"\"\"Get next range of",
"influencer from the API. Returns: dict: \"\"\" api = api or RadarlyApi.get_default_api() params",
"api = api or RadarlyApi.get_default_api() params = dict( platform=self['platform'], uid=self['id'] ) url =",
"id (str): identifier for the influencer platform (str): origin platform of the influencer",
"url = api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id, platform=platform ) res_data = api.get(url, params=params)",
"performed the request. If None, the default API will be used. Returns: InfluencerGenerator:",
"value associated to a key, or as attribute of the instance. Here are",
"fetch(cls, project_id, parameter, api=None): \"\"\"Retrieve influencers list from a project. Args: project_id (int):",
"influencer platform (str): origin platform of the influencer screen_name (str): display name on",
"used. Returns: InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter, project_id=project_id, api=api) def get_metrics(self, api=None): \"\"\"Retrieve metrics",
"as attribute of the instance. Here are some useful attributes: .. warning:: The",
"\"\"\"Dict-like object storing information about an influencer. The value of this object are",
"@classmethod def fetch_all(cls, project_id, parameter, api=None): \"\"\"retrieve all influencers from a project. Args:",
"The structure of the ``Influencer`` object may change depending on the platform Args:",
"reste = self.total % self.search_param['limit'] self.total_page = div if reste != 0: self.total_page",
"will be used. Returns: InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter, project_id=project_id, api=api) def get_metrics(self, api=None):",
"self.total // self.search_param['limit'] reste = self.total % self.search_param['limit'] self.total_page = div if reste",
"project_id (int): identifier of a project parameter (InfluencerParameter): parameter sent as payload to",
"self.search_param['limit'] self.total_page = div if reste != 0: self.total_page += 1 self.search_param =",
"make the request. If None, the default API will be used. Returns: Influencer:",
"influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url, data=self.search_param) self.total = 1000 self._items =",
"class InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields all influencers matching some payload. Args: search_param (InfluencerParameter):",
"an influencer. Args: project_id (int): id of the project influencer_id (int): id of",
"return Influencer(res_data, project_id) @classmethod def fetch(cls, project_id, parameter, api=None): \"\"\"Retrieve influencers list from",
"your project and consequently understand your audience. \"\"\" from .api import RadarlyApi from",
"reste != 0: self.total_page += 1 self.search_param = self.search_param.next_page() def __repr__(self): return '<InfluencersGenerator.total={}.total_page={}>'.format(",
"more-or-less large audience. The influencer module of ``radarly-py`` defines several methods and functions",
"import GeneratorModel, SourceModel from .utils._internal import parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like object storing information",
"parameters. api (RadarlyApi): API used to performed the request. If None, the default",
"api.post(url, data=parameter) return [cls(item, project_id) for item in data['users']] @classmethod def fetch_all(cls, project_id,",
"params=params) return Influencer(res_data, project_id) @classmethod def fetch(cls, project_id, parameter, api=None): \"\"\"Retrieve influencers list",
"the default API will be used. Returns: InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter, project_id=project_id, api=api)",
"getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def find(cls, project_id, influencer_id, platform, api=None): \"\"\"Retrieve",
"audience. The influencer module of ``radarly-py`` defines several methods and functions in order",
"def _fetch_items(self): \"\"\"Get next range of influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url,",
"display name on the social_accounts permalink (str): link to the social_account followers_count (int):",
"getattr(self, 'id'), getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def find(cls, project_id, influencer_id, platform,",
"\"\"\" return InfluencersGenerator(parameter, project_id=project_id, api=api) def get_metrics(self, api=None): \"\"\"Retrieve metrics data about the",
"api=None): \"\"\"Retrieve influencers list from a project. Args: project_id (int): id of the",
"\"\"\" api = api or RadarlyApi.get_default_api() params = dict( platform=self['platform'], uid=self['id'] ) url",
"you to understand who are the influencers in your project and consequently understand",
"who are the influencers in your project and consequently understand your audience. \"\"\"",
"of the ``Influencer`` object may change depending on the platform Args: id (str):",
"a project parameter (InfluencerParameter): parameter sent as payload to the API. See ``InfluencerParameter``",
"or RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id, platform=platform ) res_data =",
"return InfluencersGenerator(parameter, project_id=project_id, api=api) def get_metrics(self, api=None): \"\"\"Retrieve metrics data about the influencer",
"used. Returns: Influencer: \"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id) params",
"self._items = ( Influencer(item, self.project_id) for item in res_data['users'] ) div = self.total",
"self.total % self.search_param['limit'] self.total_page = div if reste != 0: self.total_page += 1",
"information about an influencer. Args: project_id (int): id of the project influencer_id (int):",
"Returns: InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter, project_id=project_id, api=api) def get_metrics(self, api=None): \"\"\"Retrieve metrics data",
"import parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like object storing information about an influencer. The value",
"If None, the default API will be used. Returns: list[Influencer]: \"\"\" api =",
"will be used. Returns: Influencer: \"\"\" api = api or RadarlyApi.get_default_api() url =",
"as value associated to a key, or as attribute of the instance. Here",
"sent as payload to the API. See ``InfluencerParameter`` to see how to build",
"@classmethod def find(cls, project_id, influencer_id, platform, api=None): \"\"\"Retrieve information about an influencer. Args:",
"return [cls(item, project_id) for item in data['users']] @classmethod def fetch_all(cls, project_id, parameter, api=None):",
"platform=self['platform'], uid=self['id'] ) url = api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url, params=params)['metrics'] return metrics class",
"by the follower in your project. stats (dict): statitics about the influencers publications",
"of the project parameter (InfluencerParameter): parameter sent as payload to the API. See",
"``InfluencerParameter`` to see how to build this object. api (RadarlyApi): API used to",
"(int): id of the project parameter (InfluencerParameter): parameter sent as payload to the",
"your project. stats (dict): statitics about the influencers publications \"\"\" def __init__(self, data,",
"this object. This object must contain pagination's parameters. api (RadarlyApi): API used to",
"uid=influencer_id, platform=platform ) res_data = api.get(url, params=params) return Influencer(res_data, project_id) @classmethod def fetch(cls,",
"= api.get(url, params=params)['metrics'] return metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields all influencers matching",
"some payload. Args: search_param (InfluencerParameter): project_id (int): api (RadarlyApi): Yields: Influencer: \"\"\" def",
"return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def find(cls, project_id, influencer_id, platform, api=None): \"\"\"Retrieve information about",
"structure of the ``Influencer`` object may change depending on the platform Args: id",
"Args: id (str): identifier for the influencer platform (str): origin platform of the",
"who has a more-or-less large audience. The influencer module of ``radarly-py`` defines several",
"and consequently understand your audience. \"\"\" from .api import RadarlyApi from .model import",
"api = api or RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id, platform=platform",
") res_data = api.get(url, params=params) return Influencer(res_data, project_id) @classmethod def fetch(cls, project_id, parameter,",
"from the API. Returns: dict: \"\"\" api = api or RadarlyApi.get_default_api() params =",
"InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields all influencers matching some payload. Args: search_param (InfluencerParameter): project_id",
"on the platform Args: id (str): identifier for the influencer platform (str): origin",
"del data['user'] super().add_data(data, translator) def __repr__(self): influ_id, platform = getattr(self, 'id'), getattr(self, 'platform')",
"None, the default API will be used. Returns: Influencer: \"\"\" api = api",
"all influencers from a project. Args: project_id (int): identifier of a project parameter",
"dict: \"\"\" api = api or RadarlyApi.get_default_api() params = dict( platform=self['platform'], uid=self['id'] )",
"are some useful attributes: .. warning:: The structure of the ``Influencer`` object may",
".. warning:: The structure of the ``Influencer`` object may change depending on the",
"API. Returns: dict: \"\"\" api = api or RadarlyApi.get_default_api() params = dict( platform=self['platform'],",
"audience. \"\"\" from .api import RadarlyApi from .model import GeneratorModel, SourceModel from .utils._internal",
"get_metrics(self, api=None): \"\"\"Retrieve metrics data about the influencer from the API. Returns: dict:",
"number of documents published by the follower in your project. stats (dict): statitics",
"be used. Returns: Influencer: \"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id)",
"self.total = 1000 self._items = ( Influencer(item, self.project_id) for item in res_data['users'] )",
"(int): number of documents published by the follower in your project. stats (dict):",
"the influencer platform (str): origin platform of the influencer screen_name (str): display name",
"( Influencer(item, self.project_id) for item in res_data['users'] ) div = self.total // self.search_param['limit']",
"influencers in your project and consequently understand your audience. \"\"\" from .api import",
"as payload to the API. See ``InfluencerParameter`` to see how to build this",
"api=None): \"\"\"Retrieve metrics data about the influencer from the API. Returns: dict: \"\"\"",
"div if reste != 0: self.total_page += 1 self.search_param = self.search_param.next_page() def __repr__(self):",
"origin platform of the influencer screen_name (str): display name on the social_accounts permalink",
"for item in data['users']] @classmethod def fetch_all(cls, project_id, parameter, api=None): \"\"\"retrieve all influencers",
"'user' in data: super().add_data(data['user'], translator) del data['user'] super().add_data(data, translator) def __repr__(self): influ_id, platform",
"influencers from a project. Args: project_id (int): identifier of a project parameter (InfluencerParameter):",
"the instance. Here are some useful attributes: .. warning:: The structure of the",
"understand your audience. \"\"\" from .api import RadarlyApi from .model import GeneratorModel, SourceModel",
"api.get(url, params=params)['metrics'] return metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields all influencers matching some",
"api = api or RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id) data = api.post(url, data=parameter) return",
"parameter, api=None): \"\"\"Retrieve influencers list from a project. Args: project_id (int): id of",
"request. If None, the default API will be used. Returns: list[Influencer]: \"\"\" api",
"object. api (RadarlyApi): API used to performed the request. If None, the default",
"several methods and functions in order to help you to understand who are",
"publications who has a more-or-less large audience. The influencer module of ``radarly-py`` defines",
"[cls(item, project_id) for item in data['users']] @classmethod def fetch_all(cls, project_id, parameter, api=None): \"\"\"retrieve",
"(str): origin platform of the influencer screen_name (str): display name on the social_accounts",
"project and consequently understand your audience. \"\"\" from .api import RadarlyApi from .model",
"help you to understand who are the influencers in your project and consequently",
"several publications who has a more-or-less large audience. The influencer module of ``radarly-py``",
"list from a project. Args: project_id (int): id of the project parameter (InfluencerParameter):",
"platform=platform ) res_data = api.get(url, params=params) return Influencer(res_data, project_id) @classmethod def fetch(cls, project_id,",
"platform of the influencer api (RadarlyApi, optional): API used to make the request.",
"the project influencer_id (int): id of the influencer platform (str): platform of the",
"about an influencer. Args: project_id (int): id of the project influencer_id (int): id",
"project_id, parameter, api=None): \"\"\"retrieve all influencers from a project. Args: project_id (int): identifier",
"Radarly is an author of several publications who has a more-or-less large audience.",
"(RadarlyApi): API used to performed the request. If None, the default API will",
"\"\"\"Get next range of influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url, data=self.search_param) self.total",
"The influencer module of ``radarly-py`` defines several methods and functions in order to",
"super().add_data(data['user'], translator) del data['user'] super().add_data(data, translator) def __repr__(self): influ_id, platform = getattr(self, 'id'),",
"= div if reste != 0: self.total_page += 1 self.search_param = self.search_param.next_page() def",
"methods and functions in order to help you to understand who are the",
"attribute of the instance. Here are some useful attributes: .. warning:: The structure",
"from a project. Args: project_id (int): identifier of a project parameter (InfluencerParameter): parameter",
"to performed the request. If None, the default API will be used. Returns:",
"to the API. See ``InfluencerParameter`` to see how to build this object. This",
"about the influencer from the API. Returns: dict: \"\"\" api = api or",
"(str): link to the social_account followers_count (int): numbers of followers of the influencer",
"see how to build this object. This object must contain pagination's parameters. api",
"id of the influencer platform (str): platform of the influencer api (RadarlyApi, optional):",
"def __init__(self, data, project_id): self.project_id = project_id super().__init__() translator = dict( stats=parse_struct_stat )",
"self._api.post(url, data=self.search_param) self.total = 1000 self._items = ( Influencer(item, self.project_id) for item in",
"an influencer. The value of this object are available as value associated to",
"screen_name (str): display name on the social_accounts permalink (str): link to the social_account",
"the API. See ``InfluencerParameter`` to see how to build this object. api (RadarlyApi):",
"permalink (str): link to the social_account followers_count (int): numbers of followers of the",
"id of the project parameter (InfluencerParameter): parameter sent as payload to the API.",
"this object. api (RadarlyApi): API used to performed the request. If None, the",
"object storing information about an influencer. The value of this object are available",
"_fetch_items(self): \"\"\"Get next range of influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url, data=self.search_param)",
"import RadarlyApi from .model import GeneratorModel, SourceModel from .utils._internal import parse_struct_stat class Influencer(SourceModel):",
"influencer module of ``radarly-py`` defines several methods and functions in order to help",
"of a project parameter (InfluencerParameter): parameter sent as payload to the API. See",
") url = api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url, params=params)['metrics'] return metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator",
"in order to help you to understand who are the influencers in your",
"your audience. \"\"\" from .api import RadarlyApi from .model import GeneratorModel, SourceModel from",
"the influencer count (int): number of documents published by the follower in your",
"may change depending on the platform Args: id (str): identifier for the influencer",
"data['users']] @classmethod def fetch_all(cls, project_id, parameter, api=None): \"\"\"retrieve all influencers from a project.",
"\"\"\" def __init__(self, data, project_id): self.project_id = project_id super().__init__() translator = dict( stats=parse_struct_stat",
"__init__(self, data, project_id): self.project_id = project_id super().__init__() translator = dict( stats=parse_struct_stat ) if",
"influencer_id (int): id of the influencer platform (str): platform of the influencer api",
"in your project and consequently understand your audience. \"\"\" from .api import RadarlyApi",
"be used. Returns: InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter, project_id=project_id, api=api) def get_metrics(self, api=None): \"\"\"Retrieve",
"(int): api (RadarlyApi): Yields: Influencer: \"\"\" def _fetch_items(self): \"\"\"Get next range of influencers\"\"\"",
"InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter, project_id=project_id, api=api) def get_metrics(self, api=None): \"\"\"Retrieve metrics data about",
"influ_id, platform = getattr(self, 'id'), getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def find(cls,",
"of the influencer screen_name (str): display name on the social_accounts permalink (str): link",
"from .model import GeneratorModel, SourceModel from .utils._internal import parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like object",
"pagination's parameters. api (RadarlyApi): API used to performed the request. If None, the",
"optional): API used to make the request. If None, the default API will",
"payload to the API. See ``InfluencerParameter`` to see how to build this object.",
"\"\"\" from .api import RadarlyApi from .model import GeneratorModel, SourceModel from .utils._internal import",
"div = self.total // self.search_param['limit'] reste = self.total % self.search_param['limit'] self.total_page = div",
"depending on the platform Args: id (str): identifier for the influencer platform (str):",
"``InfluencerParameter`` to see how to build this object. This object must contain pagination's",
"an author of several publications who has a more-or-less large audience. The influencer",
"in your project. stats (dict): statitics about the influencers publications \"\"\" def __init__(self,",
"``Influencer`` object may change depending on the platform Args: id (str): identifier for",
"url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url, data=self.search_param) self.total = 1000 self._items = (",
"(InfluencerParameter): project_id (int): api (RadarlyApi): Yields: Influencer: \"\"\" def _fetch_items(self): \"\"\"Get next range",
"An influencer in Radarly is an author of several publications who has a",
"= api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url, params=params)['metrics'] return metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields",
"= api or RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id, platform=platform )",
"Returns: Influencer: \"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['find'].format(project_id=project_id) params =",
"followers of the influencer count (int): number of documents published by the follower",
"build this object. api (RadarlyApi): API used to performed the request. If None,",
"a more-or-less large audience. The influencer module of ``radarly-py`` defines several methods and",
"res_data = self._api.post(url, data=self.search_param) self.total = 1000 self._items = ( Influencer(item, self.project_id) for",
"of the instance. Here are some useful attributes: .. warning:: The structure of",
"Influencer(item, self.project_id) for item in res_data['users'] ) div = self.total // self.search_param['limit'] reste",
"request. If None, the default API will be used. Returns: Influencer: \"\"\" api",
"dict( stats=parse_struct_stat ) if 'user' in data: super().add_data(data['user'], translator) del data['user'] super().add_data(data, translator)",
"url = api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url, params=params)['metrics'] return metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator which",
"1000 self._items = ( Influencer(item, self.project_id) for item in res_data['users'] ) div =",
"influencer count (int): number of documents published by the follower in your project.",
"default API will be used. Returns: InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter, project_id=project_id, api=api) def",
") div = self.total // self.search_param['limit'] reste = self.total % self.search_param['limit'] self.total_page =",
"project_id (int): id of the project influencer_id (int): id of the influencer platform",
"influencer api (RadarlyApi, optional): API used to make the request. If None, the",
"SourceModel from .utils._internal import parse_struct_stat class Influencer(SourceModel): \"\"\"Dict-like object storing information about an",
"None, the default API will be used. Returns: list[Influencer]: \"\"\" api = api",
"about the influencers publications \"\"\" def __init__(self, data, project_id): self.project_id = project_id super().__init__()",
"the default API will be used. Returns: list[Influencer]: \"\"\" api = api or",
"influencer platform (str): platform of the influencer api (RadarlyApi, optional): API used to",
"project_id) @classmethod def fetch(cls, project_id, parameter, api=None): \"\"\"Retrieve influencers list from a project.",
"list[Influencer]: \"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id) data = api.post(url,",
"the request. If None, the default API will be used. Returns: list[Influencer]: \"\"\"",
"Returns: list[Influencer]: \"\"\" api = api or RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id) data =",
"project_id, parameter, api=None): \"\"\"Retrieve influencers list from a project. Args: project_id (int): id",
"api or RadarlyApi.get_default_api() url = api.router.influencer['search'].format(project_id=project_id) data = api.post(url, data=parameter) return [cls(item, project_id)",
"Args: project_id (int): id of the project parameter (InfluencerParameter): parameter sent as payload",
"must contain pagination's parameters. api (RadarlyApi): API used to performed the request. If",
"data=parameter) return [cls(item, project_id) for item in data['users']] @classmethod def fetch_all(cls, project_id, parameter,",
"about an influencer. The value of this object are available as value associated",
"\"\"\"Retrieve information about an influencer. Args: project_id (int): id of the project influencer_id",
"\"\"\"retrieve all influencers from a project. Args: project_id (int): identifier of a project",
"request. If None, the default API will be used. Returns: InfluencerGenerator: \"\"\" return",
"If None, the default API will be used. Returns: InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter,",
"to understand who are the influencers in your project and consequently understand your",
"res_data = api.get(url, params=params) return Influencer(res_data, project_id) @classmethod def fetch(cls, project_id, parameter, api=None):",
"of influencers\"\"\" url = self._api.router.influencer['search'].format(project_id=self.project_id) res_data = self._api.post(url, data=self.search_param) self.total = 1000 self._items",
"(str): identifier for the influencer platform (str): origin platform of the influencer screen_name",
"translator) del data['user'] super().add_data(data, translator) def __repr__(self): influ_id, platform = getattr(self, 'id'), getattr(self,",
"in Radarly is an author of several publications who has a more-or-less large",
"payload. Args: search_param (InfluencerParameter): project_id (int): api (RadarlyApi): Yields: Influencer: \"\"\" def _fetch_items(self):",
"platform of the influencer screen_name (str): display name on the social_accounts permalink (str):",
"= ( Influencer(item, self.project_id) for item in res_data['users'] ) div = self.total //",
"the social_accounts permalink (str): link to the social_account followers_count (int): numbers of followers",
"project_id) for item in data['users']] @classmethod def fetch_all(cls, project_id, parameter, api=None): \"\"\"retrieve all",
"// self.search_param['limit'] reste = self.total % self.search_param['limit'] self.total_page = div if reste !=",
"of documents published by the follower in your project. stats (dict): statitics about",
"of followers of the influencer count (int): number of documents published by the",
"the influencer platform (str): platform of the influencer api (RadarlyApi, optional): API used",
"platform (str): platform of the influencer api (RadarlyApi, optional): API used to make",
"useful attributes: .. warning:: The structure of the ``Influencer`` object may change depending",
"storing information about an influencer. The value of this object are available as",
"project. Args: project_id (int): id of the project parameter (InfluencerParameter): parameter sent as",
"the influencer api (RadarlyApi, optional): API used to make the request. If None,",
"dict( platform=self['platform'], uid=self['id'] ) url = api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url, params=params)['metrics'] return metrics",
"res_data['users'] ) div = self.total // self.search_param['limit'] reste = self.total % self.search_param['limit'] self.total_page",
"data=self.search_param) self.total = 1000 self._items = ( Influencer(item, self.project_id) for item in res_data['users']",
"\"\"\" An influencer in Radarly is an author of several publications who has",
"if reste != 0: self.total_page += 1 self.search_param = self.search_param.next_page() def __repr__(self): return",
"% self.search_param['limit'] self.total_page = div if reste != 0: self.total_page += 1 self.search_param",
"a project. Args: project_id (int): id of the project parameter (InfluencerParameter): parameter sent",
"If None, the default API will be used. Returns: Influencer: \"\"\" api =",
"influencer screen_name (str): display name on the social_accounts permalink (str): link to the",
"for item in res_data['users'] ) div = self.total // self.search_param['limit'] reste = self.total",
"API used to performed the request. If None, the default API will be",
"are available as value associated to a key, or as attribute of the",
"the follower in your project. stats (dict): statitics about the influencers publications \"\"\"",
"platform (str): origin platform of the influencer screen_name (str): display name on the",
"or RadarlyApi.get_default_api() params = dict( platform=self['platform'], uid=self['id'] ) url = api.router.influencer['find'].format(project_id=self.project_id) metrics =",
"Args: search_param (InfluencerParameter): project_id (int): api (RadarlyApi): Yields: Influencer: \"\"\" def _fetch_items(self): \"\"\"Get",
"Here are some useful attributes: .. warning:: The structure of the ``Influencer`` object",
"__repr__(self): influ_id, platform = getattr(self, 'id'), getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def",
"consequently understand your audience. \"\"\" from .api import RadarlyApi from .model import GeneratorModel,",
"of the influencer api (RadarlyApi, optional): API used to make the request. If",
"= project_id super().__init__() translator = dict( stats=parse_struct_stat ) if 'user' in data: super().add_data(data['user'],",
"= api or RadarlyApi.get_default_api() params = dict( platform=self['platform'], uid=self['id'] ) url = api.router.influencer['find'].format(project_id=self.project_id)",
"= api.router.influencer['search'].format(project_id=project_id) data = api.post(url, data=parameter) return [cls(item, project_id) for item in data['users']]",
"large audience. The influencer module of ``radarly-py`` defines several methods and functions in",
"(str): platform of the influencer api (RadarlyApi, optional): API used to make the",
"search_param (InfluencerParameter): project_id (int): api (RadarlyApi): Yields: Influencer: \"\"\" def _fetch_items(self): \"\"\"Get next",
"api=None): \"\"\"Retrieve information about an influencer. Args: project_id (int): id of the project",
"self.total_page = div if reste != 0: self.total_page += 1 self.search_param = self.search_param.next_page()",
"item in res_data['users'] ) div = self.total // self.search_param['limit'] reste = self.total %",
".api import RadarlyApi from .model import GeneratorModel, SourceModel from .utils._internal import parse_struct_stat class",
"default API will be used. Returns: list[Influencer]: \"\"\" api = api or RadarlyApi.get_default_api()",
"to a key, or as attribute of the instance. Here are some useful",
"object must contain pagination's parameters. api (RadarlyApi): API used to performed the request.",
"metrics = api.get(url, params=params)['metrics'] return metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields all influencers",
"translator) def __repr__(self): influ_id, platform = getattr(self, 'id'), getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform)",
"to build this object. This object must contain pagination's parameters. api (RadarlyApi): API",
"of the influencer count (int): number of documents published by the follower in",
"api or RadarlyApi.get_default_api() params = dict( platform=self['platform'], uid=self['id'] ) url = api.router.influencer['find'].format(project_id=self.project_id) metrics",
"api.router.influencer['find'].format(project_id=project_id) params = dict( uid=influencer_id, platform=platform ) res_data = api.get(url, params=params) return Influencer(res_data,",
"The value of this object are available as value associated to a key,",
"RadarlyApi.get_default_api() params = dict( platform=self['platform'], uid=self['id'] ) url = api.router.influencer['find'].format(project_id=self.project_id) metrics = api.get(url,",
"fetch_all(cls, project_id, parameter, api=None): \"\"\"retrieve all influencers from a project. Args: project_id (int):",
"API. See ``InfluencerParameter`` to see how to build this object. This object must",
"identifier of a project parameter (InfluencerParameter): parameter sent as payload to the API.",
"is an author of several publications who has a more-or-less large audience. The",
"Influencer(res_data, project_id) @classmethod def fetch(cls, project_id, parameter, api=None): \"\"\"Retrieve influencers list from a",
"project_id, influencer_id, platform, api=None): \"\"\"Retrieve information about an influencer. Args: project_id (int): id",
"Args: project_id (int): id of the project influencer_id (int): id of the influencer",
"identifier for the influencer platform (str): origin platform of the influencer screen_name (str):",
"platform Args: id (str): identifier for the influencer platform (str): origin platform of",
"metrics class InfluencersGenerator(GeneratorModel): \"\"\"Generator which yields all influencers matching some payload. Args: search_param",
"link to the social_account followers_count (int): numbers of followers of the influencer count",
"platform = getattr(self, 'id'), getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def find(cls, project_id,",
"def fetch_all(cls, project_id, parameter, api=None): \"\"\"retrieve all influencers from a project. Args: project_id",
"(InfluencerParameter): parameter sent as payload to the API. See ``InfluencerParameter`` to see how",
"API used to make the request. If None, the default API will be",
"data: super().add_data(data['user'], translator) del data['user'] super().add_data(data, translator) def __repr__(self): influ_id, platform = getattr(self,",
"of this object are available as value associated to a key, or as",
"parameter, api=None): \"\"\"retrieve all influencers from a project. Args: project_id (int): identifier of",
"def __repr__(self): influ_id, platform = getattr(self, 'id'), getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod",
"url = api.router.influencer['search'].format(project_id=project_id) data = api.post(url, data=parameter) return [cls(item, project_id) for item in",
"None, the default API will be used. Returns: InfluencerGenerator: \"\"\" return InfluencersGenerator(parameter, project_id=project_id,",
"= api.post(url, data=parameter) return [cls(item, project_id) for item in data['users']] @classmethod def fetch_all(cls,",
"of the project influencer_id (int): id of the influencer platform (str): platform of",
"= self.total // self.search_param['limit'] reste = self.total % self.search_param['limit'] self.total_page = div if",
"some useful attributes: .. warning:: The structure of the ``Influencer`` object may change",
"(int): identifier of a project parameter (InfluencerParameter): parameter sent as payload to the",
"``radarly-py`` defines several methods and functions in order to help you to understand",
"to make the request. If None, the default API will be used. Returns:",
"= 1000 self._items = ( Influencer(item, self.project_id) for item in res_data['users'] ) div",
"= dict( stats=parse_struct_stat ) if 'user' in data: super().add_data(data['user'], translator) del data['user'] super().add_data(data,",
"= getattr(self, 'id'), getattr(self, 'platform') return '<Influencer.id={}.platform={}>'.format(influ_id, platform) @classmethod def find(cls, project_id, influencer_id,"
] |
[
"<= 0: raise ZDBPathNotFound(\"all storagepools are already used by a zerodb\") return free_path[0]",
"import config from zerorobot.template.base import TemplateBase from zerorobot.template.decorator import retry, timeout from zerorobot.template.state",
"hostname, \"node_id:%s\" % node_id, \"interface:%s\" % mgmt_nic['name']], 'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if",
"with more then size storage available storagepools = list(filter(usable_storagepool, node_sal.storagepools.list())) if not storagepools:",
"on :type disktype: string :param namespaces: list of namespaces to create on the",
"nic_mgmt_monitor) # make sure the bridges are installed for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try:",
"mountpoint :type mountpoint: string :param mode: zerodb mode :type mode: string :param zdb_size:",
"used pool first fs_paths = [] for sp in storagepools: try: fs =",
"in disks_types_map[disktype]: return False free = (sp.size - sp.total_quota()) / GiB if free",
":param excepted: list of zerodb service name that should be skipped :type excepted:",
"'network interface %s is down' % mgmt_nic['name'], 'environment': 'Production', 'severity': 'critical', 'event': 'Network',",
"r: r['free'], reverse=True) zdb_paths = [res['path'] for res in results] # path that",
":type name: string :param zdbinfo: list of zerodb services and their info :param",
"find a place where to create a new zerodb # let's look at",
"zerodb mountpoint :type mountpoint: string :param mode: zerodb mode :type mode: string :param",
"if len(free_path) <= 0: raise ZDBPathNotFound(\"all storagepools are already used by a zerodb\")",
"result by free size, first item of the list is the the one",
"r['free'], reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces = [ns['name'] for ns in zdb.schedule_action('namespace_list').wait(die=True).result]",
"'ssd': ['SSD', 'NVME'], } # get all usable filesystem path for this type",
"size: return False return True # all storage pool path of type disktypes",
"bridges are installed for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring bridge",
"look at the already existing one pass def usable_zdb(info): if info['mode'] != mode:",
"string \"\"\" zdb_data = { 'path': mountpoint, 'mode': mode, 'sync': False, 'diskType': disktype,",
"True # all storage pool path of type disktypes and with more then",
"of the zerodb :type zdb_size: int :param disktype: type of the disk to",
"netaddr import time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID",
"== 'hdd': # sort less used pool first fs_paths = [] for sp",
"service name that should be skipped :type excepted: [str] :return: a list of",
"no zdb filesystem on this storagepool # all path used by installed zerodb",
"key=lambda r: r['free'], reverse=True) zdb_paths = [res['path'] for res in results] # path",
"all the zerodbs installed on the node :param excepted: list of zerodb service",
"PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local' GiB = 1024 **",
":rtype: string \"\"\" zdb_data = { 'path': mountpoint, 'mode': mode, 'sync': False, 'diskType':",
"the zerodb will be deployed on :type disktype: string :param size: size of",
"# all path used by installed zerodb services zdb_infos = self._list_zdbs_info() zdb_infos =",
"'text': 'network interface %s is down' % mgmt_nic['name'], 'environment': 'Production', 'severity': 'critical', 'event':",
"def _register(self): \"\"\" make sure the node_capacity service is installed \"\"\" if config.SERVICE_LOADED:",
"cidr: netaddr.IPNetwork(cidr) vlan = network.get('vlan') if not isinstance(vlan, int): raise ValueError('Network should have",
"usable storage pool. Not enough space for disk type %s\" % disktype) storagepools.sort(key=lambda",
"= network.get('vlan') if not isinstance(vlan, int): raise ValueError('Network should have vlan configured') def",
"sp in storagepools: try: fs = sp.get('zdb') fs_paths.append(fs.path) except ValueError: pass # no",
":type size: int :param name: zerodb name :type name: string :param zdbinfo: list",
"config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return except",
":param zdb_size: size of the zerodb :type zdb_size: int :param disktype: type of",
"in results] # path that are not used by zerodb services but have",
"by installed zerodb services zdb_infos = self._list_zdbs_info() zdb_infos = filter(lambda info: info['service_name'] !=",
"mountpoint, mode, zdb_size, disktype, [namespace]) return zdb_name, namespace_name except ZDBPathNotFound as err: self.logger.warning(\"fail",
"sp.name == reserved.name: return False if sp.type.value not in disks_types_map[disktype]: return False free",
"if len(zdbinfos) <= 0: message = 'Not enough free space for namespace creation",
"disktype) def create_zdb_namespace(self, disktype, mode, password, public, ns_size, name='', zdb_size=None): if disktype not",
"= 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local' GiB =",
"CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID",
"'severity': 'critical', 'event': 'Network', 'tags': [\"node:%s\" % hostname, \"node_id:%s\" % node_id, \"interface:%s\" %",
"TemplateBase from zerorobot.template.decorator import retry, timeout from zerorobot.template.state import StateCheckError import netaddr import",
"create_zdb_namespace(self, disktype, mode, password, public, ns_size, name='', zdb_size=None): if disktype not in ['hdd',",
"- sp.total_quota()) / GiB if free <= size: return False return True #",
"err: self.logger.warning(\"fail to create a 0-db namespace: %s\", str(err)) # at this point",
"on all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30, error_message='info action timeout') def info(self): return self._node_sal.client.info.os()",
"nodes[0].guid != self.guid: raise RuntimeError('Another node service exists. Only one node service per",
"of the list is the the one with bigger free size for zdbinfo",
"of type disktypes and with more then size storage available storagepools = list(filter(usable_storagepool,",
"if namespace_name not in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name, namespace_name message = 'Namespace",
"string :param namespaces: list of namespaces to create on the zerodb :type namespaces:",
"set(zdb_paths)) if len(free_path) <= 0: raise ZDBPathNotFound(\"all storagepools are already used by a",
"Node(TemplateBase): version = '0.0.1' template_name = 'node' def __init__(self, name, guid=None, data=None): super().__init__(name=name,",
"if sp.type.value not in disks_types_map[disktype]: return False free = (sp.size - sp.total_quota()) /",
"return False free = (sp.size - sp.total_quota()) / GiB if free <= size:",
"%s\" % disktype) storagepools.sort(key=lambda sp: sp.size - sp.total_quota(), reverse=True) if disktype == 'hdd':",
"zerodb services but have a storagepool, so we can use them free_path =",
"/ GiB < zdb_size: return False if info['type'] not in disktypes: return False",
"namespaces = [ns['name'] for ns in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not in namespaces: zdb.schedule_action('namespace_create',",
"error_message='stats action timeout') def stats(self): return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action timeout') def processes(self):",
"hostname = self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name data = { 'attributes': {}, 'resource': hostname,",
"password, 'public': public, } try: mountpoint = self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint, mode,",
"size for zdbinfo in sorted(zdbinfos, key=lambda r: r['free'], reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name'])",
"zdb_size: int :param disktype: type of the disk to deploy the zerodb on",
"self.install() self.data['uptime'] = self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok') except: self.state.delete('disks', 'mounted') def",
"in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make sure the bridges are installed for service",
"/etc/hostname' % self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime() self.state.set('actions', 'install', 'ok') def reboot(self): self.logger.info('Rebooting node",
"filesystem on this storagepool # all path used by installed zerodb services zdb_infos",
"zerodb\") return free_path[0] if disktype == 'ssd': fs = storagepools[0].create('zdb_{}'.format(name), size * GiB)",
"the zerodb :type namespaces: [dict] :return: zerodb service name :rtype: string \"\"\" zdb_data",
"def usable_zdb(info): if info['mode'] != mode: return False if info['free'] / GiB <",
"mgmt_nic.get('speed') <= 0: self.logger.error(\"management interface is not healthy\") hostname = self._node_sal.client.info.os()['hostname'] node_id =",
"name self._node_sal.client.system('hostname %s' % self.data['hostname']).get() self._node_sal.client.bash('echo %s > /etc/hostname' % self.data['hostname']).get() self.data['uptime'] =",
":return: zerodb mountpoint, subvolume name :rtype: (string, string) \"\"\" node_sal = self._node_sal disks_types_map",
"# get all usable filesystem path for this type of disk and amount",
"zdb filesystem on this storagepool # all path used by installed zerodb services",
"== 'ssd': fs = storagepools[0].create('zdb_{}'.format(name), size * GiB) return fs.path raise RuntimeError(\"unsupported disktype:%s\"",
"item of the list is the the one with bigger free size for",
"%s is down' % mgmt_nic['name'], 'environment': 'Production', 'severity': 'critical', 'event': 'Network', 'tags': [\"node:%s\"",
"try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring bridge %s\" % service.name) service.schedule_action('install') except StateCheckError: pass",
"if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return",
"disk and amount of storage reserved = node_sal.find_persistance() def usable_storagepool(sp): if sp.name ==",
"namespace_name = j.data.idgenerator.generateGUID() if not name else name zdb_name = j.data.idgenerator.generateGUID() zdb_size =",
"is not healthy\") hostname = self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name data = { 'attributes':",
"GiB < zdb_size: return False if info['type'] not in disktypes: return False if",
"False return True # all storage pool path of type disktypes and with",
"\"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info') for zdb in zdbs] results =",
"['SSD', 'NVME'], } # get all usable filesystem path for this type of",
"we could find a place where to create a new zerodb # let's",
"zerodb service name :rtype: string \"\"\" zdb_data = { 'path': mountpoint, 'mode': mode,",
"node_capacity service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install',",
"for sp in storagepools: try: fs = sp.get('zdb') fs_paths.append(fs.path) except ValueError: pass #",
"0: message = 'Not enough free space for namespace creation with size {}",
"message = 'Not enough free space for namespace creation with size {} and",
"'namespaces': namespaces } zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\"",
":type disktype: string :param size: size of the zerodb :type size: int :param",
"size of the zerodb :type size: int :param name: zerodb name :type name:",
"info: info['service_name'] != name, zdb_infos) # sort result by free size, first item",
"GiB) return fs.path raise RuntimeError(\"unsupported disktype:%s\" % disktype) def create_zdb_namespace(self, disktype, mode, password,",
"self._node_sal disks_types_map = { 'hdd': ['HDD', 'ARCHIVE'], 'ssd': ['SSD', 'NVME'], } # get",
"deploy the zerodb on :type disktype: string :param namespaces: list of namespaces to",
"zerodb service name that should be skipped :type excepted: [str] :return: a list",
"disktype: string :param size: size of the zerodb :type size: int :param name:",
"not in ['hdd', 'ssd']: raise ValueError('Disktype should be hdd or ssd') if mode",
"NoNamespaceAvailability(message) @timeout(30, error_message='info action timeout') def info(self): return self._node_sal.client.info.os() @timeout(30, error_message='stats action timeout')",
"ns_size, name='', zdb_size=None): if disktype not in ['hdd', 'ssd']: raise ValueError('Disktype should be",
"less used pool first fs_paths = [] for sp in storagepools: try: fs",
"ValueError('Network should have vlan configured') def send_alert(alertas, alert): for alerta in alertas: alerta.schedule_action('send_alert',",
"mountpoint = self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint, mode, zdb_size, disktype, [namespace]) return zdb_name,",
"reboot if self._node_sal.uptime() < self.data['uptime']: self.install() self.data['uptime'] = self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted',",
"allowed') self.state.delete('disks', 'mounted') network = self.data.get('network') if network: _validate_network(network) def _monitor(self): self.logger.info('Monitoring node",
"def __init__(self, name, guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30)",
"if not addr: continue nw = netaddr.IPNetwork(addr) if str(nw.ip) == mgmt_addr: mgmt_nic =",
"disktype, namespaces): \"\"\"Create a zerodb service :param name: zdb name :type name: string",
"[zdb.schedule_action('info') for zdb in zdbs] results = [] for t in tasks: result",
"j.data.idgenerator.generateGUID() zdb_size = zdb_size if zdb_size else ns_size namespace = { 'name': namespace_name,",
"'nic_mgmt_monitor' not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make sure the bridges are installed",
"storagepools = list(filter(usable_storagepool, node_sal.storagepools.list())) if not storagepools: raise ZDBPathNotFound( \"Could not find any",
"name='', zdb_size=None): if disktype not in ['hdd', 'ssd']: raise ValueError('Disktype should be hdd",
"info :param zdbinfo: [(service, dict)], optional :return: zerodb mountpoint, subvolume name :rtype: (string,",
"ssd') if mode not in ['seq', 'user', 'direct']: raise ValueError('ZDB mode should be",
"import netaddr import time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1'",
"zdb_infos) # sort result by free size, first item of the list is",
"already existing one pass def usable_zdb(info): if info['mode'] != mode: return False if",
"result['service_name'] = t.service.name results.append(result) return results def _validate_network(network): cidr = network.get('cidr') if cidr:",
"'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1'",
"ZDBPathNotFound as err: self.logger.warning(\"fail to create a 0-db namespace: %s\", str(err)) # at",
"any usable storage pool. Not enough space for disk type %s\" % disktype)",
"'event': 'Network', 'tags': [\"node:%s\" % hostname, \"node_id:%s\" % node_id, \"interface:%s\" % mgmt_nic['name']], 'service':",
"list of namespaces to create on the zerodb :type namespaces: [dict] :return: zerodb",
"one with bigger free size results = sorted(zdb_infos, key=lambda r: r['free'], reverse=True) zdb_paths",
"= 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local' GiB = 1024 ** 3",
"'Production', 'severity': 'critical', 'event': 'Network', 'tags': [\"node:%s\" % hostname, \"node_id:%s\" % node_id, \"interface:%s\"",
"from jumpscale import j from zerorobot import config from zerorobot.template.base import TemplateBase from",
"free = (sp.size - sp.total_quota()) / GiB if free <= size: return False",
"in nic.get('addrs'): addr = addr.get('addr') if not addr: continue nw = netaddr.IPNetwork(addr) if",
"free size, first item of the list is the the one with bigger",
"free size results = sorted(zdb_infos, key=lambda r: r['free'], reverse=True) zdb_paths = [res['path'] for",
"< zdb_size: return False if info['type'] not in disktypes: return False if not",
"not in disktypes: return False if not info['running']: return False return True zdbinfos",
"type {}'.format( ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message) # sort result by free size, first",
"service.name) service.schedule_action('install') except StateCheckError: pass # make sure the networks are configured for",
"already exists on all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30, error_message='info action timeout') def info(self):",
"= 'local' GiB = 1024 ** 3 class NoNamespaceAvailability(Exception): pass class Node(TemplateBase): version",
"timeout') def info(self): return self._node_sal.client.info.os() @timeout(30, error_message='stats action timeout') def stats(self): return self._node_sal.client.aggregator.query()",
"name, mountpoint, mode, zdb_size, disktype, namespaces): \"\"\"Create a zerodb service :param name: zdb",
"@retry(Exception, tries=2, delay=2) def install(self): self.logger.info('Installing node %s' % self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version())",
"mgmt_nic = None for nic in self._node_sal.client.info.nic(): for addr in nic.get('addrs'): addr =",
"True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return except StateCheckError: time.sleep(5) @retry(Exception,",
"be deployed on :type disktype: string :param size: size of the zerodb :type",
"raise NoNamespaceAvailability(message) @timeout(30, error_message='info action timeout') def info(self): return self._node_sal.client.info.os() @timeout(30, error_message='stats action",
"for zdb in zdbs] results = [] for t in tasks: result =",
"% service.name) service.schedule_action('configure') except StateCheckError: pass def _register(self): \"\"\" make sure the node_capacity",
"%s' % self.data['hostname']).get() self._node_sal.client.bash('echo %s > /etc/hostname' % self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime() self.state.set('actions',",
"{ 'attributes': {}, 'resource': hostname, 'text': 'network interface %s is down' % mgmt_nic['name'],",
"\"\"\" make sure the node_port_manager service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while",
"'install', 'ok') def reboot(self): self.logger.info('Rebooting node %s' % self.name) self._node_sal.reboot() def zdb_path(self, disktype,",
"filesystem path for this type of disk and amount of storage reserved =",
"amount of storage reserved = node_sal.find_persistance() def usable_storagepool(sp): if sp.name == reserved.name: return",
"self.recurring_action('_monitor', 30) # every 30 seconds self.recurring_action('_network_monitor', 120) # every 2 minutes self.gl_mgr.add(\"_register\",",
"template_name = 'node' def __init__(self, name, guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self._node_sal =",
"string :param zdbinfo: list of zerodb services and their info :param zdbinfo: [(service,",
"= ['HDD', 'ARCHIVE'] elif disktype == 'ssd': disktypes = ['SSD', 'NVME'] else: raise",
"mode: string :param zdb_size: size of the zerodb :type zdb_size: int :param disktype:",
":param namespaces: list of namespaces to create on the zerodb :type namespaces: [dict]",
"node is allowed') self.state.delete('disks', 'mounted') network = self.data.get('network') if network: _validate_network(network) def _monitor(self):",
"'install', 'ok') self.logger.info(\"network monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify connectivity of management interface\") mgmt_addr =",
"<= 0: self.logger.error(\"management interface is not healthy\") hostname = self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name",
"= 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID =",
"not supported\" % disktype) namespace_name = j.data.idgenerator.generateGUID() if not name else name zdb_name",
"% self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host name self._node_sal.client.system('hostname %s' % self.data['hostname']).get()",
"sp.type.value not in disks_types_map[disktype]: return False free = (sp.size - sp.total_quota()) / GiB",
"storage available storagepools = list(filter(usable_storagepool, node_sal.storagepools.list())) if not storagepools: raise ZDBPathNotFound( \"Could not",
"tries=2, delay=2) def install(self): self.logger.info('Installing node %s' % self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) #",
"raise ValueError('ZDB mode should be user, direct or seq') if disktype == 'hdd':",
"def _create_zdb(self, name, mountpoint, mode, zdb_size, disktype, namespaces): \"\"\"Create a zerodb service :param",
"the zerodb on :type disktype: string :param namespaces: list of namespaces to create",
"self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host name self._node_sal.client.system('hostname %s' % self.data['hostname']).get() self._node_sal.client.bash('echo",
"timeout') def os_version(self): return self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name, mountpoint, mode, zdb_size, disktype, namespaces):",
"not used by zerodb services but have a storagepool, so we can use",
"'hdd': # sort less used pool first fs_paths = [] for sp in",
"make sure the networks are configured for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install',",
"self.state.delete('disks', 'mounted') network = self.data.get('network') if network: _validate_network(network) def _monitor(self): self.logger.info('Monitoring node %s'",
"in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring bridge %s\" % service.name) service.schedule_action('install') except",
"isinstance(vlan, int): raise ValueError('Network should have vlan configured') def send_alert(alertas, alert): for alerta",
":rtype: [str] \"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info') for zdb in zdbs]",
"% disktype) namespace_name = j.data.idgenerator.generateGUID() if not name else name zdb_name = j.data.idgenerator.generateGUID()",
"_port_manager(self): \"\"\" make sure the node_port_manager service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait()",
"True zdbinfos = list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos) <= 0: message = 'Not enough",
"namespace_name message = 'Namespace {} already exists on all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30,",
"configured for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring network %s\" %",
"/ GiB if free <= size: return False return True # all storage",
"should be skipped :type excepted: [str] :return: a list of zerodb path sorted",
"service.schedule_action('install') except StateCheckError: pass # make sure the networks are configured for service",
"def _list_zdbs_info(self): \"\"\" list the paths used by all the zerodbs installed on",
"string :param mountpoint: zerodb mountpoint :type mountpoint: string :param mode: zerodb mode :type",
"and their info :param zdbinfo: [(service, dict)], optional :return: zerodb mountpoint, subvolume name",
"self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) # every 30 seconds self.recurring_action('_network_monitor', 120) # every",
"sure the node_capacity service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try:",
"mgmt_nic or 'up' not in mgmt_nic.get('flags', []) or mgmt_nic.get('speed') <= 0: self.logger.error(\"management interface",
"zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\" list the paths used by all the zerodbs installed",
"= sorted(zdb_infos, key=lambda r: r['free'], reverse=True) zdb_paths = [res['path'] for res in results]",
"'tags': [\"node:%s\" % hostname, \"node_id:%s\" % node_id, \"interface:%s\" % mgmt_nic['name']], 'service': [self.template_uid.name] }",
"type of the disk to deploy the zerodb on :type disktype: string :param",
"by a zerodb\") return free_path[0] if disktype == 'ssd': fs = storagepools[0].create('zdb_{}'.format(name), size",
"== 'ssd': disktypes = ['SSD', 'NVME'] else: raise ValueError(\"disk type %s not supported\"",
"% hostname, \"node_id:%s\" % node_id, \"interface:%s\" % mgmt_nic['name']], 'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data)",
"StateCheckError import netaddr import time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID =",
"'sync': False, 'diskType': disktype, 'size': zdb_size, 'namespaces': namespaces } zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name,",
"def _validate_network(network): cidr = network.get('cidr') if cidr: netaddr.IPNetwork(cidr) vlan = network.get('vlan') if not",
"name :type name: string :param mountpoint: zerodb mountpoint :type mountpoint: string :param mode:",
"% disktype) def create_zdb_namespace(self, disktype, mode, password, public, ns_size, name='', zdb_size=None): if disktype",
"skipped :type excepted: [str] :return: a list of zerodb path sorted by free",
"['HDD', 'ARCHIVE'] elif disktype == 'ssd': disktypes = ['SSD', 'NVME'] else: raise ValueError(\"disk",
"'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return except StateCheckError: time.sleep(5) @retry(Exception, tries=2, delay=2) def install(self):",
"import time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID =",
"not in mgmt_nic.get('flags', []) or mgmt_nic.get('speed') <= 0: self.logger.error(\"management interface is not healthy\")",
"'ssd']: raise ValueError('Disktype should be hdd or ssd') if mode not in ['seq',",
"zdb_paths = [res['path'] for res in results] # path that are not used",
"% self.data['hostname']).get() self._node_sal.client.bash('echo %s > /etc/hostname' % self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime() self.state.set('actions', 'install',",
"disktype) storagepools.sort(key=lambda sp: sp.size - sp.total_quota(), reverse=True) if disktype == 'hdd': # sort",
"or ssd') if mode not in ['seq', 'user', 'direct']: raise ValueError('ZDB mode should",
"that are not used by zerodb services but have a storagepool, so we",
"zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces = [ns['name'] for ns in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name",
"action timeout') def info(self): return self._node_sal.client.info.os() @timeout(30, error_message='stats action timeout') def stats(self): return",
"'environment': 'Production', 'severity': 'critical', 'event': 'Network', 'tags': [\"node:%s\" % hostname, \"node_id:%s\" % node_id,",
"service per node is allowed') self.state.delete('disks', 'mounted') network = self.data.get('network') if network: _validate_network(network)",
"self.data['uptime']: self.install() self.data['uptime'] = self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok') except: self.state.delete('disks', 'mounted')",
"mgmt_nic['name']], 'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor' not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor)",
"j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) # every 30 seconds self.recurring_action('_network_monitor', 120) # every 2 minutes",
"'install', 'ok') self.logger.info(\"configuring bridge %s\" % service.name) service.schedule_action('install') except StateCheckError: pass # make",
"self.logger.info('Installing node %s' % self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host name self._node_sal.client.system('hostname",
"%s > /etc/hostname' % self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime() self.state.set('actions', 'install', 'ok') def reboot(self):",
"are installed for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring bridge %s\"",
"zdb_infos = filter(lambda info: info['service_name'] != name, zdb_infos) # sort result by free",
"namespace_name except ZDBPathNotFound as err: self.logger.warning(\"fail to create a 0-db namespace: %s\", str(err))",
"self.name) self._node_sal.reboot() def zdb_path(self, disktype, size, name): \"\"\"Create zdb mounpoint and subvolume :param",
"= '0.0.1' template_name = 'node' def __init__(self, name, guid=None, data=None): super().__init__(name=name, guid=guid, data=data)",
"action timeout') def os_version(self): return self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name, mountpoint, mode, zdb_size, disktype,",
"service.name) service.schedule_action('configure') except StateCheckError: pass def _register(self): \"\"\" make sure the node_capacity service",
"where to create a new zerodb # let's look at the already existing",
"raise RuntimeError(\"unsupported disktype:%s\" % disktype) def create_zdb_namespace(self, disktype, mode, password, public, ns_size, name='',",
"name :type name: string :param zdbinfo: list of zerodb services and their info",
"dict)], optional :return: zerodb mountpoint, subvolume name :rtype: (string, string) \"\"\" node_sal =",
"['hdd', 'ssd']: raise ValueError('Disktype should be hdd or ssd') if mode not in",
"'hdd': ['HDD', 'ARCHIVE'], 'ssd': ['SSD', 'NVME'], } # get all usable filesystem path",
"per node is allowed') self.state.delete('disks', 'mounted') network = self.data.get('network') if network: _validate_network(network) def",
"path that are not used by zerodb services but have a storagepool, so",
"not addr: continue nw = netaddr.IPNetwork(addr) if str(nw.ip) == mgmt_addr: mgmt_nic = nic",
"usable filesystem path for this type of disk and amount of storage reserved",
"= list(filter(usable_storagepool, node_sal.storagepools.list())) if not storagepools: raise ZDBPathNotFound( \"Could not find any usable",
"action timeout') def processes(self): return self._node_sal.client.process.list() @timeout(30, error_message='os_version action timeout') def os_version(self): return",
"timeout') def processes(self): return self._node_sal.client.process.list() @timeout(30, error_message='os_version action timeout') def os_version(self): return self._node_sal.client.ping()[13:].strip()",
"storage pool. Not enough space for disk type %s\" % disktype) storagepools.sort(key=lambda sp:",
"zerodb # let's look at the already existing one pass def usable_zdb(info): if",
"import TemplateBase from zerorobot.template.decorator import retry, timeout from zerorobot.template.state import StateCheckError import netaddr",
"'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1'",
"service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring bridge %s\" % service.name) service.schedule_action('install') except StateCheckError: pass #",
"= { 'hdd': ['HDD', 'ARCHIVE'], 'ssd': ['SSD', 'NVME'], } # get all usable",
"mounpoint and subvolume :param disktype: type of the disk the zerodb will be",
"sort result by free size, first item of the list is the the",
"size, first item of the list is the the one with bigger free",
"@timeout(30, error_message='info action timeout') def info(self): return self._node_sal.client.info.os() @timeout(30, error_message='stats action timeout') def",
"self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action timeout') def processes(self): return self._node_sal.client.process.list() @timeout(30, error_message='os_version action timeout')",
"have vlan configured') def send_alert(alertas, alert): for alerta in alertas: alerta.schedule_action('send_alert', args={'data': alert})",
"'ok') except: self.state.delete('disks', 'mounted') def _network_monitor(self): self.state.check('actions', 'install', 'ok') self.logger.info(\"network monitor\") def nic_mgmt_monitor():",
"a 0-db namespace: %s\", str(err)) # at this point we could find a",
"of management interface\") mgmt_addr = self._node_sal.management_address mgmt_nic = None for nic in self._node_sal.client.info.nic():",
"return except StateCheckError: time.sleep(5) @retry(Exception, tries=2, delay=2) def install(self): self.logger.info('Installing node %s' %",
"time.sleep(5) @retry(Exception, tries=2, delay=2) def install(self): self.logger.info('Installing node %s' % self.name) self.data['version'] =",
"in sorted(zdbinfos, key=lambda r: r['free'], reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces = [ns['name']",
"'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local' GiB = 1024",
"except: self.state.delete('disks', 'mounted') def _network_monitor(self): self.state.check('actions', 'install', 'ok') self.logger.info(\"network monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify",
"[str] :return: a list of zerodb path sorted by free size descending :rtype:",
"one node service per node is allowed') self.state.delete('disks', 'mounted') network = self.data.get('network') if",
"zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name, namespace_name message = 'Namespace {} already exists on all",
"zerodb service :param name: zdb name :type name: string :param mountpoint: zerodb mountpoint",
"name that should be skipped :type excepted: [str] :return: a list of zerodb",
"size: size of the zerodb :type size: int :param name: zerodb name :type",
"jumpscale import j from zerorobot import config from zerorobot.template.base import TemplateBase from zerorobot.template.decorator",
"pass # no zdb filesystem on this storagepool # all path used by",
"name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\" list the paths used by all",
"zerodb mountpoint, subvolume name :rtype: (string, string) \"\"\" node_sal = self._node_sal disks_types_map =",
"self.data['uptime'] = self._node_sal.uptime() self.state.set('actions', 'install', 'ok') def reboot(self): self.logger.info('Rebooting node %s' % self.name)",
"name, guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) # every",
"and nodes[0].guid != self.guid: raise RuntimeError('Another node service exists. Only one node service",
"self._node_sal.uptime() self.state.set('actions', 'install', 'ok') def reboot(self): self.logger.info('Rebooting node %s' % self.name) self._node_sal.reboot() def",
"services and their info :param zdbinfo: [(service, dict)], optional :return: zerodb mountpoint, subvolume",
"[(service, dict)], optional :return: zerodb mountpoint, subvolume name :rtype: (string, string) \"\"\" node_sal",
"data = { 'attributes': {}, 'resource': hostname, 'text': 'network interface %s is down'",
"storage pool path of type disktypes and with more then size storage available",
"raise ZDBPathNotFound( \"Could not find any usable storage pool. Not enough space for",
"pool first fs_paths = [] for sp in storagepools: try: fs = sp.get('zdb')",
"filter(lambda info: info['service_name'] != name, zdb_infos) # sort result by free size, first",
"at the already existing one pass def usable_zdb(info): if info['mode'] != mode: return",
"service name :rtype: string \"\"\" zdb_data = { 'path': mountpoint, 'mode': mode, 'sync':",
"we can use them free_path = list(set(fs_paths) - set(zdb_paths)) if len(free_path) <= 0:",
"return False if not info['running']: return False return True zdbinfos = list(filter(usable_zdb, self._list_zdbs_info()))",
"False if not info['running']: return False return True zdbinfos = list(filter(usable_zdb, self._list_zdbs_info())) if",
"self.logger.info(\"configuring bridge %s\" % service.name) service.schedule_action('install') except StateCheckError: pass # make sure the",
"storagepool # all path used by installed zerodb services zdb_infos = self._list_zdbs_info() zdb_infos",
"120) # every 2 minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self): nodes =",
"= self.api.services.find(template_name='node') if nodes and nodes[0].guid != self.guid: raise RuntimeError('Another node service exists.",
"but have a storagepool, so we can use them free_path = list(set(fs_paths) -",
"create on the zerodb :type namespaces: [dict] :return: zerodb service name :rtype: string",
"network %s\" % service.name) service.schedule_action('configure') except StateCheckError: pass def _register(self): \"\"\" make sure",
"time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1'",
"ns in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name, namespace_name",
"by all the zerodbs installed on the node :param excepted: list of zerodb",
"point we could find a place where to create a new zerodb #",
":type name: string :param mountpoint: zerodb mountpoint :type mountpoint: string :param mode: zerodb",
":param zdbinfo: [(service, dict)], optional :return: zerodb mountpoint, subvolume name :rtype: (string, string)",
"storagepool, so we can use them free_path = list(set(fs_paths) - set(zdb_paths)) if len(free_path)",
"0: raise ZDBPathNotFound(\"all storagepools are already used by a zerodb\") return free_path[0] if",
"ValueError(\"disk type %s not supported\" % disktype) namespace_name = j.data.idgenerator.generateGUID() if not name",
"zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30, error_message='info action timeout') def info(self): return self._node_sal.client.info.os() @timeout(30, error_message='stats",
"supported\" % disktype) namespace_name = j.data.idgenerator.generateGUID() if not name else name zdb_name =",
"zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\" list the paths",
"% service.name) service.schedule_action('install') except StateCheckError: pass # make sure the networks are configured",
"disktype == 'ssd': fs = storagepools[0].create('zdb_{}'.format(name), size * GiB) return fs.path raise RuntimeError(\"unsupported",
"try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok') except: self.state.delete('disks', 'mounted') def _network_monitor(self): self.state.check('actions', 'install', 'ok')",
"free <= size: return False return True # all storage pool path of",
"for ns in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name,",
"in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring network %s\" % service.name) service.schedule_action('configure') except",
"error_message='processes action timeout') def processes(self): return self._node_sal.client.process.list() @timeout(30, error_message='os_version action timeout') def os_version(self):",
"self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make sure the bridges are installed for service in",
"= None for nic in self._node_sal.client.info.nic(): for addr in nic.get('addrs'): addr = addr.get('addr')",
"t.wait(timeout=120, die=True).result result['service_name'] = t.service.name results.append(result) return results def _validate_network(network): cidr = network.get('cidr')",
"netaddr.IPNetwork(addr) if str(nw.ip) == mgmt_addr: mgmt_nic = nic break self.logger.info(mgmt_nic) if not mgmt_nic",
"except StateCheckError: time.sleep(5) def _port_manager(self): \"\"\" make sure the node_port_manager service is installed",
"except StateCheckError: time.sleep(5) @retry(Exception, tries=2, delay=2) def install(self): self.logger.info('Installing node %s' % self.name)",
"if disktype not in ['hdd', 'ssd']: raise ValueError('Disktype should be hdd or ssd')",
"except StateCheckError: pass # make sure the networks are configured for service in",
"size descending :rtype: [str] \"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info') for zdb",
"'ssd': fs = storagepools[0].create('zdb_{}'.format(name), size * GiB) return fs.path raise RuntimeError(\"unsupported disktype:%s\" %",
"fs.path raise RuntimeError(\"unsupported disktype:%s\" % disktype) def create_zdb_namespace(self, disktype, mode, password, public, ns_size,",
"results = sorted(zdb_infos, key=lambda r: r['free'], reverse=True) zdb_paths = [res['path'] for res in",
"= { 'name': namespace_name, 'size': ns_size, 'password': password, 'public': public, } try: mountpoint",
"# every 30 seconds self.recurring_action('_network_monitor', 120) # every 2 minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\",",
"= addr.get('addr') if not addr: continue nw = netaddr.IPNetwork(addr) if str(nw.ip) == mgmt_addr:",
"return False return True # all storage pool path of type disktypes and",
"sp.get('zdb') fs_paths.append(fs.path) except ValueError: pass # no zdb filesystem on this storagepool #",
"%s' % self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host name self._node_sal.client.system('hostname %s' %",
"% self.name) self._node_sal.reboot() def zdb_path(self, disktype, size, name): \"\"\"Create zdb mounpoint and subvolume",
"if info['type'] not in disktypes: return False if not info['running']: return False return",
"type of disk and amount of storage reserved = node_sal.find_persistance() def usable_storagepool(sp): if",
"['seq', 'user', 'direct']: raise ValueError('ZDB mode should be user, direct or seq') if",
"on :type disktype: string :param size: size of the zerodb :type size: int",
"size * GiB) return fs.path raise RuntimeError(\"unsupported disktype:%s\" % disktype) def create_zdb_namespace(self, disktype,",
"= self._node_sal disks_types_map = { 'hdd': ['HDD', 'ARCHIVE'], 'ssd': ['SSD', 'NVME'], } #",
"{}, 'resource': hostname, 'text': 'network interface %s is down' % mgmt_nic['name'], 'environment': 'Production',",
"'ARCHIVE'] elif disktype == 'ssd': disktypes = ['SSD', 'NVME'] else: raise ValueError(\"disk type",
"raise ValueError(\"disk type %s not supported\" % disktype) namespace_name = j.data.idgenerator.generateGUID() if not",
"[ns['name'] for ns in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return",
"self._node_sal.management_address mgmt_nic = None for nic in self._node_sal.client.info.nic(): for addr in nic.get('addrs'): addr",
"zdb_size if zdb_size else ns_size namespace = { 'name': namespace_name, 'size': ns_size, 'password':",
"type %s not supported\" % disktype) namespace_name = j.data.idgenerator.generateGUID() if not name else",
"namespace creation with size {} and type {}'.format( ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message) #",
"[] for t in tasks: result = t.wait(timeout=120, die=True).result result['service_name'] = t.service.name results.append(result)",
"return True zdbinfos = list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos) <= 0: message = 'Not",
"= 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID =",
"for this type of disk and amount of storage reserved = node_sal.find_persistance() def",
"node %s' % self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host name self._node_sal.client.system('hostname %s'",
"** 3 class NoNamespaceAvailability(Exception): pass class Node(TemplateBase): version = '0.0.1' template_name = 'node'",
"'install', 'ok') # check for reboot if self._node_sal.uptime() < self.data['uptime']: self.install() self.data['uptime'] =",
"reserved.name: return False if sp.type.value not in disks_types_map[disktype]: return False free = (sp.size",
"self._node_sal.name data = { 'attributes': {}, 'resource': hostname, 'text': 'network interface %s is",
"= self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\" list the paths used",
"fs_paths = [] for sp in storagepools: try: fs = sp.get('zdb') fs_paths.append(fs.path) except",
"zerorobot.template.decorator import retry, timeout from zerorobot.template.state import StateCheckError import netaddr import time CONTAINER_TEMPLATE_UID",
"sure the networks are configured for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok')",
"[res['path'] for res in results] # path that are not used by zerodb",
"disktype, [namespace]) return zdb_name, namespace_name except ZDBPathNotFound as err: self.logger.warning(\"fail to create a",
"with bigger free size for zdbinfo in sorted(zdbinfos, key=lambda r: r['free'], reverse=True): zdb",
"in ['seq', 'user', 'direct']: raise ValueError('ZDB mode should be user, direct or seq')",
"zdb_name, namespace_name except ZDBPathNotFound as err: self.logger.warning(\"fail to create a 0-db namespace: %s\",",
"at this point we could find a place where to create a new",
"by free size descending :rtype: [str] \"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info')",
"error_message='os_version action timeout') def os_version(self): return self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name, mountpoint, mode, zdb_size,",
"GiB = 1024 ** 3 class NoNamespaceAvailability(Exception): pass class Node(TemplateBase): version = '0.0.1'",
"def reboot(self): self.logger.info('Rebooting node %s' % self.name) self._node_sal.reboot() def zdb_path(self, disktype, size, name):",
"is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID,",
"= self._list_zdbs_info() zdb_infos = filter(lambda info: info['service_name'] != name, zdb_infos) # sort result",
"path of type disktypes and with more then size storage available storagepools =",
"disktypes: return False if not info['running']: return False return True zdbinfos = list(filter(usable_zdb,",
"list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos) <= 0: message = 'Not enough free space for",
"service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring network %s\" % service.name) service.schedule_action('configure') except StateCheckError: pass def",
"minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self): nodes = self.api.services.find(template_name='node') if nodes and",
"name): \"\"\"Create zdb mounpoint and subvolume :param disktype: type of the disk the",
"= sp.get('zdb') fs_paths.append(fs.path) except ValueError: pass # no zdb filesystem on this storagepool",
"elif disktype == 'ssd': disktypes = ['SSD', 'NVME'] else: raise ValueError(\"disk type %s",
"'name': namespace_name, 'size': ns_size, 'password': password, 'public': public, } try: mountpoint = self.zdb_path(disktype,",
"ns_size, 'password': password, 'public': public, } try: mountpoint = self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name,",
"key=lambda r: r['free'], reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces = [ns['name'] for ns",
"node :param excepted: list of zerodb service name that should be skipped :type",
"[dict] :return: zerodb service name :rtype: string \"\"\" zdb_data = { 'path': mountpoint,",
"'direct']: raise ValueError('ZDB mode should be user, direct or seq') if disktype ==",
"public, } try: mountpoint = self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint, mode, zdb_size, disktype,",
"addr.get('addr') if not addr: continue nw = netaddr.IPNetwork(addr) if str(nw.ip) == mgmt_addr: mgmt_nic",
"'NVME'], } # get all usable filesystem path for this type of disk",
"be hdd or ssd') if mode not in ['seq', 'user', 'direct']: raise ValueError('ZDB",
"all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30, error_message='info action timeout') def info(self): return self._node_sal.client.info.os() @timeout(30,",
"of zerodb service name that should be skipped :type excepted: [str] :return: a",
"raise ValueError('Disktype should be hdd or ssd') if mode not in ['seq', 'user',",
"zerodb :type zdb_size: int :param disktype: type of the disk to deploy the",
"= { 'attributes': {}, 'resource': hostname, 'text': 'network interface %s is down' %",
"# make sure the bridges are installed for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions',",
"the the one with bigger free size results = sorted(zdb_infos, key=lambda r: r['free'],",
"not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make sure the bridges are installed for",
"be user, direct or seq') if disktype == 'hdd': disktypes = ['HDD', 'ARCHIVE']",
"= ['SSD', 'NVME'] else: raise ValueError(\"disk type %s not supported\" % disktype) namespace_name",
"info['service_name'] != name, zdb_infos) # sort result by free size, first item of",
"'NVME'] else: raise ValueError(\"disk type %s not supported\" % disktype) namespace_name = j.data.idgenerator.generateGUID()",
"self.logger.warning(\"fail to create a 0-db namespace: %s\", str(err)) # at this point we",
"result = t.wait(timeout=120, die=True).result result['service_name'] = t.service.name results.append(result) return results def _validate_network(network): cidr",
"break self.logger.info(mgmt_nic) if not mgmt_nic or 'up' not in mgmt_nic.get('flags', []) or mgmt_nic.get('speed')",
"% self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime() self.state.set('actions', 'install', 'ok') def reboot(self): self.logger.info('Rebooting node %s'",
"Set host name self._node_sal.client.system('hostname %s' % self.data['hostname']).get() self._node_sal.client.bash('echo %s > /etc/hostname' % self.data['hostname']).get()",
"services but have a storagepool, so we can use them free_path = list(set(fs_paths)",
"return self._node_sal.client.process.list() @timeout(30, error_message='os_version action timeout') def os_version(self): return self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name,",
"namespaces to create on the zerodb :type namespaces: [dict] :return: zerodb service name",
"node_sal.storagepools.list())) if not storagepools: raise ZDBPathNotFound( \"Could not find any usable storage pool.",
"a new zerodb # let's look at the already existing one pass def",
"= list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos) <= 0: message = 'Not enough free space",
"on the zerodb :type namespaces: [dict] :return: zerodb service name :rtype: string \"\"\"",
"[str] \"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info') for zdb in zdbs] results",
"self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info') for zdb in zdbs] results = [] for t",
"# all storage pool path of type disktypes and with more then size",
"else ns_size namespace = { 'name': namespace_name, 'size': ns_size, 'password': password, 'public': public,",
"disk to deploy the zerodb on :type disktype: string :param namespaces: list of",
"mgmt_nic = nic break self.logger.info(mgmt_nic) if not mgmt_nic or 'up' not in mgmt_nic.get('flags',",
"disktype == 'hdd': disktypes = ['HDD', 'ARCHIVE'] elif disktype == 'ssd': disktypes =",
"self.guid: raise RuntimeError('Another node service exists. Only one node service per node is",
"fs = sp.get('zdb') fs_paths.append(fs.path) except ValueError: pass # no zdb filesystem on this",
"reserved = node_sal.find_persistance() def usable_storagepool(sp): if sp.name == reserved.name: return False if sp.type.value",
"= list(set(fs_paths) - set(zdb_paths)) if len(free_path) <= 0: raise ZDBPathNotFound(\"all storagepools are already",
"from zerorobot import config from zerorobot.template.base import TemplateBase from zerorobot.template.decorator import retry, timeout",
"storagepools[0].create('zdb_{}'.format(name), size * GiB) return fs.path raise RuntimeError(\"unsupported disktype:%s\" % disktype) def create_zdb_namespace(self,",
"= self._node_sal.management_address mgmt_nic = None for nic in self._node_sal.client.info.nic(): for addr in nic.get('addrs'):",
"super().__init__(name=name, guid=guid, data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) # every 30 seconds self.recurring_action('_network_monitor',",
"of the zerodb :type size: int :param name: zerodb name :type name: string",
"that should be skipped :type excepted: [str] :return: a list of zerodb path",
"zerodb services and their info :param zdbinfo: [(service, dict)], optional :return: zerodb mountpoint,",
"network: _validate_network(network) def _monitor(self): self.logger.info('Monitoring node %s' % self.name) self.state.check('actions', 'install', 'ok') #",
"self.data['uptime'] = self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok') except: self.state.delete('disks', 'mounted') def _network_monitor(self):",
"%s\" % service.name) service.schedule_action('install') except StateCheckError: pass # make sure the networks are",
"self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok') except: self.state.delete('disks', 'mounted') def _network_monitor(self): self.state.check('actions', 'install',",
"storagepools are already used by a zerodb\") return free_path[0] if disktype == 'ssd':",
"self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name data = { 'attributes': {}, 'resource': hostname, 'text': 'network",
"the one with bigger free size for zdbinfo in sorted(zdbinfos, key=lambda r: r['free'],",
"'node' def __init__(self, name, guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor',",
"'ok') self.logger.info(\"configuring bridge %s\" % service.name) service.schedule_action('install') except StateCheckError: pass # make sure",
"namespace_name not in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name, namespace_name message = 'Namespace {}",
"0-db namespace: %s\", str(err)) # at this point we could find a place",
"'Network', 'tags': [\"node:%s\" % hostname, \"node_id:%s\" % node_id, \"interface:%s\" % mgmt_nic['name']], 'service': [self.template_uid.name]",
"public=True) return except StateCheckError: time.sleep(5) def _port_manager(self): \"\"\" make sure the node_port_manager service",
"'mode': mode, 'sync': False, 'diskType': disktype, 'size': zdb_size, 'namespaces': namespaces } zdb =",
"if not isinstance(vlan, int): raise ValueError('Network should have vlan configured') def send_alert(alertas, alert):",
"in storagepools: try: fs = sp.get('zdb') fs_paths.append(fs.path) except ValueError: pass # no zdb",
"zerodb name :type name: string :param zdbinfo: list of zerodb services and their",
"mode not in ['seq', 'user', 'direct']: raise ValueError('ZDB mode should be user, direct",
"zdbinfos = list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos) <= 0: message = 'Not enough free",
"sorted(zdbinfos, key=lambda r: r['free'], reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces = [ns['name'] for",
"first fs_paths = [] for sp in storagepools: try: fs = sp.get('zdb') fs_paths.append(fs.path)",
"<= 0: message = 'Not enough free space for namespace creation with size",
"reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces = [ns['name'] for ns in zdb.schedule_action('namespace_list').wait(die=True).result] if",
"mode :type mode: string :param zdb_size: size of the zerodb :type zdb_size: int",
"in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name, namespace_name message = 'Namespace {} already exists",
"if disktype == 'hdd': # sort less used pool first fs_paths = []",
"not info['running']: return False return True zdbinfos = list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos) <=",
"raise ValueError('Network should have vlan configured') def send_alert(alertas, alert): for alerta in alertas:",
"= [] for sp in storagepools: try: fs = sp.get('zdb') fs_paths.append(fs.path) except ValueError:",
"self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self): nodes = self.api.services.find(template_name='node') if nodes and nodes[0].guid != self.guid:",
"self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True) return except StateCheckError: time.sleep(5) def _port_manager(self):",
"\"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={},",
"self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return except StateCheckError: time.sleep(5) @retry(Exception, tries=2, delay=2) def install(self): self.logger.info('Installing",
"= 1024 ** 3 class NoNamespaceAvailability(Exception): pass class Node(TemplateBase): version = '0.0.1' template_name",
"mode, password, public, ns_size, name='', zdb_size=None): if disktype not in ['hdd', 'ssd']: raise",
"'ARCHIVE'], 'ssd': ['SSD', 'NVME'], } # get all usable filesystem path for this",
"self.state.check('actions', 'install', 'ok') self.logger.info(\"network monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify connectivity of management interface\") mgmt_addr",
"usable_storagepool(sp): if sp.name == reserved.name: return False if sp.type.value not in disks_types_map[disktype]: return",
"namespace).wait(die=True) return zdb.name, namespace_name message = 'Namespace {} already exists on all zerodbs'.format(namespace_name)",
"for zdbinfo in sorted(zdbinfos, key=lambda r: r['free'], reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces",
"zdb.name, namespace_name message = 'Namespace {} already exists on all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message)",
"free size descending :rtype: [str] \"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info') for",
"'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor' not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) #",
"so we can use them free_path = list(set(fs_paths) - set(zdb_paths)) if len(free_path) <=",
"installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager',",
"create a 0-db namespace: %s\", str(err)) # at this point we could find",
"service :param name: zdb name :type name: string :param mountpoint: zerodb mountpoint :type",
":type namespaces: [dict] :return: zerodb service name :rtype: string \"\"\" zdb_data = {",
"# no zdb filesystem on this storagepool # all path used by installed",
"def send_alert(alertas, alert): for alerta in alertas: alerta.schedule_action('send_alert', args={'data': alert}) class ZDBPathNotFound(Exception): pass",
"mountpoint: string :param mode: zerodb mode :type mode: string :param zdb_size: size of",
"from zerorobot.template.state import StateCheckError import netaddr import time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID =",
"% disktype) storagepools.sort(key=lambda sp: sp.size - sp.total_quota(), reverse=True) if disktype == 'hdd': #",
"can use them free_path = list(set(fs_paths) - set(zdb_paths)) if len(free_path) <= 0: raise",
"the disk the zerodb will be deployed on :type disktype: string :param size:",
"% mgmt_nic['name']], 'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor' not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor',",
"False if info['type'] not in disktypes: return False if not info['running']: return False",
"NoNamespaceAvailability(message) # sort result by free size, first item of the list is",
"# make sure the networks are configured for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions',",
"= self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info') for zdb in zdbs] results = [] for",
"to deploy the zerodb on :type disktype: string :param namespaces: list of namespaces",
"ZDBPathNotFound(\"all storagepools are already used by a zerodb\") return free_path[0] if disktype ==",
"zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info') for zdb in zdbs] results = []",
"them free_path = list(set(fs_paths) - set(zdb_paths)) if len(free_path) <= 0: raise ZDBPathNotFound(\"all storagepools",
"3 class NoNamespaceAvailability(Exception): pass class Node(TemplateBase): version = '0.0.1' template_name = 'node' def",
"path used by installed zerodb services zdb_infos = self._list_zdbs_info() zdb_infos = filter(lambda info:",
"_validate_network(network) def _monitor(self): self.logger.info('Monitoring node %s' % self.name) self.state.check('actions', 'install', 'ok') # check",
"string) \"\"\" node_sal = self._node_sal disks_types_map = { 'hdd': ['HDD', 'ARCHIVE'], 'ssd': ['SSD',",
"<= size: return False return True # all storage pool path of type",
"this point we could find a place where to create a new zerodb",
"%s' % self.name) self._node_sal.reboot() def zdb_path(self, disktype, size, name): \"\"\"Create zdb mounpoint and",
"{ 'path': mountpoint, 'mode': mode, 'sync': False, 'diskType': disktype, 'size': zdb_size, 'namespaces': namespaces",
"0: self.logger.error(\"management interface is not healthy\") hostname = self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name data",
"# at this point we could find a place where to create a",
"used by all the zerodbs installed on the node :param excepted: list of",
"def processes(self): return self._node_sal.client.process.list() @timeout(30, error_message='os_version action timeout') def os_version(self): return self._node_sal.client.ping()[13:].strip() def",
"node service per node is allowed') self.state.delete('disks', 'mounted') network = self.data.get('network') if network:",
"exists on all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30, error_message='info action timeout') def info(self): return",
"@timeout(30, error_message='processes action timeout') def processes(self): return self._node_sal.client.process.list() @timeout(30, error_message='os_version action timeout') def",
"tasks = [zdb.schedule_action('info') for zdb in zdbs] results = [] for t in",
"= storagepools[0].create('zdb_{}'.format(name), size * GiB) return fs.path raise RuntimeError(\"unsupported disktype:%s\" % disktype) def",
"exists. Only one node service per node is allowed') self.state.delete('disks', 'mounted') network =",
"'mounted') network = self.data.get('network') if network: _validate_network(network) def _monitor(self): self.logger.info('Monitoring node %s' %",
"if not mgmt_nic or 'up' not in mgmt_nic.get('flags', []) or mgmt_nic.get('speed') <= 0:",
"version = '0.0.1' template_name = 'node' def __init__(self, name, guid=None, data=None): super().__init__(name=name, guid=guid,",
"for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring bridge %s\" % service.name)",
"disktype, 'size': zdb_size, 'namespaces': namespaces } zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True)",
"zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\" list the paths used by all the",
"config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return except StateCheckError:",
"t.service.name results.append(result) return results def _validate_network(network): cidr = network.get('cidr') if cidr: netaddr.IPNetwork(cidr) vlan",
"interface\") mgmt_addr = self._node_sal.management_address mgmt_nic = None for nic in self._node_sal.client.info.nic(): for addr",
"self.logger.info(\"network monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify connectivity of management interface\") mgmt_addr = self._node_sal.management_address mgmt_nic",
"service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok')",
"len(zdbinfos) <= 0: message = 'Not enough free space for namespace creation with",
"zerodb services zdb_infos = self._list_zdbs_info() zdb_infos = filter(lambda info: info['service_name'] != name, zdb_infos)",
"disktype: string :param namespaces: list of namespaces to create on the zerodb :type",
"def _network_monitor(self): self.state.check('actions', 'install', 'ok') self.logger.info(\"network monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify connectivity of management",
"if free <= size: return False return True # all storage pool path",
"used by a zerodb\") return free_path[0] if disktype == 'ssd': fs = storagepools[0].create('zdb_{}'.format(name),",
"self.recurring_action('_network_monitor', 120) # every 2 minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self): nodes",
"disktypes and with more then size storage available storagepools = list(filter(usable_storagepool, node_sal.storagepools.list())) if",
"\"node_id:%s\" % node_id, \"interface:%s\" % mgmt_nic['name']], 'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor'",
":param zdbinfo: list of zerodb services and their info :param zdbinfo: [(service, dict)],",
"[\"node:%s\" % hostname, \"node_id:%s\" % node_id, \"interface:%s\" % mgmt_nic['name']], 'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'),",
"create a new zerodb # let's look at the already existing one pass",
"size results = sorted(zdb_infos, key=lambda r: r['free'], reverse=True) zdb_paths = [res['path'] for res",
"size: int :param name: zerodb name :type name: string :param zdbinfo: list of",
"password, public, ns_size, name='', zdb_size=None): if disktype not in ['hdd', 'ssd']: raise ValueError('Disktype",
"def nic_mgmt_monitor(): self.logger.info(\"verify connectivity of management interface\") mgmt_addr = self._node_sal.management_address mgmt_nic = None",
"sp.total_quota()) / GiB if free <= size: return False return True # all",
"== reserved.name: return False if sp.type.value not in disks_types_map[disktype]: return False free =",
"or seq') if disktype == 'hdd': disktypes = ['HDD', 'ARCHIVE'] elif disktype ==",
"\"Could not find any usable storage pool. Not enough space for disk type",
"self.name) self.state.check('actions', 'install', 'ok') # check for reboot if self._node_sal.uptime() < self.data['uptime']: self.install()",
"stats(self): return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action timeout') def processes(self): return self._node_sal.client.process.list() @timeout(30, error_message='os_version",
":return: zerodb service name :rtype: string \"\"\" zdb_data = { 'path': mountpoint, 'mode':",
"for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring network %s\" % service.name)",
"vlan configured') def send_alert(alertas, alert): for alerta in alertas: alerta.schedule_action('send_alert', args={'data': alert}) class",
"of namespaces to create on the zerodb :type namespaces: [dict] :return: zerodb service",
"node service exists. Only one node service per node is allowed') self.state.delete('disks', 'mounted')",
"fs = storagepools[0].create('zdb_{}'.format(name), size * GiB) return fs.path raise RuntimeError(\"unsupported disktype:%s\" % disktype)",
"configured') def send_alert(alertas, alert): for alerta in alertas: alerta.schedule_action('send_alert', args={'data': alert}) class ZDBPathNotFound(Exception):",
"_validate_network(network): cidr = network.get('cidr') if cidr: netaddr.IPNetwork(cidr) vlan = network.get('vlan') if not isinstance(vlan,",
"self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return except StateCheckError: time.sleep(5) @retry(Exception, tries=2, delay=2)",
"sorted(zdb_infos, key=lambda r: r['free'], reverse=True) zdb_paths = [res['path'] for res in results] #",
"if 'nic_mgmt_monitor' not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make sure the bridges are",
"disks_types_map = { 'hdd': ['HDD', 'ARCHIVE'], 'ssd': ['SSD', 'NVME'], } # get all",
"mode: zerodb mode :type mode: string :param zdb_size: size of the zerodb :type",
"if disktype == 'ssd': fs = storagepools[0].create('zdb_{}'.format(name), size * GiB) return fs.path raise",
"self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint, mode, zdb_size, disktype, [namespace]) return zdb_name, namespace_name except",
"= t.wait(timeout=120, die=True).result result['service_name'] = t.service.name results.append(result) return results def _validate_network(network): cidr =",
"results.append(result) return results def _validate_network(network): cidr = network.get('cidr') if cidr: netaddr.IPNetwork(cidr) vlan =",
"self.api.services.find(template_name='node') if nodes and nodes[0].guid != self.guid: raise RuntimeError('Another node service exists. Only",
"for nic in self._node_sal.client.info.nic(): for addr in nic.get('addrs'): addr = addr.get('addr') if not",
"if mode not in ['seq', 'user', 'direct']: raise ValueError('ZDB mode should be user,",
"disktypes = ['SSD', 'NVME'] else: raise ValueError(\"disk type %s not supported\" % disktype)",
"!= self.guid: raise RuntimeError('Another node service exists. Only one node service per node",
"{ 'name': namespace_name, 'size': ns_size, 'password': password, 'public': public, } try: mountpoint =",
"'Namespace {} already exists on all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30, error_message='info action timeout')",
"'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True) return except StateCheckError: time.sleep(5) def _port_manager(self): \"\"\"",
"ValueError('Disktype should be hdd or ssd') if mode not in ['seq', 'user', 'direct']:",
"} send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor' not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make sure",
"service exists. Only one node service per node is allowed') self.state.delete('disks', 'mounted') network",
"info['mode'] != mode: return False if info['free'] / GiB < zdb_size: return False",
"service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring network %s\" % service.name) service.schedule_action('configure')",
"self._node_sal.uptime() < self.data['uptime']: self.install() self.data['uptime'] = self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok') except:",
"_register(self): \"\"\" make sure the node_capacity service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait()",
"of zerodb services and their info :param zdbinfo: [(service, dict)], optional :return: zerodb",
"by zerodb services but have a storagepool, so we can use them free_path",
"and type {}'.format( ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message) # sort result by free size,",
"string :param mode: zerodb mode :type mode: string :param zdb_size: size of the",
"return False if info['free'] / GiB < zdb_size: return False if info['type'] not",
"nodes = self.api.services.find(template_name='node') if nodes and nodes[0].guid != self.guid: raise RuntimeError('Another node service",
"pass def _register(self): \"\"\" make sure the node_capacity service is installed \"\"\" if",
"if sp.name == reserved.name: return False if sp.type.value not in disks_types_map[disktype]: return False",
"first item of the list is the the one with bigger free size",
"disktype:%s\" % disktype) def create_zdb_namespace(self, disktype, mode, password, public, ns_size, name='', zdb_size=None): if",
"action timeout') def stats(self): return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action timeout') def processes(self): return",
"mountpoint, mode, zdb_size, disktype, namespaces): \"\"\"Create a zerodb service :param name: zdb name",
"namespaces): \"\"\"Create a zerodb service :param name: zdb name :type name: string :param",
"\"\"\" make sure the node_capacity service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while",
":type disktype: string :param namespaces: list of namespaces to create on the zerodb",
"False return True zdbinfos = list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos) <= 0: message =",
"the zerodb :type zdb_size: int :param disktype: type of the disk to deploy",
"self._node_sal.client.bash('echo %s > /etc/hostname' % self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime() self.state.set('actions', 'install', 'ok') def",
"zdbinfo: [(service, dict)], optional :return: zerodb mountpoint, subvolume name :rtype: (string, string) \"\"\"",
":param mode: zerodb mode :type mode: string :param zdb_size: size of the zerodb",
"a zerodb service :param name: zdb name :type name: string :param mountpoint: zerodb",
"{} and type {}'.format( ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message) # sort result by free",
"list the paths used by all the zerodbs installed on the node :param",
"try: fs = sp.get('zdb') fs_paths.append(fs.path) except ValueError: pass # no zdb filesystem on",
"raise RuntimeError('Another node service exists. Only one node service per node is allowed')",
"zdb_size else ns_size namespace = { 'name': namespace_name, 'size': ns_size, 'password': password, 'public':",
"of the disk to deploy the zerodb on :type disktype: string :param namespaces:",
"'size': zdb_size, 'namespaces': namespaces } zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def",
"monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify connectivity of management interface\") mgmt_addr = self._node_sal.management_address mgmt_nic =",
"%s' % self.name) self.state.check('actions', 'install', 'ok') # check for reboot if self._node_sal.uptime() <",
"zdb_size, 'namespaces': namespaces } zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self):",
":type excepted: [str] :return: a list of zerodb path sorted by free size",
"len(free_path) <= 0: raise ZDBPathNotFound(\"all storagepools are already used by a zerodb\") return",
"self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring network %s\" % service.name) service.schedule_action('configure') except StateCheckError:",
"ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message) # sort result by free size, first item of",
"= network.get('cidr') if cidr: netaddr.IPNetwork(cidr) vlan = network.get('vlan') if not isinstance(vlan, int): raise",
"= 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT =",
"data=None): super().__init__(name=name, guid=guid, data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) # every 30 seconds",
"# sort result by free size, first item of the list is the",
"size {} and type {}'.format( ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message) # sort result by",
"if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True)",
"zdb_size, disktype, [namespace]) return zdb_name, namespace_name except ZDBPathNotFound as err: self.logger.warning(\"fail to create",
"nic break self.logger.info(mgmt_nic) if not mgmt_nic or 'up' not in mgmt_nic.get('flags', []) or",
"validate(self): nodes = self.api.services.find(template_name='node') if nodes and nodes[0].guid != self.guid: raise RuntimeError('Another node",
"disk type %s\" % disktype) storagepools.sort(key=lambda sp: sp.size - sp.total_quota(), reverse=True) if disktype",
"self._port_manager) def validate(self): nodes = self.api.services.find(template_name='node') if nodes and nodes[0].guid != self.guid: raise",
"\"\"\"Create a zerodb service :param name: zdb name :type name: string :param mountpoint:",
"excepted: list of zerodb service name that should be skipped :type excepted: [str]",
"name: zdb name :type name: string :param mountpoint: zerodb mountpoint :type mountpoint: string",
"disktype == 'ssd': disktypes = ['SSD', 'NVME'] else: raise ValueError(\"disk type %s not",
"name :rtype: (string, string) \"\"\" node_sal = self._node_sal disks_types_map = { 'hdd': ['HDD',",
"- set(zdb_paths)) if len(free_path) <= 0: raise ZDBPathNotFound(\"all storagepools are already used by",
"pool. Not enough space for disk type %s\" % disktype) storagepools.sort(key=lambda sp: sp.size",
"services zdb_infos = self._list_zdbs_info() zdb_infos = filter(lambda info: info['service_name'] != name, zdb_infos) #",
"self.logger.info(\"configuring network %s\" % service.name) service.schedule_action('configure') except StateCheckError: pass def _register(self): \"\"\" make",
"pass class Node(TemplateBase): version = '0.0.1' template_name = 'node' def __init__(self, name, guid=None,",
"self.logger.error(\"management interface is not healthy\") hostname = self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name data =",
"existing one pass def usable_zdb(info): if info['mode'] != mode: return False if info['free']",
"name: string :param mountpoint: zerodb mountpoint :type mountpoint: string :param mode: zerodb mode",
"mode, 'sync': False, 'diskType': disktype, 'size': zdb_size, 'namespaces': namespaces } zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID,",
"= j.data.idgenerator.generateGUID() if not name else name zdb_name = j.data.idgenerator.generateGUID() zdb_size = zdb_size",
"= self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces = [ns['name'] for ns in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not",
"for namespace creation with size {} and type {}'.format( ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message)",
":type mode: string :param zdb_size: size of the zerodb :type zdb_size: int :param",
"results def _validate_network(network): cidr = network.get('cidr') if cidr: netaddr.IPNetwork(cidr) vlan = network.get('vlan') if",
"} try: mountpoint = self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint, mode, zdb_size, disktype, [namespace])",
"network.get('vlan') if not isinstance(vlan, int): raise ValueError('Network should have vlan configured') def send_alert(alertas,",
"from zerorobot.template.decorator import retry, timeout from zerorobot.template.state import StateCheckError import netaddr import time",
"storagepools.sort(key=lambda sp: sp.size - sp.total_quota(), reverse=True) if disktype == 'hdd': # sort less",
":param size: size of the zerodb :type size: int :param name: zerodb name",
"and amount of storage reserved = node_sal.find_persistance() def usable_storagepool(sp): if sp.name == reserved.name:",
"node %s' % self.name) self.state.check('actions', 'install', 'ok') # check for reboot if self._node_sal.uptime()",
"node_id, \"interface:%s\" % mgmt_nic['name']], 'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor' not in",
"import retry, timeout from zerorobot.template.state import StateCheckError import netaddr import time CONTAINER_TEMPLATE_UID =",
"str(nw.ip) == mgmt_addr: mgmt_nic = nic break self.logger.info(mgmt_nic) if not mgmt_nic or 'up'",
"if str(nw.ip) == mgmt_addr: mgmt_nic = nic break self.logger.info(mgmt_nic) if not mgmt_nic or",
"'critical', 'event': 'Network', 'tags': [\"node:%s\" % hostname, \"node_id:%s\" % node_id, \"interface:%s\" % mgmt_nic['name']],",
"while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return except StateCheckError: time.sleep(5)",
"node %s' % self.name) self._node_sal.reboot() def zdb_path(self, disktype, size, name): \"\"\"Create zdb mounpoint",
"} # get all usable filesystem path for this type of disk and",
"mgmt_addr: mgmt_nic = nic break self.logger.info(mgmt_nic) if not mgmt_nic or 'up' not in",
"all storage pool path of type disktypes and with more then size storage",
":type zdb_size: int :param disktype: type of the disk to deploy the zerodb",
"zdb_infos = self._list_zdbs_info() zdb_infos = filter(lambda info: info['service_name'] != name, zdb_infos) # sort",
"by free size, first item of the list is the the one with",
"# let's look at the already existing one pass def usable_zdb(info): if info['mode']",
"is allowed') self.state.delete('disks', 'mounted') network = self.data.get('network') if network: _validate_network(network) def _monitor(self): self.logger.info('Monitoring",
"send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor' not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make sure the",
"public, ns_size, name='', zdb_size=None): if disktype not in ['hdd', 'ssd']: raise ValueError('Disktype should",
"False free = (sp.size - sp.total_quota()) / GiB if free <= size: return",
"zerodb on :type disktype: string :param namespaces: list of namespaces to create on",
"= 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID =",
"not name else name zdb_name = j.data.idgenerator.generateGUID() zdb_size = zdb_size if zdb_size else",
"info['free'] / GiB < zdb_size: return False if info['type'] not in disktypes: return",
"return self._node_sal.client.info.os() @timeout(30, error_message='stats action timeout') def stats(self): return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action",
"zdb_size, disktype, namespaces): \"\"\"Create a zerodb service :param name: zdb name :type name:",
"disktype: type of the disk the zerodb will be deployed on :type disktype:",
"= 'Not enough free space for namespace creation with size {} and type",
"'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local' GiB = 1024 ** 3 class NoNamespaceAvailability(Exception): pass class",
"self.state.delete('disks', 'mounted') def _network_monitor(self): self.state.check('actions', 'install', 'ok') self.logger.info(\"network monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify connectivity",
"this storagepool # all path used by installed zerodb services zdb_infos = self._list_zdbs_info()",
"zdb_size = zdb_size if zdb_size else ns_size namespace = { 'name': namespace_name, 'size':",
"def info(self): return self._node_sal.client.info.os() @timeout(30, error_message='stats action timeout') def stats(self): return self._node_sal.client.aggregator.query() @timeout(30,",
"then size storage available storagepools = list(filter(usable_storagepool, node_sal.storagepools.list())) if not storagepools: raise ZDBPathNotFound(",
"ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID",
":rtype: (string, string) \"\"\" node_sal = self._node_sal disks_types_map = { 'hdd': ['HDD', 'ARCHIVE'],",
"self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self): nodes = self.api.services.find(template_name='node') if nodes and nodes[0].guid",
"list of zerodb services and their info :param zdbinfo: [(service, dict)], optional :return:",
"StateCheckError: pass def _register(self): \"\"\" make sure the node_capacity service is installed \"\"\"",
"raise ZDBPathNotFound(\"all storagepools are already used by a zerodb\") return free_path[0] if disktype",
"if network: _validate_network(network) def _monitor(self): self.logger.info('Monitoring node %s' % self.name) self.state.check('actions', 'install', 'ok')",
"hdd or ssd') if mode not in ['seq', 'user', 'direct']: raise ValueError('ZDB mode",
"namespace = { 'name': namespace_name, 'size': ns_size, 'password': password, 'public': public, } try:",
"enough free space for namespace creation with size {} and type {}'.format( ns_size,",
"self.state.check('actions', 'install', 'ok') # check for reboot if self._node_sal.uptime() < self.data['uptime']: self.install() self.data['uptime']",
"class Node(TemplateBase): version = '0.0.1' template_name = 'node' def __init__(self, name, guid=None, data=None):",
"= self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint, mode, zdb_size, disktype, [namespace]) return zdb_name, namespace_name",
"excepted: [str] :return: a list of zerodb path sorted by free size descending",
"a list of zerodb path sorted by free size descending :rtype: [str] \"\"\"",
"connectivity of management interface\") mgmt_addr = self._node_sal.management_address mgmt_nic = None for nic in",
"not mgmt_nic or 'up' not in mgmt_nic.get('flags', []) or mgmt_nic.get('speed') <= 0: self.logger.error(\"management",
"sure the bridges are installed for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok')",
"disktype, mode, password, public, ns_size, name='', zdb_size=None): if disktype not in ['hdd', 'ssd']:",
"for res in results] # path that are not used by zerodb services",
"guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) # every 30",
"nic.get('addrs'): addr = addr.get('addr') if not addr: continue nw = netaddr.IPNetwork(addr) if str(nw.ip)",
"self.logger.info('Monitoring node %s' % self.name) self.state.check('actions', 'install', 'ok') # check for reboot if",
"namespaces } zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\" list",
"paths used by all the zerodbs installed on the node :param excepted: list",
"@timeout(30, error_message='os_version action timeout') def os_version(self): return self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name, mountpoint, mode,",
"installed on the node :param excepted: list of zerodb service name that should",
"are configured for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring network %s\"",
"size of the zerodb :type zdb_size: int :param disktype: type of the disk",
"data={}, public=True) return except StateCheckError: time.sleep(5) def _port_manager(self): \"\"\" make sure the node_port_manager",
"message = 'Namespace {} already exists on all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30, error_message='info",
"service_name='_node_capacity', data={}, public=True) return except StateCheckError: time.sleep(5) def _port_manager(self): \"\"\" make sure the",
"not healthy\") hostname = self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name data = { 'attributes': {},",
"from zerorobot.template.base import TemplateBase from zerorobot.template.decorator import retry, timeout from zerorobot.template.state import StateCheckError",
"ZDBPathNotFound( \"Could not find any usable storage pool. Not enough space for disk",
"type of the disk the zerodb will be deployed on :type disktype: string",
"try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return except StateCheckError: time.sleep(5) @retry(Exception, tries=2,",
"direct or seq') if disktype == 'hdd': disktypes = ['HDD', 'ARCHIVE'] elif disktype",
"StateCheckError: time.sleep(5) @retry(Exception, tries=2, delay=2) def install(self): self.logger.info('Installing node %s' % self.name) self.data['version']",
"interface %s is down' % mgmt_nic['name'], 'environment': 'Production', 'severity': 'critical', 'event': 'Network', 'tags':",
"{ 'hdd': ['HDD', 'ARCHIVE'], 'ssd': ['SSD', 'NVME'], } # get all usable filesystem",
"return self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name, mountpoint, mode, zdb_size, disktype, namespaces): \"\"\"Create a zerodb",
"not in disks_types_map[disktype]: return False free = (sp.size - sp.total_quota()) / GiB if",
"free space for namespace creation with size {} and type {}'.format( ns_size, ','.join(disktypes))",
"of disk and amount of storage reserved = node_sal.find_persistance() def usable_storagepool(sp): if sp.name",
"'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1'",
"available storagepools = list(filter(usable_storagepool, node_sal.storagepools.list())) if not storagepools: raise ZDBPathNotFound( \"Could not find",
"down' % mgmt_nic['name'], 'environment': 'Production', 'severity': 'critical', 'event': 'Network', 'tags': [\"node:%s\" % hostname,",
"_create_zdb(self, name, mountpoint, mode, zdb_size, disktype, namespaces): \"\"\"Create a zerodb service :param name:",
"mgmt_nic.get('flags', []) or mgmt_nic.get('speed') <= 0: self.logger.error(\"management interface is not healthy\") hostname =",
"disktype == 'hdd': # sort less used pool first fs_paths = [] for",
"disktype not in ['hdd', 'ssd']: raise ValueError('Disktype should be hdd or ssd') if",
"not find any usable storage pool. Not enough space for disk type %s\"",
"disktype) namespace_name = j.data.idgenerator.generateGUID() if not name else name zdb_name = j.data.idgenerator.generateGUID() zdb_size",
"info(self): return self._node_sal.client.info.os() @timeout(30, error_message='stats action timeout') def stats(self): return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes",
"= 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID =",
"self.data.get('network') if network: _validate_network(network) def _monitor(self): self.logger.info('Monitoring node %s' % self.name) self.state.check('actions', 'install',",
"% mgmt_nic['name'], 'environment': 'Production', 'severity': 'critical', 'event': 'Network', 'tags': [\"node:%s\" % hostname, \"node_id:%s\"",
"self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True) return except StateCheckError: time.sleep(5) def _port_manager(self): \"\"\" make sure",
"','.join(disktypes)) raise NoNamespaceAvailability(message) # sort result by free size, first item of the",
"return False if info['type'] not in disktypes: return False if not info['running']: return",
"RuntimeError(\"unsupported disktype:%s\" % disktype) def create_zdb_namespace(self, disktype, mode, password, public, ns_size, name='', zdb_size=None):",
"the zerodbs installed on the node :param excepted: list of zerodb service name",
"config from zerorobot.template.base import TemplateBase from zerorobot.template.decorator import retry, timeout from zerorobot.template.state import",
"self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host name self._node_sal.client.system('hostname %s' % self.data['hostname']).get() self._node_sal.client.bash('echo %s",
"import StateCheckError import netaddr import time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID",
"self._node_sal.client.system('hostname %s' % self.data['hostname']).get() self._node_sal.client.bash('echo %s > /etc/hostname' % self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime()",
"new zerodb # let's look at the already existing one pass def usable_zdb(info):",
"use them free_path = list(set(fs_paths) - set(zdb_paths)) if len(free_path) <= 0: raise ZDBPathNotFound(\"all",
"if not storagepools: raise ZDBPathNotFound( \"Could not find any usable storage pool. Not",
"def create_zdb_namespace(self, disktype, mode, password, public, ns_size, name='', zdb_size=None): if disktype not in",
"'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True) return except StateCheckError: time.sleep(5) def _port_manager(self): \"\"\" make",
"user, direct or seq') if disktype == 'hdd': disktypes = ['HDD', 'ARCHIVE'] elif",
"self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime() self.state.set('actions', 'install', 'ok') def reboot(self): self.logger.info('Rebooting node %s' %",
"service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring bridge %s\" % service.name) service.schedule_action('install')",
"'attributes': {}, 'resource': hostname, 'text': 'network interface %s is down' % mgmt_nic['name'], 'environment':",
"guid=guid, data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) # every 30 seconds self.recurring_action('_network_monitor', 120)",
"name else name zdb_name = j.data.idgenerator.generateGUID() zdb_size = zdb_size if zdb_size else ns_size",
"%s not supported\" % disktype) namespace_name = j.data.idgenerator.generateGUID() if not name else name",
"try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring network %s\" % service.name) service.schedule_action('configure') except StateCheckError: pass",
"is the the one with bigger free size for zdbinfo in sorted(zdbinfos, key=lambda",
"path for this type of disk and amount of storage reserved = node_sal.find_persistance()",
"should be user, direct or seq') if disktype == 'hdd': disktypes = ['HDD',",
"in mgmt_nic.get('flags', []) or mgmt_nic.get('speed') <= 0: self.logger.error(\"management interface is not healthy\") hostname",
"self.state.set('disks', 'mounted', 'ok') except: self.state.delete('disks', 'mounted') def _network_monitor(self): self.state.check('actions', 'install', 'ok') self.logger.info(\"network monitor\")",
"zdb_size=None): if disktype not in ['hdd', 'ssd']: raise ValueError('Disktype should be hdd or",
"name: string :param zdbinfo: list of zerodb services and their info :param zdbinfo:",
"service.schedule_action('configure') except StateCheckError: pass def _register(self): \"\"\" make sure the node_capacity service is",
"data={}) return except StateCheckError: time.sleep(5) @retry(Exception, tries=2, delay=2) def install(self): self.logger.info('Installing node %s'",
"self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces = [ns['name'] for ns in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not in",
"should be hdd or ssd') if mode not in ['seq', 'user', 'direct']: raise",
"reverse=True) if disktype == 'hdd': # sort less used pool first fs_paths =",
"list is the the one with bigger free size for zdbinfo in sorted(zdbinfos,",
":param name: zerodb name :type name: string :param zdbinfo: list of zerodb services",
"mgmt_addr = self._node_sal.management_address mgmt_nic = None for nic in self._node_sal.client.info.nic(): for addr in",
"# every 2 minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self): nodes = self.api.services.find(template_name='node')",
"in disktypes: return False if not info['running']: return False return True zdbinfos =",
"== 'hdd': disktypes = ['HDD', 'ARCHIVE'] elif disktype == 'ssd': disktypes = ['SSD',",
"not in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name, namespace_name message = 'Namespace {} already",
"self.state.set('actions', 'install', 'ok') def reboot(self): self.logger.info('Rebooting node %s' % self.name) self._node_sal.reboot() def zdb_path(self,",
"\"\"\"Create zdb mounpoint and subvolume :param disktype: type of the disk the zerodb",
"t in tasks: result = t.wait(timeout=120, die=True).result result['service_name'] = t.service.name results.append(result) return results",
"VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1' BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID",
"self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make sure the bridges are installed for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID):",
"= self._node_sal.uptime() self.state.set('actions', 'install', 'ok') def reboot(self): self.logger.info('Rebooting node %s' % self.name) self._node_sal.reboot()",
"name :rtype: string \"\"\" zdb_data = { 'path': mountpoint, 'mode': mode, 'sync': False,",
"return zdb_name, namespace_name except ZDBPathNotFound as err: self.logger.warning(\"fail to create a 0-db namespace:",
"list is the the one with bigger free size results = sorted(zdb_infos, key=lambda",
"of the disk the zerodb will be deployed on :type disktype: string :param",
"while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True) return except StateCheckError:",
"'local' GiB = 1024 ** 3 class NoNamespaceAvailability(Exception): pass class Node(TemplateBase): version =",
"timeout from zerorobot.template.state import StateCheckError import netaddr import time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID",
"node_sal.find_persistance() def usable_storagepool(sp): if sp.name == reserved.name: return False if sp.type.value not in",
"'ok') # check for reboot if self._node_sal.uptime() < self.data['uptime']: self.install() self.data['uptime'] = self._node_sal.uptime()",
"on the node :param excepted: list of zerodb service name that should be",
"j.data.idgenerator.generateGUID() if not name else name zdb_name = j.data.idgenerator.generateGUID() zdb_size = zdb_size if",
"zerorobot.template.base import TemplateBase from zerorobot.template.decorator import retry, timeout from zerorobot.template.state import StateCheckError import",
"zerodb will be deployed on :type disktype: string :param size: size of the",
"zdb_size: size of the zerodb :type zdb_size: int :param disktype: type of the",
"netaddr.IPNetwork(cidr) vlan = network.get('vlan') if not isinstance(vlan, int): raise ValueError('Network should have vlan",
"management interface\") mgmt_addr = self._node_sal.management_address mgmt_nic = None for nic in self._node_sal.client.info.nic(): for",
"= [zdb.schedule_action('info') for zdb in zdbs] results = [] for t in tasks:",
"storagepools: raise ZDBPathNotFound( \"Could not find any usable storage pool. Not enough space",
"item of the list is the the one with bigger free size results",
"to create a new zerodb # let's look at the already existing one",
"= node_sal.find_persistance() def usable_storagepool(sp): if sp.name == reserved.name: return False if sp.type.value not",
"!= mode: return False if info['free'] / GiB < zdb_size: return False if",
"space for disk type %s\" % disktype) storagepools.sort(key=lambda sp: sp.size - sp.total_quota(), reverse=True)",
"= [ns['name'] for ns in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True)",
"usable_zdb(info): if info['mode'] != mode: return False if info['free'] / GiB < zdb_size:",
"def stats(self): return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action timeout') def processes(self): return self._node_sal.client.process.list() @timeout(30,",
"the node :param excepted: list of zerodb service name that should be skipped",
"zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\" list the paths used by all the zerodbs",
"be skipped :type excepted: [str] :return: a list of zerodb path sorted by",
"def zdb_path(self, disktype, size, name): \"\"\"Create zdb mounpoint and subvolume :param disktype: type",
"namespace: %s\", str(err)) # at this point we could find a place where",
"cidr = network.get('cidr') if cidr: netaddr.IPNetwork(cidr) vlan = network.get('vlan') if not isinstance(vlan, int):",
"timeout') def stats(self): return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action timeout') def processes(self): return self._node_sal.client.process.list()",
"def _monitor(self): self.logger.info('Monitoring node %s' % self.name) self.state.check('actions', 'install', 'ok') # check for",
"import j from zerorobot import config from zerorobot.template.base import TemplateBase from zerorobot.template.decorator import",
"self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self): nodes = self.api.services.find(template_name='node') if nodes and nodes[0].guid !=",
"def _port_manager(self): \"\"\" make sure the node_port_manager service is installed \"\"\" if config.SERVICE_LOADED:",
"# Set host name self._node_sal.client.system('hostname %s' % self.data['hostname']).get() self._node_sal.client.bash('echo %s > /etc/hostname' %",
"'install', 'ok') self.logger.info(\"configuring network %s\" % service.name) service.schedule_action('configure') except StateCheckError: pass def _register(self):",
"self.logger.info(mgmt_nic) if not mgmt_nic or 'up' not in mgmt_nic.get('flags', []) or mgmt_nic.get('speed') <=",
"return free_path[0] if disktype == 'ssd': fs = storagepools[0].create('zdb_{}'.format(name), size * GiB) return",
"\"\"\" zdb_data = { 'path': mountpoint, 'mode': mode, 'sync': False, 'diskType': disktype, 'size':",
"node_id = self._node_sal.name data = { 'attributes': {}, 'resource': hostname, 'text': 'network interface",
"used by installed zerodb services zdb_infos = self._list_zdbs_info() zdb_infos = filter(lambda info: info['service_name']",
"< self.data['uptime']: self.install() self.data['uptime'] = self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok') except: self.state.delete('disks',",
"except ValueError: pass # no zdb filesystem on this storagepool # all path",
"the networks are configured for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring",
"installed for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring bridge %s\" %",
"list(filter(usable_storagepool, node_sal.storagepools.list())) if not storagepools: raise ZDBPathNotFound( \"Could not find any usable storage",
"installed zerodb services zdb_infos = self._list_zdbs_info() zdb_infos = filter(lambda info: info['service_name'] != name,",
"list(set(fs_paths) - set(zdb_paths)) if len(free_path) <= 0: raise ZDBPathNotFound(\"all storagepools are already used",
"one pass def usable_zdb(info): if info['mode'] != mode: return False if info['free'] /",
"results = [] for t in tasks: result = t.wait(timeout=120, die=True).result result['service_name'] =",
"zdb mounpoint and subvolume :param disktype: type of the disk the zerodb will",
":param name: zdb name :type name: string :param mountpoint: zerodb mountpoint :type mountpoint:",
"self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok') except: self.state.delete('disks', 'mounted') def _network_monitor(self): self.state.check('actions', 'install', 'ok') self.logger.info(\"network",
"return except StateCheckError: time.sleep(5) def _port_manager(self): \"\"\" make sure the node_port_manager service is",
"# path that are not used by zerodb services but have a storagepool,",
"'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1'",
"(sp.size - sp.total_quota()) / GiB if free <= size: return False return True",
"ns_size namespace = { 'name': namespace_name, 'size': ns_size, 'password': password, 'public': public, }",
"list of zerodb service name that should be skipped :type excepted: [str] :return:",
"= [] for t in tasks: result = t.wait(timeout=120, die=True).result result['service_name'] = t.service.name",
":param disktype: type of the disk the zerodb will be deployed on :type",
"their info :param zdbinfo: [(service, dict)], optional :return: zerodb mountpoint, subvolume name :rtype:",
"def usable_storagepool(sp): if sp.name == reserved.name: return False if sp.type.value not in disks_types_map[disktype]:",
"['HDD', 'ARCHIVE'], 'ssd': ['SSD', 'NVME'], } # get all usable filesystem path for",
"return True # all storage pool path of type disktypes and with more",
"self.logger.info(\"verify connectivity of management interface\") mgmt_addr = self._node_sal.management_address mgmt_nic = None for nic",
"'up' not in mgmt_nic.get('flags', []) or mgmt_nic.get('speed') <= 0: self.logger.error(\"management interface is not",
"30) # every 30 seconds self.recurring_action('_network_monitor', 120) # every 2 minutes self.gl_mgr.add(\"_register\", self._register)",
"\"\"\" list the paths used by all the zerodbs installed on the node",
"in zdbs] results = [] for t in tasks: result = t.wait(timeout=120, die=True).result",
"time.sleep(5) def _port_manager(self): \"\"\" make sure the node_port_manager service is installed \"\"\" if",
"nw = netaddr.IPNetwork(addr) if str(nw.ip) == mgmt_addr: mgmt_nic = nic break self.logger.info(mgmt_nic) if",
"service_name='_port_manager', data={}) return except StateCheckError: time.sleep(5) @retry(Exception, tries=2, delay=2) def install(self): self.logger.info('Installing node",
"% node_id, \"interface:%s\" % mgmt_nic['name']], 'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor' not",
"'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={}) return except StateCheckError: time.sleep(5) @retry(Exception, tries=2, delay=2) def",
"name=zdbinfo['service_name']) namespaces = [ns['name'] for ns in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not in namespaces:",
"self._node_sal.client.info.os() @timeout(30, error_message='stats action timeout') def stats(self): return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action timeout')",
"disks_types_map[disktype]: return False free = (sp.size - sp.total_quota()) / GiB if free <=",
"disktype, size, name): \"\"\"Create zdb mounpoint and subvolume :param disktype: type of the",
"_network_monitor(self): self.state.check('actions', 'install', 'ok') self.logger.info(\"network monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify connectivity of management interface\")",
"host name self._node_sal.client.system('hostname %s' % self.data['hostname']).get() self._node_sal.client.bash('echo %s > /etc/hostname' % self.data['hostname']).get() self.data['uptime']",
"= 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local' GiB = 1024 ** 3 class NoNamespaceAvailability(Exception): pass",
"the one with bigger free size results = sorted(zdb_infos, key=lambda r: r['free'], reverse=True)",
"- sp.total_quota(), reverse=True) if disktype == 'hdd': # sort less used pool first",
"storage reserved = node_sal.find_persistance() def usable_storagepool(sp): if sp.name == reserved.name: return False if",
"every 30 seconds self.recurring_action('_network_monitor', 120) # every 2 minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager)",
"in zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name, namespace_name message",
"nic_mgmt_monitor(): self.logger.info(\"verify connectivity of management interface\") mgmt_addr = self._node_sal.management_address mgmt_nic = None for",
"with bigger free size results = sorted(zdb_infos, key=lambda r: r['free'], reverse=True) zdb_paths =",
"BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local' GiB = 1024 ** 3 class NoNamespaceAvailability(Exception):",
"type disktypes and with more then size storage available storagepools = list(filter(usable_storagepool, node_sal.storagepools.list()))",
"all usable filesystem path for this type of disk and amount of storage",
"not storagepools: raise ZDBPathNotFound( \"Could not find any usable storage pool. Not enough",
"the node_port_manager service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions',",
"Not enough space for disk type %s\" % disktype) storagepools.sort(key=lambda sp: sp.size -",
"not in ['seq', 'user', 'direct']: raise ValueError('ZDB mode should be user, direct or",
"installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity',",
"string :param zdb_size: size of the zerodb :type zdb_size: int :param disktype: type",
"are not used by zerodb services but have a storagepool, so we can",
"False if sp.type.value not in disks_types_map[disktype]: return False free = (sp.size - sp.total_quota())",
"'ssd': disktypes = ['SSD', 'NVME'] else: raise ValueError(\"disk type %s not supported\" %",
"zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint, mode, zdb_size, disktype, [namespace]) return zdb_name, namespace_name except ZDBPathNotFound",
"already used by a zerodb\") return free_path[0] if disktype == 'ssd': fs =",
"self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring bridge %s\" % service.name) service.schedule_action('install') except StateCheckError:",
"mode, zdb_size, disktype, [namespace]) return zdb_name, namespace_name except ZDBPathNotFound as err: self.logger.warning(\"fail to",
"RuntimeError('Another node service exists. Only one node service per node is allowed') self.state.delete('disks',",
"except ZDBPathNotFound as err: self.logger.warning(\"fail to create a 0-db namespace: %s\", str(err)) #",
"in ['hdd', 'ssd']: raise ValueError('Disktype should be hdd or ssd') if mode not",
"zdb_path(self, disktype, size, name): \"\"\"Create zdb mounpoint and subvolume :param disktype: type of",
"of the list is the the one with bigger free size results =",
"mgmt_nic['name'], 'environment': 'Production', 'severity': 'critical', 'event': 'Network', 'tags': [\"node:%s\" % hostname, \"node_id:%s\" %",
"Only one node service per node is allowed') self.state.delete('disks', 'mounted') network = self.data.get('network')",
"self._list_zdbs_info() zdb_infos = filter(lambda info: info['service_name'] != name, zdb_infos) # sort result by",
"disk the zerodb will be deployed on :type disktype: string :param size: size",
"or mgmt_nic.get('speed') <= 0: self.logger.error(\"management interface is not healthy\") hostname = self._node_sal.client.info.os()['hostname'] node_id",
"or 'up' not in mgmt_nic.get('flags', []) or mgmt_nic.get('speed') <= 0: self.logger.error(\"management interface is",
"if self._node_sal.uptime() < self.data['uptime']: self.install() self.data['uptime'] = self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok')",
"else name zdb_name = j.data.idgenerator.generateGUID() zdb_size = zdb_size if zdb_size else ns_size namespace",
"name zdb_name = j.data.idgenerator.generateGUID() zdb_size = zdb_size if zdb_size else ns_size namespace =",
"_list_zdbs_info(self): \"\"\" list the paths used by all the zerodbs installed on the",
"nic in self._node_sal.client.info.nic(): for addr in nic.get('addrs'): addr = addr.get('addr') if not addr:",
"self._node_sal.client.process.list() @timeout(30, error_message='os_version action timeout') def os_version(self): return self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name, mountpoint,",
"r: r['free'], reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces = [ns['name'] for ns in",
"\"\"\" node_sal = self._node_sal disks_types_map = { 'hdd': ['HDD', 'ARCHIVE'], 'ssd': ['SSD', 'NVME'],",
"= 'node' def __init__(self, name, guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT)",
"is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID,",
"> /etc/hostname' % self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime() self.state.set('actions', 'install', 'ok') def reboot(self): self.logger.info('Rebooting",
"except StateCheckError: pass def _register(self): \"\"\" make sure the node_capacity service is installed",
"seq') if disktype == 'hdd': disktypes = ['HDD', 'ARCHIVE'] elif disktype == 'ssd':",
"namespace_name, 'size': ns_size, 'password': password, 'public': public, } try: mountpoint = self.zdb_path(disktype, zdb_size,",
"'resource': hostname, 'text': 'network interface %s is down' % mgmt_nic['name'], 'environment': 'Production', 'severity':",
"'password': password, 'public': public, } try: mountpoint = self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint,",
"zdbinfo in sorted(zdbinfos, key=lambda r: r['free'], reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID, name=zdbinfo['service_name']) namespaces =",
"sp.size - sp.total_quota(), reverse=True) if disktype == 'hdd': # sort less used pool",
"return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action timeout') def processes(self): return self._node_sal.client.process.list() @timeout(30, error_message='os_version action",
"zdb_name = j.data.idgenerator.generateGUID() zdb_size = zdb_size if zdb_size else ns_size namespace = {",
"# sort less used pool first fs_paths = [] for sp in storagepools:",
"reverse=True) zdb_paths = [res['path'] for res in results] # path that are not",
"hostname, 'text': 'network interface %s is down' % mgmt_nic['name'], 'environment': 'Production', 'severity': 'critical',",
"if disktype == 'hdd': disktypes = ['HDD', 'ARCHIVE'] elif disktype == 'ssd': disktypes",
"addr = addr.get('addr') if not addr: continue nw = netaddr.IPNetwork(addr) if str(nw.ip) ==",
"return False if sp.type.value not in disks_types_map[disktype]: return False free = (sp.size -",
"'Not enough free space for namespace creation with size {} and type {}'.format(",
"free_path = list(set(fs_paths) - set(zdb_paths)) if len(free_path) <= 0: raise ZDBPathNotFound(\"all storagepools are",
"continue nw = netaddr.IPNetwork(addr) if str(nw.ip) == mgmt_addr: mgmt_nic = nic break self.logger.info(mgmt_nic)",
"enough space for disk type %s\" % disktype) storagepools.sort(key=lambda sp: sp.size - sp.total_quota(),",
"return fs.path raise RuntimeError(\"unsupported disktype:%s\" % disktype) def create_zdb_namespace(self, disktype, mode, password, public,",
"try: mountpoint = self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint, mode, zdb_size, disktype, [namespace]) return",
"place where to create a new zerodb # let's look at the already",
"interface is not healthy\") hostname = self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name data = {",
"with size {} and type {}'.format( ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message) # sort result",
"True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True) return except StateCheckError: time.sleep(5)",
"networks are configured for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring network",
"namespaces: [dict] :return: zerodb service name :rtype: string \"\"\" zdb_data = { 'path':",
":type mountpoint: string :param mode: zerodb mode :type mode: string :param zdb_size: size",
"if info['free'] / GiB < zdb_size: return False if info['type'] not in disktypes:",
"string :param size: size of the zerodb :type size: int :param name: zerodb",
"results] # path that are not used by zerodb services but have a",
"should have vlan configured') def send_alert(alertas, alert): for alerta in alertas: alerta.schedule_action('send_alert', args={'data':",
"size, name): \"\"\"Create zdb mounpoint and subvolume :param disktype: type of the disk",
"zerodb path sorted by free size descending :rtype: [str] \"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID)",
"path sorted by free size descending :rtype: [str] \"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks",
"= { 'path': mountpoint, 'mode': mode, 'sync': False, 'diskType': disktype, 'size': zdb_size, 'namespaces':",
"mountpoint, 'mode': mode, 'sync': False, 'diskType': disktype, 'size': zdb_size, 'namespaces': namespaces } zdb",
"find any usable storage pool. Not enough space for disk type %s\" %",
"node_port_manager service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install',",
"= [res['path'] for res in results] # path that are not used by",
"make sure the node_capacity service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True:",
"= j.data.idgenerator.generateGUID() zdb_size = zdb_size if zdb_size else ns_size namespace = { 'name':",
"'public': public, } try: mountpoint = self.zdb_path(disktype, zdb_size, zdb_name) self._create_zdb(zdb_name, mountpoint, mode, zdb_size,",
"error_message='info action timeout') def info(self): return self._node_sal.client.info.os() @timeout(30, error_message='stats action timeout') def stats(self):",
"ValueError: pass # no zdb filesystem on this storagepool # all path used",
"def os_version(self): return self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name, mountpoint, mode, zdb_size, disktype, namespaces): \"\"\"Create",
"have a storagepool, so we can use them free_path = list(set(fs_paths) - set(zdb_paths))",
"pool path of type disktypes and with more then size storage available storagepools",
"is the the one with bigger free size results = sorted(zdb_infos, key=lambda r:",
"if zdb_size else ns_size namespace = { 'name': namespace_name, 'size': ns_size, 'password': password,",
"2 minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self): nodes = self.api.services.find(template_name='node') if nodes",
"'0.0.1' template_name = 'node' def __init__(self, name, guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self._node_sal",
"addr: continue nw = netaddr.IPNetwork(addr) if str(nw.ip) == mgmt_addr: mgmt_nic = nic break",
"install(self): self.logger.info('Installing node %s' % self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host name",
"'ok') def reboot(self): self.logger.info('Rebooting node %s' % self.name) self._node_sal.reboot() def zdb_path(self, disktype, size,",
"type %s\" % disktype) storagepools.sort(key=lambda sp: sp.size - sp.total_quota(), reverse=True) if disktype ==",
"space for namespace creation with size {} and type {}'.format( ns_size, ','.join(disktypes)) raise",
"<reponame>threefoldtech/0-templates from jumpscale import j from zerorobot import config from zerorobot.template.base import TemplateBase",
"if nodes and nodes[0].guid != self.guid: raise RuntimeError('Another node service exists. Only one",
"config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True) return",
"seconds self.recurring_action('_network_monitor', 120) # every 2 minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self):",
"zdbinfo: list of zerodb services and their info :param zdbinfo: [(service, dict)], optional",
"int :param disktype: type of the disk to deploy the zerodb on :type",
"'ok') self.logger.info(\"configuring network %s\" % service.name) service.schedule_action('configure') except StateCheckError: pass def _register(self): \"\"\"",
"30 seconds self.recurring_action('_network_monitor', 120) # every 2 minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def",
"network = self.data.get('network') if network: _validate_network(network) def _monitor(self): self.logger.info('Monitoring node %s' % self.name)",
"'ok') self.logger.info(\"network monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify connectivity of management interface\") mgmt_addr = self._node_sal.management_address",
"'size': ns_size, 'password': password, 'public': public, } try: mountpoint = self.zdb_path(disktype, zdb_size, zdb_name)",
"= 'Namespace {} already exists on all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30, error_message='info action",
"'mounted', 'ok') except: self.state.delete('disks', 'mounted') def _network_monitor(self): self.state.check('actions', 'install', 'ok') self.logger.info(\"network monitor\") def",
"= '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host name self._node_sal.client.system('hostname %s' % self.data['hostname']).get() self._node_sal.client.bash('echo %s >",
"False if info['free'] / GiB < zdb_size: return False if info['type'] not in",
"'mounted') def _network_monitor(self): self.state.check('actions', 'install', 'ok') self.logger.info(\"network monitor\") def nic_mgmt_monitor(): self.logger.info(\"verify connectivity of",
"sort less used pool first fs_paths = [] for sp in storagepools: try:",
"mountpoint, subvolume name :rtype: (string, string) \"\"\" node_sal = self._node_sal disks_types_map = {",
"make sure the node_port_manager service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True:",
"free_path[0] if disktype == 'ssd': fs = storagepools[0].create('zdb_{}'.format(name), size * GiB) return fs.path",
"zdbs] results = [] for t in tasks: result = t.wait(timeout=120, die=True).result result['service_name']",
"if cidr: netaddr.IPNetwork(cidr) vlan = network.get('vlan') if not isinstance(vlan, int): raise ValueError('Network should",
"self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name, mountpoint, mode, zdb_size, disktype, namespaces): \"\"\"Create a zerodb service",
"info['running']: return False return True zdbinfos = list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos) <= 0:",
"= netaddr.IPNetwork(addr) if str(nw.ip) == mgmt_addr: mgmt_nic = nic break self.logger.info(mgmt_nic) if not",
"name, zdb_infos) # sort result by free size, first item of the list",
"class NoNamespaceAvailability(Exception): pass class Node(TemplateBase): version = '0.0.1' template_name = 'node' def __init__(self,",
"NoNamespaceAvailability(Exception): pass class Node(TemplateBase): version = '0.0.1' template_name = 'node' def __init__(self, name,",
"info['type'] not in disktypes: return False if not info['running']: return False return True",
"network.get('cidr') if cidr: netaddr.IPNetwork(cidr) vlan = network.get('vlan') if not isinstance(vlan, int): raise ValueError('Network",
"self._node_sal.client.info.nic(): for addr in nic.get('addrs'): addr = addr.get('addr') if not addr: continue nw",
"\"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=PORT_MANAGER_TEMPLATE_UID, service_name='_port_manager', data={})",
":param mountpoint: zerodb mountpoint :type mountpoint: string :param mode: zerodb mode :type mode:",
"is down' % mgmt_nic['name'], 'environment': 'Production', 'severity': 'critical', 'event': 'Network', 'tags': [\"node:%s\" %",
"False, 'diskType': disktype, 'size': zdb_size, 'namespaces': namespaces } zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data)",
"'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local'",
"None for nic in self._node_sal.client.info.nic(): for addr in nic.get('addrs'): addr = addr.get('addr') if",
"processes(self): return self._node_sal.client.process.list() @timeout(30, error_message='os_version action timeout') def os_version(self): return self._node_sal.client.ping()[13:].strip() def _create_zdb(self,",
"addr in nic.get('addrs'): addr = addr.get('addr') if not addr: continue nw = netaddr.IPNetwork(addr)",
"vlan = network.get('vlan') if not isinstance(vlan, int): raise ValueError('Network should have vlan configured')",
"} zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\" list the",
"self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True) zdb.schedule_action('start').wait(die=True) def _list_zdbs_info(self): \"\"\" list the paths used by",
"could find a place where to create a new zerodb # let's look",
"== mgmt_addr: mgmt_nic = nic break self.logger.info(mgmt_nic) if not mgmt_nic or 'up' not",
"free size for zdbinfo in sorted(zdbinfos, key=lambda r: r['free'], reverse=True): zdb = self.api.services.get(template_uid=ZDB_TEMPLATE_UID,",
"StateCheckError: time.sleep(5) def _port_manager(self): \"\"\" make sure the node_port_manager service is installed \"\"\"",
"disktype: type of the disk to deploy the zerodb on :type disktype: string",
"let's look at the already existing one pass def usable_zdb(info): if info['mode'] !=",
"mountpoint: zerodb mountpoint :type mountpoint: string :param mode: zerodb mode :type mode: string",
":return: a list of zerodb path sorted by free size descending :rtype: [str]",
"pass # make sure the networks are configured for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID): try:",
"one with bigger free size for zdbinfo in sorted(zdbinfos, key=lambda r: r['free'], reverse=True):",
"self.data['hostname']).get() self._node_sal.client.bash('echo %s > /etc/hostname' % self.data['hostname']).get() self.data['uptime'] = self._node_sal.uptime() self.state.set('actions', 'install', 'ok')",
"sorted by free size descending :rtype: [str] \"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks =",
"die=True).result result['service_name'] = t.service.name results.append(result) return results def _validate_network(network): cidr = network.get('cidr') if",
"reboot(self): self.logger.info('Rebooting node %s' % self.name) self._node_sal.reboot() def zdb_path(self, disktype, size, name): \"\"\"Create",
"%s\" % service.name) service.schedule_action('configure') except StateCheckError: pass def _register(self): \"\"\" make sure the",
"def validate(self): nodes = self.api.services.find(template_name='node') if nodes and nodes[0].guid != self.guid: raise RuntimeError('Another",
"every 2 minutes self.gl_mgr.add(\"_register\", self._register) self.gl_mgr.add(\"_port_manager\", self._port_manager) def validate(self): nodes = self.api.services.find(template_name='node') if",
"storagepools: try: fs = sp.get('zdb') fs_paths.append(fs.path) except ValueError: pass # no zdb filesystem",
"return results def _validate_network(network): cidr = network.get('cidr') if cidr: netaddr.IPNetwork(cidr) vlan = network.get('vlan')",
"the list is the the one with bigger free size results = sorted(zdb_infos,",
"zerodb :type size: int :param name: zerodb name :type name: string :param zdbinfo:",
"a zerodb\") return free_path[0] if disktype == 'ssd': fs = storagepools[0].create('zdb_{}'.format(name), size *",
"zerodb mode :type mode: string :param zdb_size: size of the zerodb :type zdb_size:",
"get all usable filesystem path for this type of disk and amount of",
"nodes and nodes[0].guid != self.guid: raise RuntimeError('Another node service exists. Only one node",
"for reboot if self._node_sal.uptime() < self.data['uptime']: self.install() self.data['uptime'] = self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks',",
"= (sp.size - sp.total_quota()) / GiB if free <= size: return False return",
"if info['mode'] != mode: return False if info['free'] / GiB < zdb_size: return",
"bridge %s\" % service.name) service.schedule_action('install') except StateCheckError: pass # make sure the networks",
"{} already exists on all zerodbs'.format(namespace_name) raise NoNamespaceAvailability(message) @timeout(30, error_message='info action timeout') def",
"on this storagepool # all path used by installed zerodb services zdb_infos =",
"'{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host name self._node_sal.client.system('hostname %s' % self.data['hostname']).get() self._node_sal.client.bash('echo %s > /etc/hostname'",
"namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name, namespace_name message = 'Namespace {} already exists on",
"@timeout(30, error_message='stats action timeout') def stats(self): return self._node_sal.client.aggregator.query() @timeout(30, error_message='processes action timeout') def",
"pass def usable_zdb(info): if info['mode'] != mode: return False if info['free'] / GiB",
"used by zerodb services but have a storagepool, so we can use them",
"this type of disk and amount of storage reserved = node_sal.find_persistance() def usable_storagepool(sp):",
"are already used by a zerodb\") return free_path[0] if disktype == 'ssd': fs",
"zerorobot.template.state import StateCheckError import netaddr import time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1' VM_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/vm/0.0.1'",
"str(err)) # at this point we could find a place where to create",
"(string, string) \"\"\" node_sal = self._node_sal disks_types_map = { 'hdd': ['HDD', 'ARCHIVE'], 'ssd':",
"list of zerodb path sorted by free size descending :rtype: [str] \"\"\" zdbs",
"%s\", str(err)) # at this point we could find a place where to",
"{}'.format( ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message) # sort result by free size, first item",
"healthy\") hostname = self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name data = { 'attributes': {}, 'resource':",
"subvolume name :rtype: (string, string) \"\"\" node_sal = self._node_sal disks_types_map = { 'hdd':",
"GiB if free <= size: return False return True # all storage pool",
"r['free'], reverse=True) zdb_paths = [res['path'] for res in results] # path that are",
"the bridges are installed for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install', 'ok') self.logger.info(\"configuring",
"zerodbs installed on the node :param excepted: list of zerodb service name that",
"= j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) # every 30 seconds self.recurring_action('_network_monitor', 120) # every 2",
"the zerodb :type size: int :param name: zerodb name :type name: string :param",
"if not info['running']: return False return True zdbinfos = list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos)",
"[namespace]) return zdb_name, namespace_name except ZDBPathNotFound as err: self.logger.warning(\"fail to create a 0-db",
"node_sal = self._node_sal disks_types_map = { 'hdd': ['HDD', 'ARCHIVE'], 'ssd': ['SSD', 'NVME'], }",
"check for reboot if self._node_sal.uptime() < self.data['uptime']: self.install() self.data['uptime'] = self._node_sal.uptime() try: self._node_sal.zerodbs.prepare()",
"[self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor' not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make",
"'user', 'direct']: raise ValueError('ZDB mode should be user, direct or seq') if disktype",
"_monitor(self): self.logger.info('Monitoring node %s' % self.name) self.state.check('actions', 'install', 'ok') # check for reboot",
"self._node_sal.reboot() def zdb_path(self, disktype, size, name): \"\"\"Create zdb mounpoint and subvolume :param disktype:",
"deployed on :type disktype: string :param size: size of the zerodb :type size:",
"data) if 'nic_mgmt_monitor' not in self.gl_mgr.gls: self.gl_mgr.add('nic_mgmt_monitor', nic_mgmt_monitor) # make sure the bridges",
"as err: self.logger.warning(\"fail to create a 0-db namespace: %s\", str(err)) # at this",
"def install(self): self.logger.info('Installing node %s' % self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set host",
"NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local' GiB",
"self.logger.info('Rebooting node %s' % self.name) self._node_sal.reboot() def zdb_path(self, disktype, size, name): \"\"\"Create zdb",
"the the one with bigger free size for zdbinfo in sorted(zdbinfos, key=lambda r:",
"sp.total_quota(), reverse=True) if disktype == 'hdd': # sort less used pool first fs_paths",
"if not name else name zdb_name = j.data.idgenerator.generateGUID() zdb_size = zdb_size if zdb_size",
"'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT = 'local' GiB = 1024 ** 3 class",
"zdb_data = { 'path': mountpoint, 'mode': mode, 'sync': False, 'diskType': disktype, 'size': zdb_size,",
"[]) or mgmt_nic.get('speed') <= 0: self.logger.error(\"management interface is not healthy\") hostname = self._node_sal.client.info.os()['hostname']",
"and subvolume :param disktype: type of the disk the zerodb will be deployed",
"!= name, zdb_infos) # sort result by free size, first item of the",
"'hdd': disktypes = ['HDD', 'ARCHIVE'] elif disktype == 'ssd': disktypes = ['SSD', 'NVME']",
"BOOTSTRAP_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zeroos_bootstrap/0.0.1' ZDB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID",
"the already existing one pass def usable_zdb(info): if info['mode'] != mode: return False",
"zdb.schedule_action('namespace_list').wait(die=True).result] if namespace_name not in namespaces: zdb.schedule_action('namespace_create', namespace).wait(die=True) return zdb.name, namespace_name message =",
"zdb in zdbs] results = [] for t in tasks: result = t.wait(timeout=120,",
"in self._node_sal.client.info.nic(): for addr in nic.get('addrs'): addr = addr.get('addr') if not addr: continue",
"and with more then size storage available storagepools = list(filter(usable_storagepool, node_sal.storagepools.list())) if not",
"a storagepool, so we can use them free_path = list(set(fs_paths) - set(zdb_paths)) if",
"return False return True zdbinfos = list(filter(usable_zdb, self._list_zdbs_info())) if len(zdbinfos) <= 0: message",
"zerodb :type namespaces: [dict] :return: zerodb service name :rtype: string \"\"\" zdb_data =",
"config.SERVICE_LOADED.wait() while True: try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True) return except",
"in tasks: result = t.wait(timeout=120, die=True).result result['service_name'] = t.service.name results.append(result) return results def",
"return zdb.name, namespace_name message = 'Namespace {} already exists on all zerodbs'.format(namespace_name) raise",
"['SSD', 'NVME'] else: raise ValueError(\"disk type %s not supported\" % disktype) namespace_name =",
"optional :return: zerodb mountpoint, subvolume name :rtype: (string, string) \"\"\" node_sal = self._node_sal",
"'diskType': disktype, 'size': zdb_size, 'namespaces': namespaces } zdb = self.api.services.find_or_create(ZDB_TEMPLATE_UID, name, zdb_data) zdb.schedule_action('install').wait(die=True)",
"= self.data.get('network') if network: _validate_network(network) def _monitor(self): self.logger.info('Monitoring node %s' % self.name) self.state.check('actions',",
"= self._node_sal.name data = { 'attributes': {}, 'resource': hostname, 'text': 'network interface %s",
"for addr in nic.get('addrs'): addr = addr.get('addr') if not addr: continue nw =",
"\"interface:%s\" % mgmt_nic['name']], 'service': [self.template_uid.name] } send_alert(self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1'), data) if 'nic_mgmt_monitor' not in self.gl_mgr.gls:",
"zerorobot import config from zerorobot.template.base import TemplateBase from zerorobot.template.decorator import retry, timeout from",
"subvolume :param disktype: type of the disk the zerodb will be deployed on",
"raise NoNamespaceAvailability(message) # sort result by free size, first item of the list",
"int): raise ValueError('Network should have vlan configured') def send_alert(alertas, alert): for alerta in",
"size storage available storagepools = list(filter(usable_storagepool, node_sal.storagepools.list())) if not storagepools: raise ZDBPathNotFound( \"Could",
"j from zerorobot import config from zerorobot.template.base import TemplateBase from zerorobot.template.decorator import retry,",
"= nic break self.logger.info(mgmt_nic) if not mgmt_nic or 'up' not in mgmt_nic.get('flags', [])",
"fs_paths.append(fs.path) except ValueError: pass # no zdb filesystem on this storagepool # all",
"% self.name) self.state.check('actions', 'install', 'ok') # check for reboot if self._node_sal.uptime() < self.data['uptime']:",
"res in results] # path that are not used by zerodb services but",
"self._create_zdb(zdb_name, mountpoint, mode, zdb_size, disktype, [namespace]) return zdb_name, namespace_name except ZDBPathNotFound as err:",
"CAPACITY_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_capacity/0.0.1' NETWORK_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/network/0.0.1' PORT_MANAGER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/node_port_manager/0.0.1' BRIDGE_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/bridge/0.0.1' NODE_CLIENT",
"tasks: result = t.wait(timeout=120, die=True).result result['service_name'] = t.service.name results.append(result) return results def _validate_network(network):",
"a place where to create a new zerodb # let's look at the",
"os_version(self): return self._node_sal.client.ping()[13:].strip() def _create_zdb(self, name, mountpoint, mode, zdb_size, disktype, namespaces): \"\"\"Create a",
"for disk type %s\" % disktype) storagepools.sort(key=lambda sp: sp.size - sp.total_quota(), reverse=True) if",
"bigger free size for zdbinfo in sorted(zdbinfos, key=lambda r: r['free'], reverse=True): zdb =",
"sp: sp.size - sp.total_quota(), reverse=True) if disktype == 'hdd': # sort less used",
"mode: return False if info['free'] / GiB < zdb_size: return False if info['type']",
"name: zerodb name :type name: string :param zdbinfo: list of zerodb services and",
"the paths used by all the zerodbs installed on the node :param excepted:",
"try: self.state.check('actions', 'install', 'ok') self.api.services.find_or_create(template_uid=CAPACITY_TEMPLATE_UID, service_name='_node_capacity', data={}, public=True) return except StateCheckError: time.sleep(5) def",
"StateCheckError: pass # make sure the networks are configured for service in self.api.services.find(template_uid=NETWORK_TEMPLATE_UID):",
"1024 ** 3 class NoNamespaceAvailability(Exception): pass class Node(TemplateBase): version = '0.0.1' template_name =",
"retry, timeout from zerorobot.template.state import StateCheckError import netaddr import time CONTAINER_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/container/0.0.1'",
"make sure the bridges are installed for service in self.api.services.find(template_uid=BRIDGE_TEMPLATE_UID): try: service.state.check('actions', 'install',",
":param disktype: type of the disk to deploy the zerodb on :type disktype:",
"to create a 0-db namespace: %s\", str(err)) # at this point we could",
"to create on the zerodb :type namespaces: [dict] :return: zerodb service name :rtype:",
"= t.service.name results.append(result) return results def _validate_network(network): cidr = network.get('cidr') if cidr: netaddr.IPNetwork(cidr)",
"= self._node_sal.uptime() try: self._node_sal.zerodbs.prepare() self.state.set('disks', 'mounted', 'ok') except: self.state.delete('disks', 'mounted') def _network_monitor(self): self.state.check('actions',",
"# check for reboot if self._node_sal.uptime() < self.data['uptime']: self.install() self.data['uptime'] = self._node_sal.uptime() try:",
"the node_capacity service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try: self.state.check('actions',",
"disktypes = ['HDD', 'ARCHIVE'] elif disktype == 'ssd': disktypes = ['SSD', 'NVME'] else:",
"namespaces: list of namespaces to create on the zerodb :type namespaces: [dict] :return:",
"mode, zdb_size, disktype, namespaces): \"\"\"Create a zerodb service :param name: zdb name :type",
"not isinstance(vlan, int): raise ValueError('Network should have vlan configured') def send_alert(alertas, alert): for",
"__init__(self, name, guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) #",
"of storage reserved = node_sal.find_persistance() def usable_storagepool(sp): if sp.name == reserved.name: return False",
"creation with size {} and type {}'.format( ns_size, ','.join(disktypes)) raise NoNamespaceAvailability(message) # sort",
"zdb_name) self._create_zdb(zdb_name, mountpoint, mode, zdb_size, disktype, [namespace]) return zdb_name, namespace_name except ZDBPathNotFound as",
"* GiB) return fs.path raise RuntimeError(\"unsupported disktype:%s\" % disktype) def create_zdb_namespace(self, disktype, mode,",
"will be deployed on :type disktype: string :param size: size of the zerodb",
"for t in tasks: result = t.wait(timeout=120, die=True).result result['service_name'] = t.service.name results.append(result) return",
"all path used by installed zerodb services zdb_infos = self._list_zdbs_info() zdb_infos = filter(lambda",
"ValueError('ZDB mode should be user, direct or seq') if disktype == 'hdd': disktypes",
"= self._node_sal.client.info.os()['hostname'] node_id = self._node_sal.name data = { 'attributes': {}, 'resource': hostname, 'text':",
"'path': mountpoint, 'mode': mode, 'sync': False, 'diskType': disktype, 'size': zdb_size, 'namespaces': namespaces }",
"= zdb_size if zdb_size else ns_size namespace = { 'name': namespace_name, 'size': ns_size,",
"sure the node_port_manager service is installed \"\"\" if config.SERVICE_LOADED: config.SERVICE_LOADED.wait() while True: try:",
"self._list_zdbs_info())) if len(zdbinfos) <= 0: message = 'Not enough free space for namespace",
"NODE_CLIENT = 'local' GiB = 1024 ** 3 class NoNamespaceAvailability(Exception): pass class Node(TemplateBase):",
"more then size storage available storagepools = list(filter(usable_storagepool, node_sal.storagepools.list())) if not storagepools: raise",
"[] for sp in storagepools: try: fs = sp.get('zdb') fs_paths.append(fs.path) except ValueError: pass",
"= filter(lambda info: info['service_name'] != name, zdb_infos) # sort result by free size,",
"bigger free size results = sorted(zdb_infos, key=lambda r: r['free'], reverse=True) zdb_paths = [res['path']",
"the disk to deploy the zerodb on :type disktype: string :param namespaces: list",
"data=data) self._node_sal = j.clients.zos.get(NODE_CLIENT) self.recurring_action('_monitor', 30) # every 30 seconds self.recurring_action('_network_monitor', 120) #",
"descending :rtype: [str] \"\"\" zdbs = self.api.services.find(template_uid=ZDB_TEMPLATE_UID) tasks = [zdb.schedule_action('info') for zdb in",
"mode should be user, direct or seq') if disktype == 'hdd': disktypes =",
"zdb name :type name: string :param mountpoint: zerodb mountpoint :type mountpoint: string :param",
"else: raise ValueError(\"disk type %s not supported\" % disktype) namespace_name = j.data.idgenerator.generateGUID() if",
"the list is the the one with bigger free size for zdbinfo in",
"delay=2) def install(self): self.logger.info('Installing node %s' % self.name) self.data['version'] = '{branch}:{revision}'.format(**self._node_sal.client.info.version()) # Set",
"of zerodb path sorted by free size descending :rtype: [str] \"\"\" zdbs =",
"int :param name: zerodb name :type name: string :param zdbinfo: list of zerodb",
"zdb_size: return False if info['type'] not in disktypes: return False if not info['running']:"
] |
[
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authorization', '0004_auto_20200207_2147'), ] operations = [ migrations.AlterField(",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authorization',",
"20:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"by Django 2.2.4 on 2020-02-07 20:04 from django.db import migrations, models import django.db.models.deletion",
"('authorization', '0004_auto_20200207_2147'), ] operations = [ migrations.AlterField( model_name='people', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='authorization.Course'), ), ]",
"<reponame>KariSpace/CRM_Sedicomm # Generated by Django 2.2.4 on 2020-02-07 20:04 from django.db import migrations,",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authorization', '0004_auto_20200207_2147'), ] operations =",
"on 2020-02-07 20:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authorization', '0004_auto_20200207_2147'), ]",
"2020-02-07 20:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authorization', '0004_auto_20200207_2147'), ] operations",
"Django 2.2.4 on 2020-02-07 20:04 from django.db import migrations, models import django.db.models.deletion class",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authorization', '0004_auto_20200207_2147'),",
"class Migration(migrations.Migration): dependencies = [ ('authorization', '0004_auto_20200207_2147'), ] operations = [ migrations.AlterField( model_name='people',",
"# Generated by Django 2.2.4 on 2020-02-07 20:04 from django.db import migrations, models",
"Generated by Django 2.2.4 on 2020-02-07 20:04 from django.db import migrations, models import",
"[ ('authorization', '0004_auto_20200207_2147'), ] operations = [ migrations.AlterField( model_name='people', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='authorization.Course'), ),",
"Migration(migrations.Migration): dependencies = [ ('authorization', '0004_auto_20200207_2147'), ] operations = [ migrations.AlterField( model_name='people', name='course',",
"2.2.4 on 2020-02-07 20:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authorization', '0004_auto_20200207_2147'), ] operations = [",
"= [ ('authorization', '0004_auto_20200207_2147'), ] operations = [ migrations.AlterField( model_name='people', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='authorization.Course'),",
"dependencies = [ ('authorization', '0004_auto_20200207_2147'), ] operations = [ migrations.AlterField( model_name='people', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING,"
] |