code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class TaxonVar(TaxonCommonVar): <NEW_LINE> <INDENT> type = 'var' | Классическая переменная.
Обычно объявляется в блоке.
Может быть объявлена в модуле, но только private.
То есть, экспортировать переменные из модуля нельзя. | 625990761f5feb6acb164562 |
class PageAlias(models.Model): <NEW_LINE> <INDENT> page = models.ForeignKey(Page, null=True, blank=True, verbose_name=_('page')) <NEW_LINE> url = models.CharField(max_length=255, unique=True) <NEW_LINE> objects = PageAliasManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = _('Aliases') <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.url = normalize_url(self.url) <NEW_LINE> super(PageAlias, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "%s => %s" % (self.url, self.page.get_url()) | URL alias for a :class:`Page <pages.models.Page>` | 625990768a43f66fc4bf3b02 |
class ADataCrawling(metaclass=ABCMeta): <NEW_LINE> <INDENT> @property <NEW_LINE> def review_language(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @review_language.setter <NEW_LINE> @abstractmethod <NEW_LINE> def review_language(self, a_review_language): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def entity_type(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @entity_type.setter <NEW_LINE> @abstractmethod <NEW_LINE> def entity_type(self, a_entity_type): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def entity_location(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @entity_location.setter <NEW_LINE> @abstractmethod <NEW_LINE> def entity_location(self, a_entity_location): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def entity_id(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @entity_id.setter <NEW_LINE> @abstractmethod <NEW_LINE> def entity_id(self, a_entity_id): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def base_url(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def review(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def build_base_url(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_num_reviews(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @max_num_reviews.setter <NEW_LINE> @abstractmethod <NEW_LINE> def max_num_reviews(self, a_max_num_reviews): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def timeout(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @timeout.setter <NEW_LINE> @abstractmethod <NEW_LINE> def timeout(self, a_timeout): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def pause_btween_requests(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @pause_btween_requests.setter <NEW_LINE> def pause_btween_requests(self, a_pause_btween_requests): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_attempts(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @max_attempts.setter <NEW_LINE> def max_attempts(self, a_max_attempts): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def get_review_ids(self): <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def get_review(self, review_id): <NEW_LINE> <INDENT> ... | Abstract class for the definition of a crawler. | 625990764f6381625f19a161 |
class DagA: <NEW_LINE> <INDENT> def __init__(self, go_a, ancestors, go2depth, w_e, godag): <NEW_LINE> <INDENT> self.go_a = go_a <NEW_LINE> self.ancestors = ancestors <NEW_LINE> self.goids = self._init_goids() <NEW_LINE> self.go2svalue = self._init_go2svalue(go2depth, w_e, godag) <NEW_LINE> <DEDENT> def get_sv(self): <NEW_LINE> <INDENT> return sum(self.go2svalue.values()) <NEW_LINE> <DEDENT> def get_svalues(self, goids): <NEW_LINE> <INDENT> s_go2svalue = self.go2svalue <NEW_LINE> return [s_go2svalue[go] for go in goids] <NEW_LINE> <DEDENT> def _init_go2svalue(self, go2depth, w_e, godag): <NEW_LINE> <INDENT> go2svalue = {self.go_a: 1.0} <NEW_LINE> if not self.ancestors: <NEW_LINE> <INDENT> return go2svalue <NEW_LINE> <DEDENT> terms_a = self.goids <NEW_LINE> w_r = {r:v for r, v in w_e.items() if r != 'is_a'} <NEW_LINE> for ancestor_id in self._get_sorted(go2depth): <NEW_LINE> <INDENT> goterm = godag[ancestor_id] <NEW_LINE> weight = w_e['is_a'] <NEW_LINE> svals = [weight*go2svalue[o.item_id] for o in goterm.children if o.item_id in terms_a] <NEW_LINE> for rel, weight in w_r.items(): <NEW_LINE> <INDENT> if rel in goterm.relationship_rev: <NEW_LINE> <INDENT> for cobj in goterm.relationship_rev[rel]: <NEW_LINE> <INDENT> if cobj.item_id in terms_a: <NEW_LINE> <INDENT> svals.append(weight*go2svalue[cobj.item_id]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if svals: <NEW_LINE> <INDENT> go2svalue[ancestor_id] = max(svals) <NEW_LINE> <DEDENT> <DEDENT> return go2svalue <NEW_LINE> <DEDENT> def _get_sorted(self, go2depth): <NEW_LINE> <INDENT> go2dep = {go:go2depth[go] for go in self.ancestors} <NEW_LINE> go_dep = sorted(go2dep.items(), key=lambda t: t[1], reverse=True) <NEW_LINE> gos, _ = zip(*go_dep) <NEW_LINE> return gos <NEW_LINE> <DEDENT> def _init_goids(self): <NEW_LINE> <INDENT> goids = set(self.ancestors) <NEW_LINE> goids.add(self.go_a) <NEW_LINE> return goids | A GO term, A, can be represented as DAG_a = (A, T_a, E_a), aka a GoSubDag | 62599076e1aae11d1e7cf4c5 |
class Win7SP1x64_23418(obj.Profile): <NEW_LINE> <INDENT> _md_memory_model = '64bit' <NEW_LINE> _md_os = 'windows' <NEW_LINE> _md_major = 6 <NEW_LINE> _md_minor = 1 <NEW_LINE> _md_build = 7601 <NEW_LINE> _md_vtype_module = 'volatility.plugins.overlays.windows.win7_sp1_x64_632B36E0_vtypes' <NEW_LINE> _md_product = ["NtProductWinNt"] | A Profile for Windows 7 SP1 x64 (6.1.7601.23418 / 2016-04-09) | 625990767d847024c075dd47 |
class MagiclinkPattern(LinkInlineProcessor): <NEW_LINE> <INDENT> ANCESTOR_EXCLUDES = ('a',) <NEW_LINE> def handleMatch(self, m, data): <NEW_LINE> <INDENT> el = etree.Element("a") <NEW_LINE> el.text = md_util.AtomicString(m.group('link')) <NEW_LINE> if m.group("www"): <NEW_LINE> <INDENT> href = "http://%s" % m.group('link') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> href = m.group('link') <NEW_LINE> if self.config['hide_protocol']: <NEW_LINE> <INDENT> el.text = md_util.AtomicString(el.text[el.text.find("://") + 3:]) <NEW_LINE> <DEDENT> <DEDENT> el.set("href", self.unescape(href.strip())) <NEW_LINE> if self.config.get('repo_url_shortener', False): <NEW_LINE> <INDENT> el.set('magiclink', str(MAGIC_LINK)) <NEW_LINE> <DEDENT> return el, m.start(0), m.end(0) | Convert html, ftp links to clickable links. | 625990765fc7496912d48f20 |
class Key(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _("Key") <NEW_LINE> verbose_name_plural = _("Keys") <NEW_LINE> <DEDENT> key = models.TextField() <NEW_LINE> fingerprint = models.CharField(max_length=200, blank=True, editable=False) <NEW_LINE> use_asc = models.BooleanField(default=False, help_text=_( "If True, an '.asc' extension will be added to email attachments " "sent to the address for this key.")) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.fingerprint <NEW_LINE> <DEDENT> @property <NEW_LINE> def email_addresses(self): <NEW_LINE> <INDENT> return ",".join(str(address) for address in self.address_set.all()) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> gpg = get_gpg() <NEW_LINE> result = gpg.import_keys(self.key) <NEW_LINE> addresses = [] <NEW_LINE> for key in result.results: <NEW_LINE> <INDENT> addresses.extend(addresses_for_key(gpg, key)) <NEW_LINE> <DEDENT> self.fingerprint = result.fingerprints[0] <NEW_LINE> super(Key, self).save(*args, **kwargs) <NEW_LINE> for address in addresses: <NEW_LINE> <INDENT> address, _ = Address.objects.get_or_create( key=self, address=address) <NEW_LINE> address.use_asc = self.use_asc <NEW_LINE> address.save() | Accepts a key and imports it via admin's save_model which
omits saving. | 6259907660cbc95b06365a24 |
class TrainsCollection(object): <NEW_LINE> <INDENT> headers = '车次 车站 时间 历时 商务 一等 二等 软卧 硬卧 软座 硬座 无座'.split() <NEW_LINE> def __init__(self, rows, opts): <NEW_LINE> <INDENT> self._rows = rows <NEW_LINE> self._opts = opts <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<TrainsCollection size={}>'.format(len(self)) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> if i < len(self): <NEW_LINE> <INDENT> yield self[i] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield next(self) <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._rows) <NEW_LINE> <DEDENT> def _get_duration(self, row): <NEW_LINE> <INDENT> duration = row.get('lishi').replace(':', '小时') + '分钟' <NEW_LINE> if duration.startswith('00'): <NEW_LINE> <INDENT> return duration[4:] <NEW_LINE> <DEDENT> if duration.startswith('0'): <NEW_LINE> <INDENT> return duration[1:] <NEW_LINE> <DEDENT> return duration <NEW_LINE> <DEDENT> @property <NEW_LINE> def trains(self): <NEW_LINE> <INDENT> for row in self._rows: <NEW_LINE> <INDENT> train_no = row.get('station_train_code') <NEW_LINE> initial = train_no[0].lower() <NEW_LINE> if not self._opts or initial in self._opts: <NEW_LINE> <INDENT> train = [ train_no, '\n'.join([ colored.green(row.get('from_station_name')), colored.red(row.get('to_station_name')), ]), '\n'.join([ colored.green(row.get('start_time')), colored.red(row.get('arrive_time')), ]), self._get_duration(row), row.get('swz_num'), row.get('zy_num'), row.get('ze_num'), row.get('rw_num'), row.get('yw_num'), row.get('rz_num'), row.get('yz_num'), row.get('wz_num') ] <NEW_LINE> yield train <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def pretty_print(self): <NEW_LINE> <INDENT> pt = PrettyTable() <NEW_LINE> if len(self) == 0: <NEW_LINE> <INDENT> pt._set_field_names(['Sorry,']) <NEW_LINE> pt.add_row([TRAIN_NOT_FOUND]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pt._set_field_names(self.headers) <NEW_LINE> for train in self.trains: <NEW_LINE> <INDENT> pt.add_row(train) <NEW_LINE> <DEDENT> <DEDENT> print(pt) | A set of raw datas from a query. | 62599076fff4ab517ebcf184 |
class DeleteActivityInputSet(InputSet): <NEW_LINE> <INDENT> def set_AccessToken(self, value): <NEW_LINE> <INDENT> super(DeleteActivityInputSet, self)._set_input('AccessToken', value) <NEW_LINE> <DEDENT> def set_ActivityID(self, value): <NEW_LINE> <INDENT> super(DeleteActivityInputSet, self)._set_input('ActivityID', value) | An InputSet with methods appropriate for specifying the inputs to the DeleteActivity
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 625990765166f23b2e244d44 |
class DialogController (object): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__ (self, dialog, application, initial = u""): <NEW_LINE> <INDENT> self._dialog = dialog <NEW_LINE> self._application = application <NEW_LINE> items = sorted (self.getParam (LJConfig (self._application.config))) <NEW_LINE> self._items = [item.strip() for item in items if len (item.strip()) != 0] <NEW_LINE> self._result = u"" <NEW_LINE> self._initDialog (initial) <NEW_LINE> <DEDENT> def _initDialog (self, initial): <NEW_LINE> <INDENT> self._dialog.Clear() <NEW_LINE> self._dialog.AppendItems (self._items) <NEW_LINE> self._dialog.SetValue (initial) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def getParam (self, config): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def setParam (self, config, value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def getCommandName (self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def result (self): <NEW_LINE> <INDENT> return self._result <NEW_LINE> <DEDENT> def showDialog (self): <NEW_LINE> <INDENT> dlgResult = self._dialog.ShowModal() <NEW_LINE> if dlgResult == wx.ID_OK: <NEW_LINE> <INDENT> name = self._dialog.GetValue().strip() <NEW_LINE> self._result = u"(:{command} {name}:)".format (command = self.getCommandName(), name = name) <NEW_LINE> if (len (name) != 0 and name not in self._items): <NEW_LINE> <INDENT> self._items.append (name) <NEW_LINE> clearItems = sorted ([item for item in self._items if len (item.strip()) != 0]) <NEW_LINE> self.setParam (LJConfig (self._application.config), clearItems) <NEW_LINE> <DEDENT> <DEDENT> return dlgResult | Базовый класс для диалога вставки пользователя и сообщества ЖЖ | 62599076cc0a2c111447c788 |
class Bounds(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.is_empty_ = True <NEW_LINE> self.min_ = None <NEW_LINE> self.max_ = None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def CreateFromEvent(event): <NEW_LINE> <INDENT> bounds = Bounds() <NEW_LINE> bounds.AddEvent(event) <NEW_LINE> return bounds <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.is_empty_: <NEW_LINE> <INDENT> return "Bounds()" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Bounds(min=%s,max=%s)" % (self.min_, self.max_) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def is_empty(self): <NEW_LINE> <INDENT> return self.is_empty_ <NEW_LINE> <DEDENT> @property <NEW_LINE> def min(self): <NEW_LINE> <INDENT> if self.is_empty_: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.min_ <NEW_LINE> <DEDENT> @property <NEW_LINE> def max(self): <NEW_LINE> <INDENT> if self.is_empty_: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.max_ <NEW_LINE> <DEDENT> @property <NEW_LINE> def bounds(self): <NEW_LINE> <INDENT> if self.is_empty_: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.max_ - self.min_ <NEW_LINE> <DEDENT> @property <NEW_LINE> def center(self): <NEW_LINE> <INDENT> return (self.min_ + self.max_) * 0.5 <NEW_LINE> <DEDENT> def Contains(self, other): <NEW_LINE> <INDENT> if self.is_empty or other.is_empty: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.min <= other.min and self.max >= other.max <NEW_LINE> <DEDENT> def Intersects(self, other): <NEW_LINE> <INDENT> if self.is_empty or other.is_empty: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return not (other.max < self.min or other.min > self.max) <NEW_LINE> <DEDENT> def Reset(self): <NEW_LINE> <INDENT> self.is_empty_ = True <NEW_LINE> self.min_ = None <NEW_LINE> self.max_ = None <NEW_LINE> <DEDENT> def AddBounds(self, bounds): <NEW_LINE> <INDENT> if bounds.is_empty: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.AddValue(bounds.min_) <NEW_LINE> self.AddValue(bounds.max_) <NEW_LINE> <DEDENT> def AddValue(self, value): <NEW_LINE> <INDENT> if self.is_empty_: <NEW_LINE> <INDENT> self.max_ = value <NEW_LINE> self.min_ = value <NEW_LINE> self.is_empty_ = False <NEW_LINE> return <NEW_LINE> <DEDENT> self.max_ = max(self.max_, value) <NEW_LINE> self.min_ = min(self.min_, value) <NEW_LINE> <DEDENT> def AddEvent(self, event): <NEW_LINE> <INDENT> self.AddValue(event.start) <NEW_LINE> self.AddValue(event.start + event.duration) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def CompareByMinTimes(a, b): <NEW_LINE> <INDENT> if not a.is_empty and not b.is_empty: <NEW_LINE> <INDENT> return a.min_ - b.min_ <NEW_LINE> <DEDENT> if a.is_empty and not b.is_empty: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if not a.is_empty and b.is_empty: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return 0 | Represents a min-max bounds. | 62599076167d2b6e312b8248 |
class DummyDNSDriver(DNSDriver): <NEW_LINE> <INDENT> name = "Dummy DNS Provider" <NEW_LINE> website = "http://example.com" <NEW_LINE> def __init__(self, api_key, api_secret): <NEW_LINE> <INDENT> self._zones = {} <NEW_LINE> <DEDENT> def list_record_types(self): <NEW_LINE> <INDENT> return [RecordType.A] <NEW_LINE> <DEDENT> def list_zones(self): <NEW_LINE> <INDENT> return [zone["zone"] for zone in list(self._zones.values())] <NEW_LINE> <DEDENT> def list_records(self, zone): <NEW_LINE> <INDENT> return self._zones[zone.id]["records"].values() <NEW_LINE> <DEDENT> def get_zone(self, zone_id): <NEW_LINE> <INDENT> if zone_id not in self._zones: <NEW_LINE> <INDENT> raise ZoneDoesNotExistError(driver=self, value=None, zone_id=zone_id) <NEW_LINE> <DEDENT> return self._zones[zone_id]["zone"] <NEW_LINE> <DEDENT> def get_record(self, zone_id, record_id): <NEW_LINE> <INDENT> self.get_zone(zone_id=zone_id) <NEW_LINE> zone_records = self._zones[zone_id]["records"] <NEW_LINE> if record_id not in zone_records: <NEW_LINE> <INDENT> raise RecordDoesNotExistError(record_id=record_id, value=None, driver=self) <NEW_LINE> <DEDENT> return zone_records[record_id] <NEW_LINE> <DEDENT> def create_zone(self, domain, type="master", ttl=None, extra=None): <NEW_LINE> <INDENT> id = "id-%s" % (domain) <NEW_LINE> if id in self._zones: <NEW_LINE> <INDENT> raise ZoneAlreadyExistsError(zone_id=id, value=None, driver=self) <NEW_LINE> <DEDENT> zone = Zone(id=id, domain=domain, type=type, ttl=ttl, extra={}, driver=self) <NEW_LINE> self._zones[id] = {"zone": zone, "records": {}} <NEW_LINE> return zone <NEW_LINE> <DEDENT> def create_record(self, name, zone, type, data, extra=None): <NEW_LINE> <INDENT> id = "id-%s" % (name) <NEW_LINE> zone = self.get_zone(zone_id=zone.id) <NEW_LINE> if id in self._zones[zone.id]["records"]: <NEW_LINE> <INDENT> raise RecordAlreadyExistsError(record_id=id, value=None, driver=self) <NEW_LINE> <DEDENT> record = Record( id=id, name=name, type=type, data=data, extra=extra, zone=zone, driver=self ) <NEW_LINE> self._zones[zone.id]["records"][id] = record <NEW_LINE> return record <NEW_LINE> <DEDENT> def delete_zone(self, zone): <NEW_LINE> <INDENT> self.get_zone(zone_id=zone.id) <NEW_LINE> del self._zones[zone.id] <NEW_LINE> return True <NEW_LINE> <DEDENT> def delete_record(self, record): <NEW_LINE> <INDENT> self.get_record(zone_id=record.zone.id, record_id=record.id) <NEW_LINE> del self._zones[record.zone.id]["records"][record.id] <NEW_LINE> return True | Dummy DNS driver.
>>> from libcloud.dns.drivers.dummy import DummyDNSDriver
>>> driver = DummyDNSDriver('key', 'secret')
>>> driver.name
'Dummy DNS Provider' | 6259907666673b3332c31d6c |
class MethodNotAvailableInAPIVersion(Exception): <NEW_LINE> <INDENT> def __init__(self, current_api_version, method): <NEW_LINE> <INDENT> self.api_version = current_api_version <NEW_LINE> self.method = method <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Method '%s' is not available in the %s api version." % (self.method, self.api_version) | Try to call API method, which is not available. | 6259907638b623060ffaa50d |
class GameTieAction(Action): <NEW_LINE> <INDENT> def __init__(self, winner=None, gameName = None, other=None): <NEW_LINE> <INDENT> Action.__init__(self, AUDIT_TIE_GAME) <NEW_LINE> self.gameName = gameName <NEW_LINE> if winner is not None: <NEW_LINE> <INDENT> self.winner = '%s (%d)' % (winner.username, int(winner.score)) <NEW_LINE> <DEDENT> if other is not None: <NEW_LINE> <INDENT> self.other = '' <NEW_LINE> for o in other: <NEW_LINE> <INDENT> self.other += '%s (%d)' % (o.username, int(o.score)) <NEW_LINE> self.other += ', ' <NEW_LINE> <DEDENT> self.other = self.other[:-2] <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s %s %s %s %s" % (self.winner, lookup.SERVER_MESSAGE_LOOKUP[lookup.TIED_WITH], self.other, lookup.SERVER_MESSAGE_LOOKUP[lookup.PLAYING_IN], self.gameName) | Game tie action | 625990762c8b7c6e89bd5157 |
class Optimizer(object): <NEW_LINE> <INDENT> def __init__(self, parameters, **kwargs): <NEW_LINE> <INDENT> self.parameters = parameters <NEW_LINE> self.lr = kwargs.pop('lr', 0.001) <NEW_LINE> self.l1_weight_decay = kwargs.pop('l1_weight_decay', 0.0) <NEW_LINE> self.l2_weight_decay = kwargs.pop('l2_weight_decay', 0.0) <NEW_LINE> self.gradient_clip = kwargs.pop('gradient_clip', 0.0) <NEW_LINE> self.state = dict() <NEW_LINE> for p in self.parameters(): <NEW_LINE> <INDENT> self.state[p] = dict() <NEW_LINE> <DEDENT> <DEDENT> def zero_grad(self): <NEW_LINE> <INDENT> for p in self.parameters(): <NEW_LINE> <INDENT> if p.grad is not None: <NEW_LINE> <INDENT> p.grad = np.zeros(p.shape) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def clip_grads(self): <NEW_LINE> <INDENT> if self.gradient_clip != 0.0: <NEW_LINE> <INDENT> for p in self.parameters(): <NEW_LINE> <INDENT> p.grad = np.clip(p.grad, -self.gradient_clip, self.gradient_clip) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def step(self): <NEW_LINE> <INDENT> self.clip_grads() <NEW_LINE> self._step() <NEW_LINE> <DEDENT> def _step(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Base class for all optimizers
| 6259907621bff66bcd7245d7 |
class DetailView(BaseCart): <NEW_LINE> <INDENT> def get(self, request, sku_id): <NEW_LINE> <INDENT> context = cache.get("detail_%s" % sku_id) <NEW_LINE> if context is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sku = GoodsSKU.objects.get(id=sku_id) <NEW_LINE> <DEDENT> except GoodsSKU.DoesNotExist: <NEW_LINE> <INDENT> return redirect(reverse('goods:index')) <NEW_LINE> <DEDENT> categorys = GoodsCategory.objects.all() <NEW_LINE> sku_orders = sku.ordergoods_set.all().order_by('-create_time')[0:30] <NEW_LINE> if sku_orders: <NEW_LINE> <INDENT> for sku_order in sku_orders: <NEW_LINE> <INDENT> sku_order.ctime = sku_order.create_time.strftime('%Y-%m-%d %H:%M:%S') <NEW_LINE> sku_order.username = sku_order.order.user.username <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> sku_orders = [] <NEW_LINE> <DEDENT> new_skus = GoodsSKU.objects.filter(category=sku.category).order_by('-create_time')[0:2] <NEW_LINE> other_skus = sku.goods.goodssku_set.exclude(id=sku_id) <NEW_LINE> context = { "categorys": categorys, "sku": sku, "orders": sku_orders, "new_skus": new_skus, "other_skus": other_skus } <NEW_LINE> cache.set("detail_%s" % sku_id, context, 3600) <NEW_LINE> <DEDENT> cart_num = self.get_cart_num(request) <NEW_LINE> context['cart_num'] = cart_num <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> redis_conn = get_redis_connection('default') <NEW_LINE> redis_conn.lrem('history_%s' % user.id, 0, sku_id) <NEW_LINE> redis_conn.lpush('history_%s' % user.id, sku_id) <NEW_LINE> redis_conn.ltrim('history_%s' % user.id, 0, 4) <NEW_LINE> <DEDENT> return render(request, 'detail.html', context) | 商品详情页的视图函数 | 625990767cff6e4e811b73ae |
class ANSIColors: <NEW_LINE> <INDENT> HEADER = '\033[95m' <NEW_LINE> OKBLUE = '\033[94m' <NEW_LINE> OKCYAN = '\033[96m' <NEW_LINE> OKGREEN = '\033[92m' <NEW_LINE> WARNING = '\033[93m' <NEW_LINE> FAIL = '\033[91m' <NEW_LINE> ENDC = '\033[0m' <NEW_LINE> BOLD = '\033[1m' <NEW_LINE> UNDERLINE = '\033[4m' <NEW_LINE> @classmethod <NEW_LINE> def header(cls, string: str) -> str: <NEW_LINE> <INDENT> return f'{cls.HEADER}{string}{cls.ENDC}' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def okblue(cls, string: str) -> str: <NEW_LINE> <INDENT> return f'{cls.OKBLUE}{string}{cls.ENDC}' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def okcyan(cls, string: str) -> str: <NEW_LINE> <INDENT> return f'{cls.OKCYAN}{string}{cls.ENDC}' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def okgreen(cls, string: str) -> str: <NEW_LINE> <INDENT> return f'{cls.OKGREEN}{string}{cls.ENDC}' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def warning(cls, string: str) -> str: <NEW_LINE> <INDENT> return f'{cls.WARNING}{string}{cls.ENDC}' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fail(cls, string: str) -> str: <NEW_LINE> <INDENT> return f'{cls.FAIL}{string}{cls.ENDC}' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def bold(cls, string: str) -> str: <NEW_LINE> <INDENT> return f'{cls.BOLD}{string}{cls.ENDC}' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def underline(cls, string: str) -> str: <NEW_LINE> <INDENT> return f'{cls.UNDERLINE}{string}{cls.ENDC}' | Classe com `sequências de scape` ANSI que formatam a saída no terminal. | 625990764f6381625f19a162 |
class Account: <NEW_LINE> <INDENT> def __init__(self, holder, created_on, account_number, account_type, balance=0.0): <NEW_LINE> <INDENT> self._holder = holder <NEW_LINE> self._created_on = created_on <NEW_LINE> self._account_number = account_number <NEW_LINE> self._account_type = account_type <NEW_LINE> self._balance = balance <NEW_LINE> <DEDENT> def get_holder(self): <NEW_LINE> <INDENT> return self._holder <NEW_LINE> <DEDENT> def get_created_on(self): <NEW_LINE> <INDENT> return self._created_on <NEW_LINE> <DEDENT> def get_account_number(self): <NEW_LINE> <INDENT> return self._account_number <NEW_LINE> <DEDENT> def get_account_type(self): <NEW_LINE> <INDENT> return self._account_type <NEW_LINE> <DEDENT> def get_balance(self): <NEW_LINE> <INDENT> return self._balance <NEW_LINE> <DEDENT> def update_balance(self, amount): <NEW_LINE> <INDENT> self._balance += amount | Implementation of a customer's bank account.
Can hold and update a balance.
Can process withdrawals and deposits made by the account holder. | 62599076e1aae11d1e7cf4c6 |
class JustfixDevelopmentDefaults(JustfixEnvironment): <NEW_LINE> <INDENT> SECRET_KEY = "for development only!" <NEW_LINE> SECURE_SSL_REDIRECT = False <NEW_LINE> SESSION_COOKIE_SECURE = False <NEW_LINE> CSRF_COOKIE_SECURE = False <NEW_LINE> TWOFACTOR_VERIFY_DURATION = 0 | Reasonable defaults for developing the project. | 625990767d847024c075dd49 |
class CommentsView(generics.ListCreateAPIView): <NEW_LINE> <INDENT> lookup_field = 'article__slug' <NEW_LINE> lookup_url_kwarg = 'slug' <NEW_LINE> permission_classes = (IsAuthenticatedOrReadOnly,) <NEW_LINE> queryset = Comment.objects.select_related( 'article', 'user' ) <NEW_LINE> serializer_class = CommentSerializer <NEW_LINE> def filter_queryset(self, queryset): <NEW_LINE> <INDENT> filters = { self.lookup_field: self.kwargs[self.lookup_url_kwarg] } <NEW_LINE> return queryset.filter(**filters) <NEW_LINE> <DEDENT> def create(self, request, slug=None): <NEW_LINE> <INDENT> data = request.data <NEW_LINE> context = {'user': request.user} <NEW_LINE> try: <NEW_LINE> <INDENT> context['article'] = Article.objects.get(slug=slug) <NEW_LINE> <DEDENT> except Article.DoesNotExist: <NEW_LINE> <INDENT> raise NotFound('An article with this slug does not exist.') <NEW_LINE> <DEDENT> serializer = self.serializer_class(data=data, context=context) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) | This is a controller for users to create, read, and alter comments. | 625990768a349b6b43687bc9 |
class d3MapRendererDialogTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_icon_png(self): <NEW_LINE> <INDENT> path = ':/plugins/d3MapRenderer/icon.png' <NEW_LINE> icon = QIcon(path) <NEW_LINE> self.assertFalse(icon.isNull()) | Test rerources work. | 625990767047854f46340d28 |
class JSONSchemaField(JSONBField): <NEW_LINE> <INDENT> format_checker = FormatChecker() <NEW_LINE> empty_values = (None, '') <NEW_LINE> def get_default(self): <NEW_LINE> <INDENT> return copy.deepcopy(super(JSONBField, self).get_default()) <NEW_LINE> <DEDENT> def schema(self, model_instance): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def validate(self, value, model_instance): <NEW_LINE> <INDENT> super(JSONSchemaField, self).validate(value, model_instance) <NEW_LINE> errors = [] <NEW_LINE> for error in Draft4Validator( self.schema(model_instance), format_checker=self.format_checker ).iter_errors(value): <NEW_LINE> <INDENT> if error.validator == 'pattern' and 'error' in error.schema: <NEW_LINE> <INDENT> error.message = error.schema['error'].format(instance=error.instance) <NEW_LINE> <DEDENT> elif error.validator == 'type': <NEW_LINE> <INDENT> expected_type = error.validator_value <NEW_LINE> if expected_type == 'object': <NEW_LINE> <INDENT> expected_type = 'dict' <NEW_LINE> <DEDENT> if error.path: <NEW_LINE> <INDENT> error.message = _( '{type} provided in relative path {path}, expected {expected_type}' ).format(path=list(error.path), type=type(error.instance).__name__, expected_type=expected_type) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error.message = _( '{type} provided, expected {expected_type}' ).format(path=list(error.path), type=type(error.instance).__name__, expected_type=expected_type) <NEW_LINE> <DEDENT> <DEDENT> elif error.validator == 'additionalProperties' and hasattr(error, 'path'): <NEW_LINE> <INDENT> error.message = _( 'Schema validation error in relative path {path} ({error})' ).format(path=list(error.path), error=error.message) <NEW_LINE> <DEDENT> errors.append(error) <NEW_LINE> <DEDENT> if errors: <NEW_LINE> <INDENT> raise django_exceptions.ValidationError( [e.message for e in errors], code='invalid', params={'value': value}, ) | A JSONB field that self-validates against a defined JSON schema
(http://json-schema.org). This base class is intended to be overwritten by
defining `self.schema`. | 6259907697e22403b383c872 |
class AnnotationTransformEvent: <NEW_LINE> <INDENT> def __init__(self, request, annotation, annotation_dict): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> self.annotation = annotation <NEW_LINE> self.annotation_dict = annotation_dict | An event fired before an annotation is indexed or otherwise needs to be
transformed by third-party code.
This event can be used by subscribers who wish to modify the content of an
annotation just before it is indexed or in other use-cases. | 625990761b99ca40022901ed |
class BaseREVAEMNIST(nn.Module): <NEW_LINE> <INDENT> def __init__(self, z_c_dim, z_exc_dim): <NEW_LINE> <INDENT> super(BaseREVAEMNIST, self).__init__() <NEW_LINE> self._z_c_dim = z_c_dim <NEW_LINE> self._z_exc_dim = z_exc_dim <NEW_LINE> self.encoder = _Encoder(z_c_dim + z_exc_dim) <NEW_LINE> self.decoder = _Decoder(z_c_dim + z_exc_dim) <NEW_LINE> self.classifier = _Classifier(z_c_dim) <NEW_LINE> self.cond_prior = _ConditionalPrior(z_c_dim) <NEW_LINE> <DEDENT> @property <NEW_LINE> def z_c_dim(self): <NEW_LINE> <INDENT> return self._z_c_dim <NEW_LINE> <DEDENT> @property <NEW_LINE> def z_exc_dim(self): <NEW_LINE> <INDENT> return self._z_exc_dim <NEW_LINE> <DEDENT> def forward(self, x, y): <NEW_LINE> <INDENT> raise NotImplementedError() | A base class of the Reparameterized VAE (REVAE) for the MNIST dataset.
Args:
z_c_dim (int): The dimension of z_c.
z_exc_dim (int): The dimension of z_\c. | 625990764527f215b58eb658 |
class Retention(object): <NEW_LINE> <INDENT> __slots__ = ("stages",) <NEW_LINE> def __init__(self, stages): <NEW_LINE> <INDENT> prev = None <NEW_LINE> if not stages: <NEW_LINE> <INDENT> raise InvalidArgumentError("there must be at least one stage") <NEW_LINE> <DEDENT> for s in stages: <NEW_LINE> <INDENT> if prev and s.precision % prev.precision: <NEW_LINE> <INDENT> raise InvalidArgumentError( "precision of %s must be a multiple of %s" % (s, prev) ) <NEW_LINE> <DEDENT> if prev and prev.duration >= s.duration: <NEW_LINE> <INDENT> raise InvalidArgumentError( "duration of %s must be lesser than %s" % (s, prev) ) <NEW_LINE> <DEDENT> prev = s <NEW_LINE> <DEDENT> self.stages = tuple(stages) <NEW_LINE> self.stages[0].stage0 = True <NEW_LINE> <DEDENT> def __getitem__(self, n): <NEW_LINE> <INDENT> return self.stages[n] <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.stages) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Retention): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.stages == other.stages <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) <NEW_LINE> <DEDENT> @property <NEW_LINE> def as_string(self): <NEW_LINE> <INDENT> return ":".join(s.as_string for s in self.stages) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, string): <NEW_LINE> <INDENT> if string: <NEW_LINE> <INDENT> stages = [Stage.from_string(s) for s in string.split(":")] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stages = [] <NEW_LINE> <DEDENT> return cls(stages=stages) <NEW_LINE> <DEDENT> @property <NEW_LINE> def duration(self): <NEW_LINE> <INDENT> if not self.stages: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return self.stages[-1].duration <NEW_LINE> <DEDENT> @property <NEW_LINE> def stage0(self): <NEW_LINE> <INDENT> return self.stages[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def downsampled_stages(self): <NEW_LINE> <INDENT> return self.stages[1:] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_carbon(cls, elem): <NEW_LINE> <INDENT> stages = [Stage(points=points, precision=precision) for precision, points in elem] <NEW_LINE> return cls(stages) <NEW_LINE> <DEDENT> def find_stage_for_ts(self, searched, now): <NEW_LINE> <INDENT> for stage in self.stages: <NEW_LINE> <INDENT> if searched > now - stage.duration: <NEW_LINE> <INDENT> return stage <NEW_LINE> <DEDENT> <DEDENT> return self.stages[-1] <NEW_LINE> <DEDENT> def align_time_window(self, start_time, end_time, now, shift=False): <NEW_LINE> <INDENT> stage = self.find_stage_for_ts(searched=start_time, now=now) <NEW_LINE> now = stage.round_up(now) <NEW_LINE> if shift: <NEW_LINE> <INDENT> oldest_timestamp = now - stage.duration <NEW_LINE> start_time = max(start_time, oldest_timestamp) <NEW_LINE> <DEDENT> start_time = min(now, start_time) <NEW_LINE> start_time = stage.round_down(start_time) <NEW_LINE> end_time = min(now, end_time) <NEW_LINE> end_time = stage.round_up(end_time) <NEW_LINE> if end_time < start_time: <NEW_LINE> <INDENT> end_time = start_time <NEW_LINE> <DEDENT> return start_time, end_time, stage <NEW_LINE> <DEDENT> @property <NEW_LINE> def points(self): <NEW_LINE> <INDENT> return sum(stage.points for stage in self.stages) | A retention policy, made of 0 or more Stages. | 6259907656ac1b37e630399a |
class Anistream(Anime, sitename='anistream.xyz'): <NEW_LINE> <INDENT> sitename = 'anistream.xyz' <NEW_LINE> QUALITIES = ['360p', '480p', '720p', '1080p'] <NEW_LINE> @classmethod <NEW_LINE> def search(self, query): <NEW_LINE> <INDENT> soup = helpers.soupify(helpers.get(f"https://anistream.xyz/search?term={query}")) <NEW_LINE> results = soup.select_one('.card-body').select('a') <NEW_LINE> results = [ SearchResult(title=v.text, url=v.attrs['href']) for v in results ] <NEW_LINE> return results <NEW_LINE> <DEDENT> def _scrape_episodes(self): <NEW_LINE> <INDENT> version = self.config.get('version', 'subbed') <NEW_LINE> soup = helpers.soupify(helpers.get(self.url)) <NEW_LINE> versions = soup.select_one('.card-body').select('ul') <NEW_LINE> def get_links(version): <NEW_LINE> <INDENT> links = [v.attrs['href'] for v in version.select('a')][::-1] <NEW_LINE> return links <NEW_LINE> <DEDENT> dubbed = get_links(versions[1]) <NEW_LINE> subbed = get_links(versions[0]) <NEW_LINE> if version.lower() == 'dubbed': <NEW_LINE> <INDENT> choice = dubbed <NEW_LINE> other = subbed <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> choice = subbed <NEW_LINE> other = dubbed <NEW_LINE> <DEDENT> if choice: <NEW_LINE> <INDENT> return choice <NEW_LINE> <DEDENT> return other <NEW_LINE> <DEDENT> def _scrape_metadata(self): <NEW_LINE> <INDENT> soup = helpers.soupify(helpers.get(self.url)) <NEW_LINE> self.title = soup.select_one('.card-header > h1').text | Site: http://anistream.xyz
Config
------
version: One of ['subbed', 'dubbed]
Selects the version of audio of anime. | 6259907699fddb7c1ca63a8d |
class ETandemCommandline(_EmbossCommandLine): <NEW_LINE> <INDENT> def __init__(self, cmd="etandem", **kwargs): <NEW_LINE> <INDENT> self.parameters = [ _Option(["-sequence", "sequence"], "Sequence", filename=True, is_required=True), _Option(["-minrepeat", "minrepeat"], "Minimum repeat size", is_required=True), _Option(["-maxrepeat", "maxrepeat"], "Maximum repeat size", is_required=True), _Option(["-threshold", "threshold"], "Threshold score"), _Option(["-mismatch", "mismatch"], "Allow N as a mismatch"), _Option(["-uniform", "uniform"], "Allow uniform consensus"), _Option(["-rformat", "rformat"], "Output report format")] <NEW_LINE> _EmbossCommandLine.__init__(self, cmd, **kwargs) | Commandline object for the etandem program from EMBOSS.
| 6259907638b623060ffaa50e |
class Discretise: <NEW_LINE> <INDENT> def __init__(self,bin_sizes,state_mins,state_maxs): <NEW_LINE> <INDENT> if isinstance(bin_sizes,types.IntType): <NEW_LINE> <INDENT> self._num_dim = 1 <NEW_LINE> <DEDENT> elif isinstance(bin_sizes,list): <NEW_LINE> <INDENT> assert len(bin_sizes) == len(state_mins) == len(state_maxs) <NEW_LINE> self._num_dim = len(bin_sizes) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> warnings.warn("all inputs should be of either int or np.ndarray your input is " + type(bin_sizes), Warning) <NEW_LINE> <DEDENT> self.bin_sizes = bin_sizes <NEW_LINE> self.state_mins = state_mins <NEW_LINE> self.state_maxs = state_maxs <NEW_LINE> <DEDENT> def bound_value(self,value,vmin,vmax): <NEW_LINE> <INDENT> if value < vmin: <NEW_LINE> <INDENT> return vmin <NEW_LINE> <DEDENT> elif value > vmax: <NEW_LINE> <INDENT> return vmax <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> def numtoint(self,state): <NEW_LINE> <INDENT> assert isinstance(state,numbers.Number) <NEW_LINE> state = self.bound_value(float(state),self.state_mins,self.state_maxs) <NEW_LINE> return int(round((state - self.state_mins)/(self.state_maxs - self.state_mins) * self.bin_sizes, 0)) <NEW_LINE> <DEDENT> def num1Dlist2int(self,states): <NEW_LINE> <INDENT> assert isinstance(states,list) <NEW_LINE> return [ self.numtoint(s) for s in states ] <NEW_LINE> <DEDENT> def vecNDtoint(self, state): <NEW_LINE> <INDENT> assert isinstance(state, np.ndarray) <NEW_LINE> idx = 0 <NEW_LINE> state_j = 0 <NEW_LINE> for j in range(0,dims-1): <NEW_LINE> <INDENT> state_j = self.bound_value(state[j],self.state_mins[j],self.state_maxs[j]) <NEW_LINE> idx = idx + np.prod(self._N[j+1:]) * round( (state_j - self.state_mins[j])/(self.state_maxs[j] - self.state_mins[j]) * self.bin_sizes[j] , 0 ) <NEW_LINE> <DEDENT> state_j = self.bound_value(state[-1],self.state_mins[-1],self.state_maxs[-1]) <NEW_LINE> idx = idx + round( (state_j - self.state_mins[-1])/(self.state_maxs[-1] - self.state_mins[-1]) * self.bin_sizes[-1], 0) <NEW_LINE> return idx <NEW_LINE> <DEDENT> def vecNDtoint(self,states): <NEW_LINE> <INDENT> assert isinstance(state,np.ndarray) <NEW_LINE> return [ self.vecNDtoint(s) for s in states ] | Discretises multivariate continuous state array to an index. This is
necessary when runing discrete RL methods on continuous state
environments. | 62599076379a373c97d9a992 |
class GameWorld: <NEW_LINE> <INDENT> def __init__( self, *, engine: Engine, map_width: int, map_height: int, max_rooms: int, room_min_size: int, room_max_size: int, max_monsters_per_room: int, max_items_per_room: int, current_floor: int = 0 ): <NEW_LINE> <INDENT> self.engine = engine <NEW_LINE> self.map_width = map_width <NEW_LINE> self.map_height = map_height <NEW_LINE> self.max_rooms = max_rooms <NEW_LINE> self.room_min_size = room_min_size <NEW_LINE> self.room_max_size = room_max_size <NEW_LINE> self.max_monsters_per_room = max_monsters_per_room <NEW_LINE> self.max_items_per_room = max_items_per_room <NEW_LINE> self.current_floor = current_floor <NEW_LINE> <DEDENT> def generate_floor(self) -> None: <NEW_LINE> <INDENT> from procgen import generate_dungeon <NEW_LINE> self.current_floor += 1 <NEW_LINE> self.engine.game_map = generate_dungeon( max_rooms=self.max_rooms, room_min_size=self.room_min_size, room_max_size=self.room_max_size, map_width=self.map_width, map_height=self.map_height, max_monsters_per_room=self.max_monsters_per_room, max_items_per_room=self.max_items_per_room, engine=self.engine, ) | Holds the settings for the GameMap and generates new maps when moving down stairs | 62599076f548e778e596ceff |
@ui.register_ui( button_close=ui.Button(By.CLASS_NAME, 'inmplayer-popover-close-button')) <NEW_LINE> class WelcomeModal(ui.Block): <NEW_LINE> <INDENT> pass | Welcome modal block. | 625990764428ac0f6e659e9f |
class Agent(object): <NEW_LINE> <INDENT> def __init__(self, bandit, policy, prior=0, gamma=None): <NEW_LINE> <INDENT> self.policy = policy <NEW_LINE> self.k = bandit.k <NEW_LINE> self.prior = prior <NEW_LINE> self.gamma = gamma <NEW_LINE> self._value_estimates = prior * np.ones(self.k) <NEW_LINE> self.action_attempts = np.zeros(self.k) <NEW_LINE> self.t = 0 <NEW_LINE> self.last_action = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'f/{}'.format(str(self.policy)) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._value_estimates[:] = self.prior <NEW_LINE> self.action_attempts[:] = 0 <NEW_LINE> self.last_action = None <NEW_LINE> self.t = 0 <NEW_LINE> <DEDENT> def choose(self): <NEW_LINE> <INDENT> action = self.policy.choose(self) <NEW_LINE> self.last_action = action <NEW_LINE> return action <NEW_LINE> <DEDENT> def observe(self, reward): <NEW_LINE> <INDENT> self.action_attempts[self.last_action] += 1 <NEW_LINE> if self.gamma is None: <NEW_LINE> <INDENT> g = 1 / self.action_attempts[self.last_action] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> g = self.gamma <NEW_LINE> <DEDENT> q = self._value_estimates[self.last_action] <NEW_LINE> self._value_estimates[self.last_action] += g * (reward - q) <NEW_LINE> self.t += 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def value_estimates(self): <NEW_LINE> <INDENT> return self._value_estimates | An Agent is able to take one of a set of actions at each time step. The
action is chosen using a strategy based on the history of prior actions
and outcome observations. | 625990767c178a314d78e8a3 |
class KeyInfo(Model): <NEW_LINE> <INDENT> _validation = { 'start': {'required': True}, 'expiry': {'required': True}, } <NEW_LINE> _attribute_map = { 'start': {'key': 'Start', 'type': 'str', 'xml': {'name': 'Start'}}, 'expiry': {'key': 'Expiry', 'type': 'str', 'xml': {'name': 'Expiry'}}, } <NEW_LINE> _xml_map = { } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(KeyInfo, self).__init__(**kwargs) <NEW_LINE> self.start = kwargs.get('start', None) <NEW_LINE> self.expiry = kwargs.get('expiry', None) | Key information.
All required parameters must be populated in order to send to Azure.
:param start: Required. The date-time the key is active in ISO 8601 UTC
time
:type start: str
:param expiry: Required. The date-time the key expires in ISO 8601 UTC
time
:type expiry: str | 6259907663b5f9789fe86ad6 |
class ModelBase(caching.base.CachingMixin, models.Model): <NEW_LINE> <INDENT> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> modified = models.DateTimeField(auto_now=True) <NEW_LINE> objects = ManagerBase() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> get_latest_by = 'created' <NEW_LINE> <DEDENT> def get_absolute_url(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_url_path(*args, **kwargs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _cache_key(cls, pk, db): <NEW_LINE> <INDENT> key_parts = ('o', cls._meta, pk, 'default') <NEW_LINE> return ':'.join(map(encoding.smart_unicode, key_parts)) <NEW_LINE> <DEDENT> def reload(self): <NEW_LINE> <INDENT> from_db = self.__class__.objects.get(pk=self.pk) <NEW_LINE> for field in self.__class__._meta.fields: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(self, field.name, getattr(from_db, field.name)) <NEW_LINE> <DEDENT> except models.ObjectDoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def update(self, **kw): <NEW_LINE> <INDENT> signal = kw.pop('_signal', True) <NEW_LINE> cls = self.__class__ <NEW_LINE> for k, v in kw.items(): <NEW_LINE> <INDENT> setattr(self, k, v) <NEW_LINE> <DEDENT> if signal: <NEW_LINE> <INDENT> attrs = dict(self.__dict__) <NEW_LINE> models.signals.pre_save.send(sender=cls, instance=self) <NEW_LINE> for k, v in self.__dict__.items(): <NEW_LINE> <INDENT> if attrs[k] != v: <NEW_LINE> <INDENT> kw[k] = v <NEW_LINE> setattr(self, k, v) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> objects = getattr(cls, 'with_deleted', cls.objects) <NEW_LINE> objects.filter(pk=self.pk).update(**kw) <NEW_LINE> if signal: <NEW_LINE> <INDENT> models.signals.post_save.send(sender=cls, instance=self, created=False) | Base class for zamboni models to abstract some common features.
* Adds automatic created and modified fields to the model.
* Fetches all translations in one subsequent query during initialization. | 62599076aad79263cf430129 |
class Molecule(Mol): <NEW_LINE> <INDENT> def __init__(self, atomic_numbers=None, coords=None, atom_names=None, model=None, residue_seq=None, chain=None, sheet=None, helix=None, is_hetatm=None): <NEW_LINE> <INDENT> if atomic_numbers is None and coords is None: <NEW_LINE> <INDENT> self.Initialize() <NEW_LINE> <DEDENT> elif not isinstance(atomic_numbers, np.ndarray) or not isinstance(coords, np.ndarray): <NEW_LINE> <INDENT> raise ValueError('atom_types and coords must be numpy arrays.') <NEW_LINE> <DEDENT> elif len(atomic_numbers) == len(coords): <NEW_LINE> <INDENT> self.atom_names = atom_names <NEW_LINE> self.model = model <NEW_LINE> self.residue_seq = residue_seq <NEW_LINE> self.chain = chain <NEW_LINE> self.sheet = sheet <NEW_LINE> self.helix = helix <NEW_LINE> self.is_hetatm = is_hetatm <NEW_LINE> coords = numpy_to_vtk_points(coords) <NEW_LINE> atom_nums = nps.numpy_to_vtk(atomic_numbers, array_type=VTK_UNSIGNED_SHORT) <NEW_LINE> atom_nums.SetName("Atomic Numbers") <NEW_LINE> fieldData = DataSetAttributes() <NEW_LINE> fieldData.AddArray(atom_nums) <NEW_LINE> self.Initialize(coords, fieldData) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n1 = len(coords) <NEW_LINE> n2 = len(atomic_numbers) <NEW_LINE> raise ValueError('Mismatch in length of atomic_numbers({0}) and ' 'length of atomic_coords({1}).'.format(n1, n2)) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def total_num_atoms(self): <NEW_LINE> <INDENT> return self.GetNumberOfAtoms() <NEW_LINE> <DEDENT> @property <NEW_LINE> def total_num_bonds(self): <NEW_LINE> <INDENT> return self.GetNumberOfBonds() | Your molecule class.
An object that is used to create molecules and store molecular data (e.g.
coordinate and bonding data).
This is a more pythonic version of ``Molecule``. | 6259907697e22403b383c874 |
class TemplateTagTests(test.TestCase): <NEW_LINE> <INDENT> def render_template_tag(self, tag_name, tag_require=''): <NEW_LINE> <INDENT> tag_call = "{%% %s %%}" % tag_name <NEW_LINE> return self.render_template(tag_call, tag_require) <NEW_LINE> <DEDENT> def render_template(self, template_text, tag_require='', context={}): <NEW_LINE> <INDENT> template = Template("{%% load %s %%} %s" % (tag_require, template_text)) <NEW_LINE> return template.render(Context(context)) <NEW_LINE> <DEDENT> def test_site_branding_tag(self): <NEW_LINE> <INDENT> rendered_str = self.render_template_tag("site_branding", "branding") <NEW_LINE> self.assertEqual(settings.SITE_BRANDING, rendered_str.strip(), "tag site_branding renders %s" % rendered_str.strip()) <NEW_LINE> <DEDENT> def test_size_format_filters(self): <NEW_LINE> <INDENT> size_str = ('5|diskgbformat', '10|diskgbformat', '5555|mb_float_format', '80|mb_float_format', '.5|mbformat', '0.005|mbformat', '0.0005|mbformat') <NEW_LINE> expected = u' 5.0GB 10.0GB 5.4GB 80.0MB 512KB 5KB 524Bytes ' <NEW_LINE> text = '' <NEW_LINE> for size_filter in size_str: <NEW_LINE> <INDENT> text += '{{' + size_filter + '}} ' <NEW_LINE> <DEDENT> rendered_str = self.render_template(tag_require='sizeformat', template_text=text) <NEW_LINE> self.assertEqual(rendered_str, expected) <NEW_LINE> <DEDENT> def test_size_format_filters_with_string(self): <NEW_LINE> <INDENT> size_str = ('"test"|diskgbformat', '"limit"|mb_float_format', '"no limit"|mbformat') <NEW_LINE> expected = u' test limit no limit ' <NEW_LINE> text = '' <NEW_LINE> for size_filter in size_str: <NEW_LINE> <INDENT> text += '{{' + size_filter + '}} ' <NEW_LINE> <DEDENT> rendered_str = self.render_template(tag_require='sizeformat', template_text=text) <NEW_LINE> self.assertEqual(rendered_str, expected) <NEW_LINE> <DEDENT> def test_truncate_filter(self): <NEW_LINE> <INDENT> ctx_string = {'val1': 'he', 'val2': 'hellotrunc', 'val3': 'four'} <NEW_LINE> text = ('{{test.val1|truncate:1}}#{{test.val2|truncate:4}}#' '{{test.val3|truncate:10}}') <NEW_LINE> expected = u' h#h...#four' <NEW_LINE> rendered_str = self.render_template(tag_require='truncate_filter', template_text=text, context={'test': ctx_string}) <NEW_LINE> self.assertEqual(rendered_str, expected) <NEW_LINE> <DEDENT> def test_quota_filter(self): <NEW_LINE> <INDENT> ctx_string = {'val1': 100, 'val2': 1000, 'val3': float('inf')} <NEW_LINE> text = ('{{test.val1|quota:"TB"}}#{{test.val2|quota}}#' '{{test.val3|quota}}') <NEW_LINE> expected = u' 100 TB Available#1000 Available#No Limit' <NEW_LINE> rendered_str = self.render_template(tag_require='horizon', template_text=text, context={'test': ctx_string}) <NEW_LINE> self.assertEqual(rendered_str, expected) | Test Custom Template Tag. | 6259907632920d7e50bc79b9 |
class LossyQueueHandler(handlers.QueueHandler): <NEW_LINE> <INDENT> def enqueue(self, record): <NEW_LINE> <INDENT> self.queue.appendleft(record) | Like QueueHandler, except it'll try and keep the youngest, not oldest,
entries. | 62599076091ae356687065ab |
class PasswordForm(Form): <NEW_LINE> <INDENT> old_pwd = PasswordField(u'Old Password') <NEW_LINE> pwd = PasswordField(u'Password', [ EqualTo('confirm', message='Passwords must match'), Length(min=PWD_MIN_LENGTH, max=PWD_MAX_LENGTH) ]) <NEW_LINE> confirm = PasswordField(u'Repeat Password') <NEW_LINE> change = SubmitField(u'Change Password') <NEW_LINE> @login_required <NEW_LINE> def validate(self): <NEW_LINE> <INDENT> rv = Form.validate(self) <NEW_LINE> if rv: <NEW_LINE> <INDENT> if hashpw(self.old_pwd.data, current_user.pwd) == current_user.pwd: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flash("Your old password is incorrect") <NEW_LINE> <DEDENT> <DEDENT> flash("Your new password did not match with the confirmation password") <NEW_LINE> return False | Form for changing password | 625990764c3428357761bc28 |
class SocketClosedException(Exception): <NEW_LINE> <INDENT> def __init__(self, peer): <NEW_LINE> <INDENT> log.info("Peer %s closed connection" % (str(peer.peer))) <NEW_LINE> self.peer = peer | Raised when a peer closes their socket | 6259907655399d3f05627e86 |
class AddableJoinOp(JoinOp): <NEW_LINE> <INDENT> __slots__ = ('_parent',) <NEW_LINE> def __init__(self, *sources: Event): <NEW_LINE> <INDENT> JoinOp.__init__(self) <NEW_LINE> self._sources = deque() <NEW_LINE> self._parent = None <NEW_LINE> self._set_sources(*sources) <NEW_LINE> <DEDENT> def _set_sources(self, *sources): <NEW_LINE> <INDENT> for source in sources: <NEW_LINE> <INDENT> source = Event.create(source) <NEW_LINE> self.add_source(source) <NEW_LINE> <DEDENT> <DEDENT> def add_source(self, source): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_parent(self, parent: Event): <NEW_LINE> <INDENT> self._parent = parent <NEW_LINE> parent.done_event += self._on_parent_done <NEW_LINE> <DEDENT> def on_source_done(self, source): <NEW_LINE> <INDENT> self._disconnect_from(source) <NEW_LINE> self._sources.remove(source) <NEW_LINE> if not self._sources and self._parent is None: <NEW_LINE> <INDENT> self.set_done() <NEW_LINE> <DEDENT> <DEDENT> def _on_parent_done(self, parent): <NEW_LINE> <INDENT> parent -= self._on_parent_done <NEW_LINE> self._parent = None <NEW_LINE> if not self._sources: <NEW_LINE> <INDENT> self.set_done() | Base class for join operators where new sources, produced by a
parent higher-order event, can be added dynamically. | 6259907699fddb7c1ca63a8e |
class Menu: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.options = [] | Menu class. | 6259907626068e7796d4e2ae |
class SynonymStandardizationDictionary: <NEW_LINE> <INDENT> def __init__(self, syntax_file=None, syntax_directory=None): <NEW_LINE> <INDENT> self.syntax_file = syntax_file <NEW_LINE> self.syntax_directory = syntax_directory <NEW_LINE> if syntax_file == None and syntax_directory == None: <NEW_LINE> <INDENT> raise Exception("Either syntax_file or syntax_directory required.") <NEW_LINE> <DEDENT> if syntax_file != None and syntax_directory != None: <NEW_LINE> <INDENT> raise Exception("Only one of syntax_file and syntax_directory can be provided.") <NEW_LINE> <DEDENT> self.load_syntax() <NEW_LINE> <DEDENT> def load_syntax(self): <NEW_LINE> <INDENT> if self.syntax_file != None: <NEW_LINE> <INDENT> self.syntax_list = [] <NEW_LINE> with open(pkg_resources.resource_filename(__name__, self.syntax_file), 'r') as sf: <NEW_LINE> <INDENT> for syntax_entry in json.load(sf): <NEW_LINE> <INDENT> for from_word in syntax_entry["from"]: <NEW_LINE> <INDENT> self.syntax_list.append({'to': syntax_entry['to'], 'from': from_word}) <NEW_LINE> <DEDENT> self.syntax_list.append({'to': syntax_entry['to'], 'from': syntax_entry['to']}) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif self.syntax_directory != None: <NEW_LINE> <INDENT> self.syntax_list = [] <NEW_LINE> for f in pkg_resources.resource_listdir(__name__, self.syntax_directory): <NEW_LINE> <INDENT> with open(pkg_resources.resource_filename(__name__, self.syntax_directory + "/" + f), 'r') as sf: <NEW_LINE> <INDENT> for syntax_entry in json.load(sf): <NEW_LINE> <INDENT> for from_word in syntax_entry["from"]: <NEW_LINE> <INDENT> self.syntax_list.append({'to': syntax_entry['to'], 'from': from_word}) <NEW_LINE> <DEDENT> self.syntax_list.append({'to': syntax_entry['to'], 'from': syntax_entry['to']}) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Both syntax_file and syntax_directory are None; cannot load syntax.") <NEW_LINE> <DEDENT> for syntax_item in self.syntax_list: <NEW_LINE> <INDENT> if "to" not in syntax_item or "from" not in syntax_item: <NEW_LINE> <INDENT> raise InvalidSynonymStandardizationDictionary("Every element needs to have a to field and a from field") <NEW_LINE> <DEDENT> <DEDENT> self.syntax_dictionary = {} <NEW_LINE> for syntax_index, syntax_item in enumerate(self.syntax_list): <NEW_LINE> <INDENT> if syntax_item["from"] in self.syntax_dictionary: <NEW_LINE> <INDENT> raise InvalidSynonymStandardizationDictionary("To command appearing twice: " + syntax_item["to"]) <NEW_LINE> <DEDENT> self.syntax_dictionary[syntax_item["from"]] = syntax_index <NEW_LINE> <DEDENT> <DEDENT> def get_standard_synonym(self, word, params = {}): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> syntax_entry = self.get_syntax_entry(word) <NEW_LINE> <DEDENT> except UnrecognizedSynonym: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return syntax_entry['to'] <NEW_LINE> <DEDENT> def get_syntax_entry(self, word): <NEW_LINE> <INDENT> if word not in self.syntax_dictionary: <NEW_LINE> <INDENT> raise UnrecognizedSynonym("The command " + word + " is not recognized.") <NEW_LINE> <DEDENT> syntax_entry = self.syntax_list[self.syntax_dictionary[word]] <NEW_LINE> return syntax_entry | Works as an interface for the synonym standardization dictionary. | 62599076dc8b845886d54f2c |
class MultiLabelMarginLoss(_Loss): <NEW_LINE> <INDENT> def forward(self, input, target): <NEW_LINE> <INDENT> _assert_no_grad(target) <NEW_LINE> return F.multilabel_margin_loss(input, target, size_average=self.size_average) | 创建一个标准, 用以优化多元分类问题的合页损失函数 (基于空白的损失), 计算损失值时
需要2个参数分别为输入, `x` (一个2维小批量 `Tensor`) 和输出 `y`
(一个2维 `Tensor`, 其值为 `x` 的索引值).
对于mini-batch(小批量) 中的每个样本按如下公式计算损失::
loss(x, y) = sum_ij(max(0, 1 - (x[y[j]] - x[i]))) / x.size(0)
其中 `i` 的取值范围是 `0` 到 `x.size(0)`, `j` 的取值范围是 `0` 到 `y.size(0)`,
`y[j] >= 0`, 并且对于所有 `i` 和 `j` 有 `i != y[j]`.
`y` 和 `x` 必须有相同的元素数量.
此标准仅考虑 `y[j]` 中最先出现的非零值.
如此可以允许每个样本可以有数量不同的目标类别. | 6259907621bff66bcd7245db |
class GPGKey(Base): <NEW_LINE> <INDENT> is_katello = True <NEW_LINE> delete_locator = locators['gpgkey.remove'] <NEW_LINE> def navigate_to_entity(self): <NEW_LINE> <INDENT> Navigator(self.browser).go_to_gpg_keys() <NEW_LINE> <DEDENT> def _search_locator(self): <NEW_LINE> <INDENT> return locators['gpgkey.key_name'] <NEW_LINE> <DEDENT> def create(self, name, upload_key=False, key_path=None, key_content=None): <NEW_LINE> <INDENT> self.click(locators['gpgkey.new']) <NEW_LINE> self.assign_value(common_locators['name'], name) <NEW_LINE> if upload_key: <NEW_LINE> <INDENT> self.assign_value(locators['gpgkey.file_path'], key_path) <NEW_LINE> <DEDENT> elif key_content: <NEW_LINE> <INDENT> self.click(locators['gpgkey.content']) <NEW_LINE> self.assign_value(locators['gpgkey.content'], key_content) <NEW_LINE> <DEDENT> self.click(common_locators['create']) <NEW_LINE> self.wait_until_element_is_not_visible(locators['gpgkey.new_form']) <NEW_LINE> <DEDENT> def update(self, name, new_name=None, new_key=None): <NEW_LINE> <INDENT> self.search_and_click(name) <NEW_LINE> if new_name: <NEW_LINE> <INDENT> self.edit_entity( locators['gpgkey.edit_name'], locators['gpgkey.edit_name_text'], new_name, locators['gpgkey.save_name'] ) <NEW_LINE> <DEDENT> if new_key: <NEW_LINE> <INDENT> self.edit_entity( locators['gpgkey.edit_content'], locators['gpgkey.file_path'], new_key, locators['gpgkey.save_content'] ) <NEW_LINE> <DEDENT> <DEDENT> def get_product_repo(self, key_name, entity_name, entity_type='Product'): <NEW_LINE> <INDENT> self.search_and_click(key_name) <NEW_LINE> if entity_type == 'Product': <NEW_LINE> <INDENT> self.click(tab_locators['gpgkey.tab_products']) <NEW_LINE> self.assign_value( locators['gpgkey.product_repo_search'], entity_name) <NEW_LINE> return self.wait_until_element( locators['gpgkey.product'] % entity_name) <NEW_LINE> <DEDENT> elif entity_type == 'Repository': <NEW_LINE> <INDENT> self.click(tab_locators['gpgkey.tab_repos']) <NEW_LINE> self.assign_value( locators['gpgkey.product_repo_search'], entity_name) <NEW_LINE> return self.wait_until_element( locators['gpgkey.repo'] % entity_name) <NEW_LINE> <DEDENT> <DEDENT> def assert_key_from_product(self, name, prd_element, repo=None): <NEW_LINE> <INDENT> self.click(prd_element) <NEW_LINE> if repo is not None: <NEW_LINE> <INDENT> self.click(tab_locators['prd.tab_repos']) <NEW_LINE> self.click(locators['repo.select'] % repo) <NEW_LINE> self.click(locators['repo.gpg_key_edit']) <NEW_LINE> element = self.get_element_value(locators['repo.gpg_key_update']) <NEW_LINE> if element != '': <NEW_LINE> <INDENT> raise UIError( 'GPGKey "{0}" is still assoc with selected repo' .format(name) ) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.click(tab_locators['prd.tab_details']) <NEW_LINE> self.click(locators['prd.gpg_key_edit']) <NEW_LINE> element = self.get_element_value(locators['prd.gpg_key_update']) <NEW_LINE> if element != '': <NEW_LINE> <INDENT> raise UIError( 'GPG key "{0}" is still assoc with product' .format(name) ) <NEW_LINE> <DEDENT> <DEDENT> return None | Manipulates GPG keys from UI. | 6259907692d797404e389814 |
class Tweet(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(User) <NEW_LINE> text = models.CharField(max_length=160) <NEW_LINE> created_date = models.DateTimeField(auto_now_add=True) <NEW_LINE> country = models.CharField(max_length=30) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.text | Tweet Model | 6259907676e4537e8c3f0ef1 |
class TestConnectToSequencescape(unittest.TestCase): <NEW_LINE> <INDENT> def test_returns_connection(self): <NEW_LINE> <INDENT> database_location = "dialect://HOST" <NEW_LINE> connection = connect_to_sequencescape(database_location) <NEW_LINE> self.assertIsInstance(connection, Connection) | Tests for `connect_to_sequencescape` method. | 625990764e4d562566373d74 |
class Story(): <NEW_LINE> <INDENT> def __init__(self, name, parameters=ParameterDeclarations()): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.acts = [] <NEW_LINE> if not isinstance(parameters,ParameterDeclarations): <NEW_LINE> <INDENT> raise TypeError('parameters input is not of type ParameterDeclarations') <NEW_LINE> <DEDENT> self.parameter = parameters <NEW_LINE> <DEDENT> def __eq__(self,other): <NEW_LINE> <INDENT> if isinstance(other,Story): <NEW_LINE> <INDENT> if self.get_attributes() == other.get_attributes() and self.parameter == other.parameter and self.acts == other.acts: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse(element): <NEW_LINE> <INDENT> name = element.attrib['name'] <NEW_LINE> if element.find('ParameterDeclarations') != None: <NEW_LINE> <INDENT> parameters = ParameterDeclarations.parse(element.find('ParameterDeclarations')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parameters = ParameterDeclarations() <NEW_LINE> <DEDENT> story = Story(name,parameters) <NEW_LINE> for a in element.findall('Act'): <NEW_LINE> <INDENT> story.add_act(Act.parse(a)) <NEW_LINE> <DEDENT> return story <NEW_LINE> <DEDENT> def add_act(self,act): <NEW_LINE> <INDENT> if not isinstance(act,Act): <NEW_LINE> <INDENT> raise TypeError('act input is not of type Act') <NEW_LINE> <DEDENT> self.acts.append(act) <NEW_LINE> <DEDENT> def get_attributes(self): <NEW_LINE> <INDENT> return {'name':self.name} <NEW_LINE> <DEDENT> def get_element(self): <NEW_LINE> <INDENT> element = ET.Element('Story',attrib=self.get_attributes()) <NEW_LINE> element.append(self.parameter.get_element()) <NEW_LINE> if not self.acts: <NEW_LINE> <INDENT> raise ValueError('no acts added to the story') <NEW_LINE> <DEDENT> for a in self.acts: <NEW_LINE> <INDENT> element.append(a.get_element()) <NEW_LINE> <DEDENT> return element | The Story class creates a story of the OpenScenario
Parameters
----------
name (str): name of the story
parameters (ParameterDeclarations): the parameters of the Story
Default: ParameterDeclarations()
Attributes
----------
name (str): name of the story
parameters (ParameterDeclarations): the parameters of the story (optional)
acts (list of Act): all acts belonging to the story
Methods
-------
parse(element)
parses a ElementTree created by the class and returns an instance of the class
add_act(act)
adds an act to the story
get_element()
Returns the full ElementTree of the class
get_attributes()
Returns a dictionary of all attributes of the class | 62599076baa26c4b54d50c22 |
class VideoGallery(SingletonModel, AbstractMeta): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return u"Video Gallery" <NEW_LINE> <DEDENT> def get_videos(self): <NEW_LINE> <INDENT> all_videos = (image for image in self.videogallerylink_set.filter(status=AbstractStatus.PUBLISHED)) <NEW_LINE> return all_videos | Video Gallery | 62599076283ffb24f3cf521d |
class ElectronicDevice: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.deviceAvailability= True <NEW_LINE> self.locationDevice= "not set" <NEW_LINE> self.deviceType="not set" <NEW_LINE> <DEDENT> def setDeviceAvailability(self, availability): <NEW_LINE> <INDENT> self.deviceAvailability = availability <NEW_LINE> <DEDENT> def setLocationDevice(self, location): <NEW_LINE> <INDENT> self.locationDevice= location <NEW_LINE> <DEDENT> def setDeviceType(self, type): <NEW_LINE> <INDENT> self.deviceType= type <NEW_LINE> <DEDENT> def getLocationDevice(self): <NEW_LINE> <INDENT> return self.locationDevice <NEW_LINE> <DEDENT> def getDeviceType(self): <NEW_LINE> <INDENT> return self.deviceType <NEW_LINE> <DEDENT> def printElectronicDevicesDetails(self): <NEW_LINE> <INDENT> print("The location of the {} is:{} " .format(self.deviceType, self.locationDevice)) <NEW_LINE> if self.deviceAvailability== True: <NEW_LINE> <INDENT> print("Device is available") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Device not available") <NEW_LINE> <DEDENT> <DEDENT> def checkAvailability(self): <NEW_LINE> <INDENT> if self.deviceAvailability== True: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Class to represent the electronic device | 6259907671ff763f4b5e911e |
class UpgradeNodeCommand(GraphCommand): <NEW_LINE> <INDENT> def __init__(self, graph, node, parent=None): <NEW_LINE> <INDENT> super(UpgradeNodeCommand, self).__init__(graph, parent) <NEW_LINE> self.nodeDict = node.toDict() <NEW_LINE> self.nodeName = node.getName() <NEW_LINE> self.outEdges = {} <NEW_LINE> self.setText("Upgrade Node {}".format(self.nodeName)) <NEW_LINE> <DEDENT> def redoImpl(self): <NEW_LINE> <INDENT> if not self.graph.node(self.nodeName).canUpgrade: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> upgradedNode, inEdges, self.outEdges = self.graph.upgradeNode(self.nodeName) <NEW_LINE> return upgradedNode <NEW_LINE> <DEDENT> def undoImpl(self): <NEW_LINE> <INDENT> self.graph.removeNode(self.nodeName) <NEW_LINE> with GraphModification(self.graph): <NEW_LINE> <INDENT> node = nodeFactory(self.nodeDict) <NEW_LINE> self.graph.addNode(node, self.nodeName) <NEW_LINE> for dstAttr, srcAttr in self.outEdges.items(): <NEW_LINE> <INDENT> self.graph.addEdge(self.graph.attribute(srcAttr), self.graph.attribute(dstAttr)) | Perform node upgrade on a CompatibilityNode. | 625990768a349b6b43687bcd |
class TunTapInterface(SuperSocket): <NEW_LINE> <INDENT> desc = "Act as the host's peer of a tun / tap interface" <NEW_LINE> def __init__(self, iface=None, mode_tun=None, *arg, **karg): <NEW_LINE> <INDENT> self.iface = conf.iface if iface is None else iface <NEW_LINE> self.mode_tun = ("tun" in self.iface) if mode_tun is None else mode_tun <NEW_LINE> self.closed = True <NEW_LINE> self.open() <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> if not self.closed: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.outs = self.ins = open( "/dev/net/tun" if LINUX else ("/dev/%s" % self.iface), "r+b", buffering=0 ) <NEW_LINE> if LINUX: <NEW_LINE> <INDENT> from fcntl import ioctl <NEW_LINE> ioctl(self.ins, 0x400454ca, struct.pack( "16sH", bytes_encode(self.iface), 0x0001 if self.mode_tun else 0x1002, )) <NEW_LINE> <DEDENT> self.closed = False <NEW_LINE> <DEDENT> def __call__(self, *arg, **karg): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def recv(self, x=MTU): <NEW_LINE> <INDENT> if self.mode_tun: <NEW_LINE> <INDENT> data = os.read(self.ins.fileno(), x + 4) <NEW_LINE> proto = struct.unpack('!H', data[2:4])[0] <NEW_LINE> return conf.l3types.get(proto, conf.raw_layer)(data[4:]) <NEW_LINE> <DEDENT> return conf.l2types.get(1, conf.raw_layer)( os.read(self.ins.fileno(), x) ) <NEW_LINE> <DEDENT> def send(self, x): <NEW_LINE> <INDENT> sx = raw(x) <NEW_LINE> if self.mode_tun: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> proto = conf.l3types[type(x)] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> log_runtime.warning( "Cannot find layer 3 protocol value to send %s in " "conf.l3types, using 0", x.name if hasattr(x, "name") else type(x).__name__ ) <NEW_LINE> proto = 0 <NEW_LINE> <DEDENT> sx = struct.pack('!HH', 0, proto) + sx <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> x.sent_time = time.time() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return os.write(self.outs.fileno(), sx) <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> log_runtime.error("%s send", self.__class__.__name__, exc_info=True) | A socket to act as the host's peer of a tun / tap interface.
| 625990767d43ff24874280cd |
class TestReview(TestBaseModel): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._class = Review <NEW_LINE> self._name = "Review" <NEW_LINE> <DEDENT> def test__class_attrs(self): <NEW_LINE> <INDENT> self.assertIsInstance(self._class.place_id, str) <NEW_LINE> self.assertIsInstance(self._class.user_id, str) <NEW_LINE> self.assertIsInstance(self._class.text, str) | Review Tests | 62599076be8e80087fbc0a06 |
class Link(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> url = models.URLField(max_length=1023) <NEW_LINE> project = models.ForeignKey('projects.Project', null=True) <NEW_LINE> user = models.ForeignKey('users.UserProfile', null=True) <NEW_LINE> subscription = models.ForeignKey(Subscription, null=True) | A link that can be added to a project or user. Links that have an Atom or
RSS feed will be subscribed to using the declared hub or SuperFeedrs. | 625990763317a56b869bf1ff |
@library.register(CONCENT_MSG_BASE + 11) <NEW_LINE> class ForceGetTaskResultFailed(tasks.TaskMessage): <NEW_LINE> <INDENT> TASK_ID_PROVIDERS = ('task_to_compute', ) <NEW_LINE> EXPECTED_OWNERS = (tasks.TaskMessage.OWNER_CHOICES.concent, ) <NEW_LINE> __slots__ = [ 'task_to_compute', ] + base.Message.__slots__ <NEW_LINE> MSG_SLOTS = { 'task_to_compute': base.MessageSlotDefinition(tasks.TaskToCompute), } | Sent from the Concent to the Requestor to announce a failure to retrieve
the results from the Provider.
Having received this message, the Requestor can use it later on
to reject any attempt at forced acceptance by proving the result
could not have been downloaded in the first place. | 62599076ad47b63b2c5a91c2 |
class GetEndpointResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) <NEW_LINE> <DEDENT> def get_NewAccessToken(self): <NEW_LINE> <INDENT> return self._output.get('NewAccessToken', None) | A ResultSet with methods tailored to the values returned by the GetEndpoint Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 62599076cc0a2c111447c78b |
class SaltKey(salt.utils.parsers.SaltKeyOptionParser): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> import salt.key <NEW_LINE> self.parse_args() <NEW_LINE> self.setup_logfile_logger() <NEW_LINE> verify_log(self.config) <NEW_LINE> key = salt.key.KeyCLI(self.config) <NEW_LINE> if check_user(self.config['user']): <NEW_LINE> <INDENT> key.run() | Initialize the Salt key manager | 62599076bf627c535bcb2e41 |
class DenseLayer(FullyConnectedLayer): <NEW_LINE> <INDENT> def __init__(self, input_dim, output_dim=100, weight_scale=1e-2): <NEW_LINE> <INDENT> self.input_dim = input_dim <NEW_LINE> self.output_dim = output_dim <NEW_LINE> W = weight_scale*np.random.rand(input_dim, output_dim) <NEW_LINE> b = np.zeros(output_dim) <NEW_LINE> self.params = [W, b] <NEW_LINE> <DEDENT> def feedforward(self, X): <NEW_LINE> <INDENT> out = relu_forward(np.dot(X, self.params[0]) + self.params[1]) <NEW_LINE> self.X = X <NEW_LINE> return out <NEW_LINE> <DEDENT> def backward(self, dout): <NEW_LINE> <INDENT> W, b = self.params <NEW_LINE> X = self.X <NEW_LINE> dX = np.zeros_like(X) <NEW_LINE> dW = np.zeros_like(W) <NEW_LINE> db = np.zeros_like(b) <NEW_LINE> dinput = relu_backward(dout, X.dot(W)+b) <NEW_LINE> dX = np.dot(dinput, W.T) <NEW_LINE> dW = np.dot(X.T, dinput) <NEW_LINE> db = np.sum(dinput, axis = 0) <NEW_LINE> self.gradients = [dW, db] <NEW_LINE> return dX | A dense hidden layer performs an affine transform followed by ReLU.
Here we use ReLU as default activation function. | 62599076379a373c97d9a996 |
class RangeDaily(RangeDailyBase): <NEW_LINE> <INDENT> def missing_datetimes(self, finite_datetimes): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cls_with_params = functools.partial(self.of, **self.of_params) <NEW_LINE> complete_parameters = self.of.bulk_complete.__func__(cls_with_params, map(self.datetime_to_parameter, finite_datetimes)) <NEW_LINE> return set(finite_datetimes) - set(map(self.parameter_to_datetime, complete_parameters)) <NEW_LINE> <DEDENT> except NotImplementedError: <NEW_LINE> <INDENT> return infer_bulk_complete_from_fs( finite_datetimes, lambda d: self._instantiate_task_cls(self.datetime_to_parameter(d)), lambda d: d.strftime('(%Y).*(%m).*(%d)')) | Efficiently produces a contiguous completed range of a daily recurring
task that takes a single ``DateParameter``.
Falls back to infer it from output filesystem listing to facilitate the
common case usage.
Convenient to use even from command line, like:
.. code-block:: console
luigi --module your.module RangeDaily --of YourActualTask --start 2014-01-01 | 625990764428ac0f6e659ea3 |
class Patch(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def num_cells_global(self): <NEW_LINE> <INDENT> return self.get_dim_attribute('num_cells') <NEW_LINE> <DEDENT> @property <NEW_LINE> def lower_global(self): <NEW_LINE> <INDENT> return self.get_dim_attribute('lower') <NEW_LINE> <DEDENT> @property <NEW_LINE> def upper_global(self): <NEW_LINE> <INDENT> return self.get_dim_attribute('upper') <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_dim(self): <NEW_LINE> <INDENT> return len(self._dimensions) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dimensions(self): <NEW_LINE> <INDENT> return [getattr(self,name) for name in self._dimensions] <NEW_LINE> <DEDENT> @property <NEW_LINE> def delta(self): <NEW_LINE> <INDENT> return self.get_dim_attribute('delta') <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._dimensions <NEW_LINE> <DEDENT> def __init__(self,dimensions): <NEW_LINE> <INDENT> self.level = 1 <NEW_LINE> self.patch_index = 1 <NEW_LINE> if isinstance(dimensions,Dimension): <NEW_LINE> <INDENT> dimensions = [dimensions] <NEW_LINE> <DEDENT> self._dimensions = [] <NEW_LINE> for dim in dimensions: <NEW_LINE> <INDENT> dim.on_lower_boundary = True <NEW_LINE> dim.on_upper_boundary = True <NEW_LINE> self.add_dimension(dim) <NEW_LINE> <DEDENT> self.grid = Grid(dimensions) <NEW_LINE> super(Patch,self).__init__() <NEW_LINE> <DEDENT> def add_dimension(self,dimension): <NEW_LINE> <INDENT> if dimension.name in self._dimensions: <NEW_LINE> <INDENT> raise Exception('Unable to add dimension. A dimension'+ ' of the same name: {name}, already exists.' .format(name=dimension.name)) <NEW_LINE> <DEDENT> self._dimensions.append(dimension.name) <NEW_LINE> setattr(self,dimension.name,dimension) <NEW_LINE> <DEDENT> def get_dim_attribute(self,attr): <NEW_LINE> <INDENT> return [getattr(getattr(self,name),attr) for name in self._dimensions] <NEW_LINE> <DEDENT> def __deepcopy__(self,memo={}): <NEW_LINE> <INDENT> import copy <NEW_LINE> result = self.__class__(copy.deepcopy(self.dimensions)) <NEW_LINE> result.__init__(copy.deepcopy(self.dimensions)) <NEW_LINE> result.grid.mapc2p = self.grid.mapc2p <NEW_LINE> for attr in ('level','patch_index'): <NEW_LINE> <INDENT> setattr(result,attr,copy.deepcopy(getattr(self,attr))) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> output = "Patch %s:\n" % self.patch_index <NEW_LINE> output += '\n'.join((str(getattr(self,dim)) for dim in self._dimensions)) <NEW_LINE> return output | :Global Patch information:
Each patch has a value for :attr:`level` and :attr:`patch_index`. | 625990768e7ae83300eeaa06 |
class LightObject: <NEW_LINE> <INDENT> def __eq__(self, other): <NEW_LINE> <INDENT> attr_names = dir(self) <NEW_LINE> for cur_attr in attr_names: <NEW_LINE> <INDENT> if not cur_attr.startswith('_'): <NEW_LINE> <INDENT> attr_val = getattr(self, cur_attr) <NEW_LINE> if not callable(attr_val) and attr_val != getattr(other, cur_attr): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | In-memory object
This class represents a POJO object which holds only simple
properties stored in memory but no indirect resources. | 625990763539df3088ecdc0c |
class AbstractFlags(AbstractSingleton): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def get(self, key): ... <NEW_LINE> @abstractmethod <NEW_LINE> def set(self, key, value): ... | Abstract Flags Class
This is a Abstract Singleton Class | 625990767047854f46340d2d |
class SealsIdentity(rf.Serializer): <NEW_LINE> <INDENT> SeaIdSEAID530 = RequiredStr(max_length=20, help_text='Seals identity') | SEAID529Type | 6259907632920d7e50bc79bc |
class OrderGoods(BaseModel): <NEW_LINE> <INDENT> SCORE_CHOICES = ( (0, '0分'), (1, '20分'), (2, '40分'), (3, '60分'), (4, '80分'), (5, '100分'), ) <NEW_LINE> order = models.ForeignKey(OrderInfo, related_name='skus', on_delete=models.CASCADE, verbose_name="订单") <NEW_LINE> sku = models.ForeignKey(Sku, on_delete=models.PROTECT, verbose_name="订单商品") <NEW_LINE> count = models.IntegerField(default=1, verbose_name="数量") <NEW_LINE> specs = models.CharField(verbose_name="商品属性",max_length=99) <NEW_LINE> price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="单价") <NEW_LINE> comment = models.TextField(default="", verbose_name="评价信息") <NEW_LINE> score = models.SmallIntegerField(choices=SCORE_CHOICES, default=5, verbose_name='满意度评分') <NEW_LINE> is_anonymous = models.BooleanField(default=False, verbose_name='是否匿名评价') <NEW_LINE> is_commented = models.BooleanField(default=False, verbose_name='是否评价了') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "tb_order_goods" <NEW_LINE> verbose_name = '订单商品' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.sku.name | 订单商品 | 625990768a43f66fc4bf3b0a |
class CustomProgEnvToolAction (CustomToolAction): <NEW_LINE> <INDENT> def get_tool(self, value): <NEW_LINE> <INDENT> if '=' in value: <NEW_LINE> <INDENT> env, default = value.split('=', 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> env, default = value, None <NEW_LINE> <DEDENT> return ProgEnvTool(env, default=default) | An action that sets ``tool`` with a custom `ProgEnvTool` instance. | 62599076097d151d1a2c29e9 |
class VoteLedger(Ledger): <NEW_LINE> <INDENT> def __init__(self, ballots): <NEW_LINE> <INDENT> super(VoteLedger, self).__init__() <NEW_LINE> self.total_ballots = len(ballots) <NEW_LINE> for ballot in ballots: <NEW_LINE> <INDENT> self.ledger[ballot] = STATE.CREATED <NEW_LINE> <DEDENT> self.ledger[STATE.CREATED] = self.total_ballots <NEW_LINE> self.ledger[STATE.ISSUED] = 0 <NEW_LINE> self.ledger[STATE.USED] = 0 <NEW_LINE> candidades = [] <NEW_LINE> for item in ballots[0].items: <NEW_LINE> <INDENT> for candidate in item.choices: <NEW_LINE> <INDENT> self.ledger[candidate] = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def apply_transactions(self, transactions): <NEW_LINE> <INDENT> for iteration in range(2): <NEW_LINE> <INDENT> for transaction in transactions: <NEW_LINE> <INDENT> if iteration == 1 and transaction._reiterate is False: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ballot = transaction.content <NEW_LINE> old_state = self.ledger[ballot] <NEW_LINE> tx_previous_state = transaction.previous_state <NEW_LINE> tx_new_state = transaction.new_state <NEW_LINE> if tx_previous_state != old_state: <NEW_LINE> <INDENT> transaction._reiterate = True <NEW_LINE> continue <NEW_LINE> <DEDENT> self.ledger[ballot] = tx_new_state <NEW_LINE> self.ledger[old_state] = self.ledger[old_state] - 1 <NEW_LINE> self.ledger[tx_new_state] = self.ledger[tx_new_state] + 1 <NEW_LINE> candidates = ballot.get_selected_choices() <NEW_LINE> for candidate in candidates: <NEW_LINE> <INDENT> self.ledger[candidate] = self.ledger[candidate] + 1 <NEW_LINE> <DEDENT> transaction._reiterate = False | Ledger that stores state of ballots, total votes for candidates as well as collective
totals of created, issued, and used ballots. | 6259907691f36d47f2231b49 |
class Logger(object): <NEW_LINE> <INDENT> _FORMAT_LOG_MSG = "%(asctime)s %(name)s %(levelname)s: %(message)s" <NEW_LINE> _FORMAT_LOG_DATE = "%Y/%m/%d %p %l:%M:%S" <NEW_LINE> def __init__(self, log_file_path=None, debug=False): <NEW_LINE> <INDENT> self.logger = logging.getLogger(type(self).__name__) <NEW_LINE> handler = logging.StreamHandler() <NEW_LINE> formatter = logging.Formatter( fmt=self._FORMAT_LOG_MSG, datefmt=self._FORMAT_LOG_DATE) <NEW_LINE> handler.setFormatter(formatter) <NEW_LINE> self.logger.addHandler(handler) <NEW_LINE> if log_file_path: <NEW_LINE> <INDENT> handler = logging.FileHandler(log_file_path, mode="a") <NEW_LINE> handler.setFormatter(formatter) <NEW_LINE> self.logger.addHandler(handler) <NEW_LINE> <DEDENT> if debug: <NEW_LINE> <INDENT> self.logger.setLevel(logging.DEBUG) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.setLevel(logging.INFO) | Logger base class for this module. | 625990767047854f46340d2e |
class ASSArticle(ASSItem): <NEW_LINE> <INDENT> _title: str <NEW_LINE> _keywords: list <NEW_LINE> _abstract: str <NEW_LINE> _author: list <NEW_LINE> _doi: str <NEW_LINE> _issn: str <NEW_LINE> _content: str <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> bibentry: dict <NEW_LINE> if ass_constant.BIB_ENTRY in kwargs: <NEW_LINE> <INDENT> bibentry = list(loadbibtex(open(kwargs[ass_constant.BIB_ENTRY])).entries_dict.values())[0] <NEW_LINE> <DEDENT> elif ass_constant.BIB_STR in kwargs: <NEW_LINE> <INDENT> bibentry = list(loadstrtex(kwargs[ass_constant.BIB_STR]).entries_dict.values())[0] <NEW_LINE> <DEDENT> elif ass_constant.BIB_JSON in kwargs: <NEW_LINE> <INDENT> bibentry = json.load(kwargs[ass_constant.BIB_STR]) <NEW_LINE> <DEDENT> elif ass_constant.BIB_DICT in kwargs: <NEW_LINE> <INDENT> bibentry = kwargs[ass_constant.BIB_DICT] <NEW_LINE> <DEDENT> self._title = bibentry.get(ass_constant.TITLE_TAG, None) <NEW_LINE> self._author = bibentry.get(ass_constant.AUTHOR_TAG, None) <NEW_LINE> self._keywords = bibentry.get(ass_constant.KEYWORD_TAG, None) <NEW_LINE> self._abstract = bibentry.get(ass_constant.ABSTRACT_TAG, None) <NEW_LINE> self._content = bibentry.get(ass_constant.CONTENT_TAG, None) <NEW_LINE> self._doi = bibentry.get(ass_constant.DOI_TAG, None) <NEW_LINE> self._issn = bibentry.get(ass_constant.ISSN_TAG, None) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self._content <NEW_LINE> <DEDENT> def title(self): <NEW_LINE> <INDENT> return self._title <NEW_LINE> <DEDENT> def author(self): <NEW_LINE> <INDENT> return self._author <NEW_LINE> <DEDENT> def abstract(self): <NEW_LINE> <INDENT> return self._abstract <NEW_LINE> <DEDENT> def keywords(self): <NEW_LINE> <INDENT> return self._keywords <NEW_LINE> <DEDENT> def content(self): <NEW_LINE> <INDENT> return self._content <NEW_LINE> <DEDENT> def raw(self) -> dict: <NEW_LINE> <INDENT> return { ass_constant.DOI_TAG: (self._doi if self._doi else ass_constant.NA), ass_constant.ISSN_TAG: (self._issn if self._issn else ass_constant.NA), ass_constant.TITLE_TAG: (self._title if self._title else ass_constant.NA), ass_constant.AUTHOR_TAG: ('; '.join(self._author) if self._author else ass_constant.NA), ass_constant.ABSTRACT_TAG: (self._abstract if self._abstract else ass_constant.NA), ass_constant.KEYWORD_TAG: ('; '.join(self._keywords) if self._keywords else ass_constant.NA), ass_constant.CONTENT_TAG: (self._content if self._content else ass_constant.NA) } <NEW_LINE> <DEDENT> def export_bibtex(self, file): <NEW_LINE> <INDENT> with open(file, 'w') as bib_file: <NEW_LINE> <INDENT> bib_file.write(BibTexWriter().write( { ass_constant.TITLE_TAG: self._title, ass_constant.AUTHOR_TAG: self._author, ass_constant.KEYWORD_TAG: self._keywords, ass_constant.ABSTRACT_TAG: self._abstract } )) <NEW_LINE> <DEDENT> <DEDENT> def export_json(self, file): <NEW_LINE> <INDENT> file = open(file, "w") <NEW_LINE> file.write(json.dumps( self.raw(), ensure_ascii=False, indent=0 )) <NEW_LINE> file.close() | The basic item element for a corpus made of scientific articles | 6259907667a9b606de54775f |
class InfoObjectFamily(DingoModel): <NEW_LINE> <INDENT> name = models.SlugField(max_length=256, unique=True, help_text="Identifier for InfoObject Family") <NEW_LINE> title = models.CharField(max_length=1024, blank=True, help_text="""A human-readable title for the InfoObject Family""") <NEW_LINE> description = models.TextField(blank=True) <NEW_LINE> @staticmethod <NEW_LINE> def autocomplete_search_fields(): <NEW_LINE> <INDENT> return ("name__icontains",) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "%s" % self.name | There may be several source formats of information objects,
for example:
- CybOx
- STIX
- OpenIOC
- ...
The 'family' associated with an Information Objects informs
about the source format. | 6259907699cbb53fe683285a |
class RuleViolationError(CommandFailure): <NEW_LINE> <INDENT> pass | Error indicating action being against the rules of contract bridge | 6259907601c39578d7f143ef |
class IndexRecordHash(Base): <NEW_LINE> <INDENT> __tablename__ = 'index_record_hash' <NEW_LINE> did = Column(String, ForeignKey('index_record.did'), primary_key=True) <NEW_LINE> hash_type = Column(String, primary_key=True) <NEW_LINE> hash_value = Column(String) | Base index record hash representation. | 62599076ad47b63b2c5a91c4 |
class HostGroupResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'items': 'list[HostGroup]' } <NEW_LINE> attribute_map = { 'items': 'items' } <NEW_LINE> required_args = { } <NEW_LINE> def __init__( self, items=None, ): <NEW_LINE> <INDENT> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, key, value): <NEW_LINE> <INDENT> if key not in self.attribute_map: <NEW_LINE> <INDENT> raise KeyError("Invalid key `{}` for `HostGroupResponse`".format(key)) <NEW_LINE> <DEDENT> self.__dict__[key] = value <NEW_LINE> <DEDENT> def __getattribute__(self, item): <NEW_LINE> <INDENT> value = object.__getattribute__(self, item) <NEW_LINE> if isinstance(value, Property): <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> if hasattr(self, attr): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if issubclass(HostGroupResponse, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, HostGroupResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | 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. | 6259907656b00c62f0fb4247 |
class OutputPluginDescriptor(rdf_structs.RDFProtoStruct): <NEW_LINE> <INDENT> protobuf = output_plugin_pb2.OutputPluginDescriptor <NEW_LINE> def GetPluginClass(self): <NEW_LINE> <INDENT> if self.plugin_name: <NEW_LINE> <INDENT> plugin_cls = OutputPlugin.classes.get(self.plugin_name) <NEW_LINE> if plugin_cls is None: <NEW_LINE> <INDENT> logging.warn("Unknown output plugin %s", self.plugin_name) <NEW_LINE> return UnknownOutputPlugin <NEW_LINE> <DEDENT> return plugin_cls <NEW_LINE> <DEDENT> <DEDENT> def GetPluginArgsClass(self): <NEW_LINE> <INDENT> plugin_cls = self.GetPluginClass() <NEW_LINE> if plugin_cls: <NEW_LINE> <INDENT> return plugin_cls.args_type <NEW_LINE> <DEDENT> <DEDENT> def GetPluginForState(self, plugin_state): <NEW_LINE> <INDENT> cls = self.GetPluginClass() <NEW_LINE> return cls(None, state=plugin_state) <NEW_LINE> <DEDENT> def GetPluginVerifiersClasses(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> if self.plugin_name: <NEW_LINE> <INDENT> for cls in OutputPluginVerifier.classes.values(): <NEW_LINE> <INDENT> if cls.plugin_name == self.plugin_name: <NEW_LINE> <INDENT> result.append(cls) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def GetPluginVerifiers(self): <NEW_LINE> <INDENT> return [cls() for cls in self.GetPluginVerifiersClasses()] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> result = self.plugin_name <NEW_LINE> if self.plugin_args: <NEW_LINE> <INDENT> result += " <%s>" % utils.SmartStr(self.plugin_args) <NEW_LINE> <DEDENT> return result | An rdfvalue describing the output plugin to create. | 625990765166f23b2e244d4c |
class DummyModelFactory(factory.DjangoModelFactory): <NEW_LINE> <INDENT> FACTORY_FOR = DummyModel <NEW_LINE> charfield = factory.Sequence(lambda n: 'charfield {0}'.format(n)) | Factory for the ``DummyModel`` test model. | 62599076796e427e538500ef |
class Transposition_cipher_range_keys(unittest.TestCase): <NEW_LINE> <INDENT> def test_Transposition_range_keys(self): <NEW_LINE> <INDENT> for test_key in range(1, int(len(test_message) / 2)): <NEW_LINE> <INDENT> transposition_test = Transposition(test_message, key=test_key) <NEW_LINE> self.assertEqual(transposition_test.decrypt(), test_message) | Test Transposition cipher with keys in range of len(test_message). | 6259907638b623060ffaa511 |
class MediaControlPlugin(QtWidgets.QGroupBox, peacock.base.MediaControlWidgetBase, PostprocessorPlugin): <NEW_LINE> <INDENT> timeChanged = QtCore.pyqtSignal(float) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(MediaControlPlugin, self).__init__() <NEW_LINE> self.setEnabled(False) <NEW_LINE> self.setMainLayoutName('RightLayout') <NEW_LINE> self._data = [] <NEW_LINE> <DEDENT> @QtCore.pyqtSlot() <NEW_LINE> def onDataChanged(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.initialize(self._data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def onSetData(self, data): <NEW_LINE> <INDENT> if data != None: <NEW_LINE> <INDENT> for d in self._data: <NEW_LINE> <INDENT> d.dataChanged.disconnect(self.onDataChanged) <NEW_LINE> <DEDENT> self._data = data <NEW_LINE> <DEDENT> self._times = [] <NEW_LINE> for data in self._data: <NEW_LINE> <INDENT> data.dataChanged.connect(self.onDataChanged) <NEW_LINE> self._times += data.times() <NEW_LINE> <DEDENT> self._times = sorted(list(set(self._times))) <NEW_LINE> self._num_steps = len(self._times) <NEW_LINE> if self._times: <NEW_LINE> <INDENT> self.setVisible(True) <NEW_LINE> self.updateControls() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.setVisible(False) <NEW_LINE> <DEDENT> <DEDENT> def updateControls(self, **kwargs): <NEW_LINE> <INDENT> self._current_step = kwargs.pop('timestep', self._current_step) <NEW_LINE> time = kwargs.pop('time', None) <NEW_LINE> if time != None: <NEW_LINE> <INDENT> idx = bisect.bisect_right(self._times, time) - 1 <NEW_LINE> if idx < 0: <NEW_LINE> <INDENT> idx = 0 <NEW_LINE> <DEDENT> elif idx > len(self._times)-1: <NEW_LINE> <INDENT> idx = -1 <NEW_LINE> <DEDENT> self._current_step = idx <NEW_LINE> <DEDENT> self.updateTimeDisplay() <NEW_LINE> self.timeChanged.emit(self._times[self._current_step]) | Time controls for Postprocessor data.
Args:
date[list]: A list of PostprocessorDataWidget objects. | 62599076ec188e330fdfa21c |
class HomeController: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def show(self, request: Request, view: View): <NEW_LINE> <INDENT> if not Auth(request).user(): <NEW_LINE> <INDENT> request.redirect('/login') <NEW_LINE> <DEDENT> return view.render('auth/home', {'app': request.app().make('Application'), 'Auth': Auth(request)}) | Home Dashboard Controller
| 625990762ae34c7f260aca5b |
class TestCDAtaListAttributes(SoupTest): <NEW_LINE> <INDENT> def test_single_value_becomes_list(self): <NEW_LINE> <INDENT> soup = self.soup("<a class='foo'>") <NEW_LINE> self.assertEqual(["foo"],soup.a['class']) <NEW_LINE> <DEDENT> def test_multiple_values_becomes_list(self): <NEW_LINE> <INDENT> soup = self.soup("<a class='foo bar'>") <NEW_LINE> self.assertEqual(["foo", "bar"], soup.a['class']) <NEW_LINE> <DEDENT> def test_multiple_values_separated_by_weird_whitespace(self): <NEW_LINE> <INDENT> soup = self.soup("<a class='foo\tbar\nbaz'>") <NEW_LINE> self.assertEqual(["foo", "bar", "baz"],soup.a['class']) <NEW_LINE> <DEDENT> def test_attributes_joined_into_string_on_output(self): <NEW_LINE> <INDENT> soup = self.soup("<a class='foo\tbar'>") <NEW_LINE> self.assertEqual(b'<a class="foo bar"></a>', soup.a.encode()) <NEW_LINE> <DEDENT> def test_get_attribute_list(self): <NEW_LINE> <INDENT> soup = self.soup("<a id='abc def'>") <NEW_LINE> self.assertEqual(['abc def'], soup.a.get_attribute_list('id')) <NEW_LINE> <DEDENT> def test_accept_charset(self): <NEW_LINE> <INDENT> soup = self.soup('<form accept-charset="ISO-8859-1 UTF-8">') <NEW_LINE> self.assertEqual(['ISO-8859-1', 'UTF-8'], soup.form['accept-charset']) <NEW_LINE> <DEDENT> def test_cdata_attribute_applying_only_to_one_tag(self): <NEW_LINE> <INDENT> data = '<a accept-charset="ISO-8859-1 UTF-8"></a>' <NEW_LINE> soup = self.soup(data) <NEW_LINE> self.assertEqual('ISO-8859-1 UTF-8', soup.a['accept-charset']) <NEW_LINE> <DEDENT> def test_string_has_immutable_name_property(self): <NEW_LINE> <INDENT> string = self.soup("s").string <NEW_LINE> self.assertEqual(None, string.name) <NEW_LINE> def t(): <NEW_LINE> <INDENT> string.name = 'foo' <NEW_LINE> <DEDENT> self.assertRaises(AttributeError, t) | Testing cdata-list attributes like 'class'.
| 62599076f548e778e596cf05 |
class Plane(object): <NEW_LINE> <INDENT> def __init__(self,normal,dvalue,color): <NEW_LINE> <INDENT> self.mNormal=normal.normalized() <NEW_LINE> self.mDistance=dvalue <NEW_LINE> self.mColor=color <NEW_LINE> <DEDENT> def rayIntersection(self,ray): <NEW_LINE> <INDENT> if self.mNormal.dot(ray.mDirection)==0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> t=(self.mDistance-(ray.mOrigin.dot(self.mNormal)))/self.mNormal.dot(ray.mDirection) <NEW_LINE> if t<0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return rayHit(t,self.mNormal,ray,self) | Creates a plane object | 625990764428ac0f6e659ea5 |
class QuadrupletDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, dataset, train=True): <NEW_LINE> <INDENT> if dataset is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.dataset = dataset <NEW_LINE> self.labels = self.dataset.labels <NEW_LINE> self.labels_set = set(self.labels) <NEW_LINE> self.label_to_indices = {label: np.where(np.array(self.labels) == label)[0] for label in self.labels_set} <NEW_LINE> self.train = train <NEW_LINE> if not self.train: <NEW_LINE> <INDENT> random_state = np.random.RandomState(29) <NEW_LINE> quadruplets = [] <NEW_LINE> for i in range(len(self.dataset)): <NEW_LINE> <INDENT> pos = random_state.choice(self.label_to_indices[self.labels[i]]) <NEW_LINE> neg1_label = np.random.choice(list(self.labels_set - set([self.labels[i]]))) <NEW_LINE> neg1 = random_state.choice(self.label_to_indices[neg1_label]) <NEW_LINE> neg2_label = np.random.choice(list(self.labels_set - set([self.labels[i], neg1_label]))) <NEW_LINE> neg2 = random_state.choice(self.label_to_indices[neg2_label]) <NEW_LINE> quadruplets.append([i, pos, neg1, neg2]) <NEW_LINE> <DEDENT> self.test_quadruplets = quadruplets <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> if self.train: <NEW_LINE> <INDENT> img1, label1 = self.dataset[index] <NEW_LINE> positive_index = index <NEW_LINE> while positive_index == index: <NEW_LINE> <INDENT> positive_index = np.random.choice(self.label_to_indices[label1]) <NEW_LINE> <DEDENT> negative1_label = np.random.choice(list(self.labels_set - set([label1]))) <NEW_LINE> negative1_index = np.random.choice(self.label_to_indices[negative1_label]) <NEW_LINE> negative2_label = np.random.choice(list(self.labels_set - set([label1, negative1_label]))) <NEW_LINE> negative2_index = np.random.choice(self.label_to_indices[negative2_label]) <NEW_LINE> img2, label2 = self.dataset[positive_index] <NEW_LINE> img3, label3 = self.dataset[negative1_index] <NEW_LINE> img4, label4 = self.dataset[negative2_index] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> img1, label1 = self.dataset[self.test_quadruplets[index][0]] <NEW_LINE> img2, label2 = self.dataset[self.test_quadruplets[index][1]] <NEW_LINE> img3, label3 = self.dataset[self.test_quadruplets[index][2]] <NEW_LINE> img4, label4 = self.dataset[self.test_quadruplets[index][3]] <NEW_LINE> <DEDENT> return (img1, img2, img3, img4), [label1, label2, label3, label4] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.dataset) | Train: For each sample (anchor) randomly chooses a positive and negative1 and negative2 samples
Test: Creates fixed quadruplets for testing | 62599076460517430c432d14 |
class FocalMechanism(QPCore.QPPublicObject): <NEW_LINE> <INDENT> addElements = QPElement.QPElementList(( QPElement.QPElement('publicID', 'publicID', 'attribute', unicode, 'basic'), QPElement.QPElement('triggeringOriginID', 'triggeringOriginID', 'element', unicode, 'basic'), QPElement.QPElement('nodalPlanes', 'nodalPlanes', 'element', NodalPlanes.NodalPlanes, 'complex'), QPElement.QPElement('principalAxes', 'principalAxes', 'element', PrincipalAxes.PrincipalAxes, 'complex'), QPElement.QPElement('azimuthalGap', 'azimuthalGap', 'element', float, 'basic'), QPElement.QPElement('stationPolarityCount', 'stationPolarityCount', 'element', int, 'basic'), QPElement.QPElement('misfit', 'misfit', 'element', float, 'basic'), QPElement.QPElement('stationDistributionRatio', 'stationDistributionRatio', 'element', float, 'basic'), QPElement.QPElement('methodID', 'methodID', 'element', unicode, 'basic'), QPElement.QPElement('evaluationMode', 'evaluationMode', 'element', unicode, 'enum'), QPElement.QPElement('evaluationStatus', 'evaluationStatus', 'element', unicode, 'enum'), QPElement.QPElement('creationInfo', 'creationInfo', 'element', CreationInfo.CreationInfo, 'complex'), QPElement.QPElement('momentTensor', 'momentTensor', 'element', MomentTensor.MomentTensor, 'multiple'), QPElement.QPElement('waveformID', 'waveformID', 'element', WaveformStreamID.WaveformStreamID, 'multiple'), QPElement.QPElement('comment', 'comment', 'element', Comment.Comment, 'multiple'), )) <NEW_LINE> def __init__(self, publicID=None, **kwargs): <NEW_LINE> <INDENT> super(FocalMechanism, self).__init__(publicID, **kwargs) <NEW_LINE> self.elements.extend(self.addElements) <NEW_LINE> if self.publicID is None: <NEW_LINE> <INDENT> self.publicID = self.createPublicID(self.__class__.__name__, **kwargs) <NEW_LINE> <DEDENT> self._initMultipleElements() | QuakePy: FocalMechanism | 625990764f6381625f19a166 |
class BaseAuditError(job_run_result.JobRunResult): <NEW_LINE> <INDENT> def __init__(self, message, model_or_kind, model_id=None): <NEW_LINE> <INDENT> if not isinstance(message, str): <NEW_LINE> <INDENT> raise TypeError('message must be a string') <NEW_LINE> <DEDENT> if not message: <NEW_LINE> <INDENT> raise ValueError('message must be a non-empty string') <NEW_LINE> <DEDENT> if model_id is None: <NEW_LINE> <INDENT> model_id = job_utils.get_model_id(model_or_kind) <NEW_LINE> model_kind = job_utils.get_model_kind(model_or_kind) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> model_kind = model_or_kind <NEW_LINE> <DEDENT> error_message = '%s in %s(id=%s): %s' % ( self.__class__.__name__, model_kind, utils.quoted(model_id), message) <NEW_LINE> super(BaseAuditError, self).__init__(stderr=error_message) | Base class for model audit errors. | 62599076e1aae11d1e7cf4ca |
class GreeterServicer(object): <NEW_LINE> <INDENT> def Hello(self, request, context): <NEW_LINE> <INDENT> pass <NEW_LINE> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | 定义服务的API
| 625990768a349b6b43687bd1 |
class TooOldServerVersion(Exception): <NEW_LINE> <INDENT> def __init__(self, method_name='', version='', message=None): <NEW_LINE> <INDENT> if message is None: <NEW_LINE> <INDENT> self.message = ( f'The "{method_name}" method works with versions older {version},' f' upgrade version ADCM.' ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> super().__init__(self.message) | Incompatible version, upgrade version ADCM. | 62599076a8370b77170f1d44 |
class AddToGroupNode(CrowdMasterAGenTreeNode): <NEW_LINE> <INDENT> bl_idname = 'AddToGroupNodeType' <NEW_LINE> bl_label = 'Add To Group' <NEW_LINE> bl_icon = 'SOUND' <NEW_LINE> groupName = StringProperty() <NEW_LINE> def init(self, context): <NEW_LINE> <INDENT> self.inputs.new('TemplateSocketType', "Template") <NEW_LINE> self.inputs[0].link_limit = 1 <NEW_LINE> self.outputs.new("TemplateSocketType", "Template") <NEW_LINE> <DEDENT> def draw_buttons(self, context, layout): <NEW_LINE> <INDENT> layout.label("Group name:") <NEW_LINE> layout.prop(self, "groupName", text="cm_") <NEW_LINE> <DEDENT> def getSettings(self): <NEW_LINE> <INDENT> return {"groupName": "cm_" + self.groupName} | The addToGroup node | 6259907667a9b606de547760 |
class ValidateComponent(Rule): <NEW_LINE> <INDENT> def __init__(self, uri, component: list): <NEW_LINE> <INDENT> passed = True <NEW_LINE> fail_reasons = [] <NEW_LINE> required = ["label", "from", "to", "title", "rules", "headers"] <NEW_LINE> for req in required: <NEW_LINE> <INDENT> if not req in component: <NEW_LINE> <INDENT> fail_reasons.append(f"The '{req}' component is missing for {uri}") <NEW_LINE> <DEDENT> <DEDENT> if fail_reasons: <NEW_LINE> <INDENT> passed = False <NEW_LINE> <DEDENT> Rule.__init__( self, "Components for AGLDWG PID URI", "Validate that the AGLDWG PID URI contains required metadata for validation checking.", "AGLDWG", passed, fail_reasons, len(required), len(fail_reasons), ) | Validate that the PID URI test contains the correct component keys.
Arguments:
Rule {[type]} -- [description] | 625990763346ee7daa33831b |
class NoRepeatNGramLogitsProcessor(LogitsProcessor): <NEW_LINE> <INDENT> def __init__(self, ngram_size: int): <NEW_LINE> <INDENT> if not isinstance(ngram_size, int) or ngram_size <= 0: <NEW_LINE> <INDENT> raise ValueError(f"`ngram_size` has to be a strictly positive integer, but is {ngram_size}") <NEW_LINE> <DEDENT> self.ngram_size = ngram_size <NEW_LINE> <DEDENT> def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor: <NEW_LINE> <INDENT> num_batch_hypotheses = scores.shape[0] <NEW_LINE> cur_len = input_ids.shape[-1] <NEW_LINE> banned_batch_tokens = _calc_banned_ngram_tokens(self.ngram_size, input_ids, num_batch_hypotheses, cur_len) <NEW_LINE> for i, banned_tokens in enumerate(banned_batch_tokens): <NEW_LINE> <INDENT> scores[i, banned_tokens] = -float("inf") <NEW_LINE> <DEDENT> return scores | :class:`transformers.LogitsProcessor` that enforces no repetition of n-grams. See `Fairseq
<https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345>`__.
Args:
ngram_size (:obj:`int`):
All ngrams of size :obj:`ngram_size` can only occur once. | 62599076627d3e7fe0e08800 |
class Centroid(Point): <NEW_LINE> <INDENT> gtype = libvect.GV_CENTROID <NEW_LINE> def __init__(self, area_id=None, **kargs): <NEW_LINE> <INDENT> super(Centroid, self).__init__(**kargs) <NEW_LINE> self.area_id = area_id <NEW_LINE> if self.id and self.c_mapinfo and self.area_id is None: <NEW_LINE> <INDENT> self.area_id = self.get_area_id() <NEW_LINE> <DEDENT> elif self.c_mapinfo and self.area_id and self.id is None: <NEW_LINE> <INDENT> self.id = self.get_centroid_id() <NEW_LINE> <DEDENT> if self.area_id is not None: <NEW_LINE> <INDENT> self.read() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Centoid(%s)" % ', '.join(['%f' % co for co in self.coords()]) <NEW_LINE> <DEDENT> def get_centroid_id(self): <NEW_LINE> <INDENT> centroid_id = libvect.Vect_get_area_centroid(self.c_mapinfo, self.area_id) <NEW_LINE> return centroid_id if centroid_id != 0 else None <NEW_LINE> <DEDENT> def get_area_id(self): <NEW_LINE> <INDENT> area_id = libvect.Vect_get_centroid_area(self.c_mapinfo, self.id) <NEW_LINE> return area_id if area_id != 0 else None | The Centroid class inherit from the Point class.
Centroid contains an attribute with the C Map_info struct, and attributes
with the id of the Area. ::
>>> centroid = Centroid(x=0, y=10)
>>> centroid
Centoid(0.000000, 10.000000)
>>> from grass.pygrass.vector import VectorTopo
>>> geo = VectorTopo('geology')
>>> geo.open(mode='r')
>>> centroid = Centroid(v_id=1, c_mapinfo=geo.c_mapinfo)
>>> centroid
Centoid(893202.874416, 297339.312795)
.. | 6259907638b623060ffaa512 |
class INT_COR_Generator(COR_Generator): <NEW_LINE> <INDENT> def execute(self, rule): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if(rule.type is not CODE_STR or rule.text_type is not CODE_INT): <NEW_LINE> <INDENT> if(self.next is not None): <NEW_LINE> <INDENT> return self.next.execute(rule) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return Random_gen.generate_int_in_str(rule.length) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print("Error INT_COR_Generator") | The cor corresponding the int generation | 625990762ae34c7f260aca5d |
class Local(object): <NEW_LINE> <INDENT> def __init__(self, target_host, local_base_path, out_path): <NEW_LINE> <INDENT> self.target_host = target_host <NEW_LINE> self.base_path = local_base_path <NEW_LINE> self.cache_path = os.path.join(self.base_path, "cache") <NEW_LINE> self.conf_path = os.path.join(self.base_path, "conf") <NEW_LINE> self.global_explorer_path = os.path.join(self.conf_path, "explorer") <NEW_LINE> self.manifest_path = os.path.join(self.conf_path, "manifest") <NEW_LINE> self.type_path = os.path.join(self.conf_path, "type") <NEW_LINE> self.lib_path = os.path.join(self.base_path, "lib") <NEW_LINE> self.out_path = out_path <NEW_LINE> self.bin_path = os.path.join(self.out_path, "bin") <NEW_LINE> self.global_explorer_out_path = os.path.join(self.out_path, "explorer") <NEW_LINE> self.object_path = os.path.join(self.out_path, "object") <NEW_LINE> self.log = logging.getLogger(self.target_host) <NEW_LINE> os.umask(0o077) <NEW_LINE> <DEDENT> def create_directories(self): <NEW_LINE> <INDENT> self.mkdir(self.out_path) <NEW_LINE> self.mkdir(self.global_explorer_out_path) <NEW_LINE> self.mkdir(self.bin_path) <NEW_LINE> <DEDENT> def rmdir(self, path): <NEW_LINE> <INDENT> self.log.debug("Local rmdir: %s", path) <NEW_LINE> shutil.rmtree(path) <NEW_LINE> <DEDENT> def mkdir(self, path): <NEW_LINE> <INDENT> self.log.debug("Local mkdir: %s", path) <NEW_LINE> os.makedirs(path, exist_ok=True) <NEW_LINE> <DEDENT> def run(self, command, env=None, return_output=False): <NEW_LINE> <INDENT> assert isinstance(command, (list, tuple)), "list or tuple argument expected, got: %s" % command <NEW_LINE> self.log.debug("Local run: %s", command) <NEW_LINE> if env is None: <NEW_LINE> <INDENT> env = os.environ.copy() <NEW_LINE> <DEDENT> env['__target_host'] = self.target_host <NEW_LINE> try: <NEW_LINE> <INDENT> if return_output: <NEW_LINE> <INDENT> return subprocess.check_output(command, env=env).decode() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subprocess.check_call(command, env=env) <NEW_LINE> <DEDENT> <DEDENT> except subprocess.CalledProcessError: <NEW_LINE> <INDENT> raise cdist.Error("Command failed: " + " ".join(command)) <NEW_LINE> <DEDENT> except OSError as error: <NEW_LINE> <INDENT> raise cdist.Error(" ".join(*args) + ": " + error.args[1]) <NEW_LINE> <DEDENT> <DEDENT> def run_script(self, script, env=None, return_output=False): <NEW_LINE> <INDENT> command = ["/bin/sh", "-e"] <NEW_LINE> command.append(script) <NEW_LINE> return self.run(command, env, return_output) <NEW_LINE> <DEDENT> def link_emulator(self, exec_path): <NEW_LINE> <INDENT> src = os.path.abspath(exec_path) <NEW_LINE> for cdist_type in core.CdistType.list_types(self.type_path): <NEW_LINE> <INDENT> dst = os.path.join(self.bin_path, cdist_type.name) <NEW_LINE> self.log.debug("Linking emulator: %s to %s", src, dst) <NEW_LINE> try: <NEW_LINE> <INDENT> os.symlink(src, dst) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> raise cdist.Error("Linking emulator from %s to %s failed: %s" % (src, dst, e.__str__())) | Execute commands locally.
All interaction with the local side should be done through this class.
Directly accessing the local side from python code is a bug. | 625990768a43f66fc4bf3b0e |
class MakeRequests(object): <NEW_LINE> <INDENT> def __init__(self, url, apikey, method='GET'): <NEW_LINE> <INDENT> self.method = method <NEW_LINE> self.url = url <NEW_LINE> self.apikey = apikey <NEW_LINE> <DEDENT> def send_(self): <NEW_LINE> <INDENT> if self.method is 'GET': <NEW_LINE> <INDENT> headers = {'apikey': self.apikey} <NEW_LINE> r = requests.get(self.url, headers=headers) <NEW_LINE> return r | Some request helper classes | 6259907632920d7e50bc79c0 |
@dataclass(frozen=True) <NEW_LINE> class SpotInstanceInputs(SageMakerComponentBaseInputs): <NEW_LINE> <INDENT> spot_instance: SageMakerComponentInput <NEW_LINE> max_wait_time: SageMakerComponentInput <NEW_LINE> max_run_time: SageMakerComponentInput <NEW_LINE> checkpoint_config: SageMakerComponentInput | Inputs to enable spot instance support. | 62599076a17c0f6771d5d869 |
class DialogIcons(IconProviderInfo): <NEW_LINE> <INDENT> name = u'VistaICO.com' <NEW_LINE> url = (u'http://www.vistaico.com') | Copyright information of the icons used in the dialogs. | 62599076be7bc26dc9252b11 |
class Plotting(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> def f(x): <NEW_LINE> <INDENT> return sin(1 * x) + 5e-1 * cos(10 * x) + 5e-3 * sin(100 * x) <NEW_LINE> <DEDENT> def u(x): <NEW_LINE> <INDENT> return np.exp(2 * np.pi * 1j * x) <NEW_LINE> <DEDENT> subinterval = Interval(-6, 10) <NEW_LINE> self.f0 = Bndfun.initfun_fixedlen(f, subinterval, 1000) <NEW_LINE> self.f1 = Bndfun.initfun_adaptive(f, subinterval) <NEW_LINE> self.f2 = Bndfun.initfun_adaptive(u, Interval(-1, 1)) <NEW_LINE> <DEDENT> @unittest.skipIf(plt is None, "matplotlib not installed") <NEW_LINE> def test_plot(self): <NEW_LINE> <INDENT> fig, ax = plt.subplots() <NEW_LINE> self.f0.plot(ax=ax, color="g", marker="o", markersize=2, linestyle="") <NEW_LINE> <DEDENT> @unittest.skipIf(plt is None, "matplotlib not installed") <NEW_LINE> def test_plot_complex(self): <NEW_LINE> <INDENT> fig, ax = plt.subplots() <NEW_LINE> for rho in np.arange(1.1, 2, 0.1): <NEW_LINE> <INDENT> (np.exp(1j * 0.25 * np.pi) * joukowsky(rho * self.f2)).plot(ax=ax) <NEW_LINE> <DEDENT> <DEDENT> @unittest.skipIf(plt is None, "matplotlib not installed") <NEW_LINE> def test_plotcoeffs(self): <NEW_LINE> <INDENT> fig, ax = plt.subplots() <NEW_LINE> self.f0.plotcoeffs(ax=ax) <NEW_LINE> self.f1.plotcoeffs(ax=ax, color="r") | Unit-tests for Bndfun plotting methods | 625990769c8ee82313040e43 |
class Alias(BaseModel): <NEW_LINE> <INDENT> book = models.ForeignKey( Book, related_name='aliases') <NEW_LINE> value = models.CharField( max_length=255, db_index=True, help_text='The value of this identifier') <NEW_LINE> scheme = models.CharField( max_length=40, help_text='The scheme of identifier') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ('book', 'scheme', 'value') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'"{title}": {scheme} / {value}'.format( title=self.book.title, scheme=self.scheme, value=self.value) | Alternate identifiers for a given book.
For example, a book can be referred to with an ISBN-10 (older, deprecated scheme), ISBN-13
(newer scheme), or any number of other aliases. In addition to the publisher-provided aliases
we create an alias 'PUB_ID' for the book id they provide. | 62599076f9cc0f698b1c5f88 |
class stock_picking(osv.osv): <NEW_LINE> <INDENT> _inherit = 'stock.picking' <NEW_LINE> PICKING_STATE = [ ('draft', 'Draft'), ('auto', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('shipped', 'Available Shipped'), ('done', 'Closed'), ('cancel', 'Cancelled'), ('import', 'Import in progress'), ('delivered', 'Delivered'), ] <NEW_LINE> def _vals_get_out_step(self, cr, uid, ids, fields, arg, context=None): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for obj in self.browse(cr, uid, ids, context=context): <NEW_LINE> <INDENT> result[obj.id] = {} <NEW_LINE> for f in fields: <NEW_LINE> <INDENT> result[obj.id].update({f:False,}) <NEW_LINE> <DEDENT> result[obj.id]['delivered_hidden'] = obj.delivered <NEW_LINE> result[obj.id]['state_hidden'] = obj.state <NEW_LINE> if obj.state == 'done' and obj.delivered: <NEW_LINE> <INDENT> result[obj.id]['state_hidden'] = 'delivered' <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> _columns = { 'delivered': fields.boolean(string='Delivered', readonly=True,), 'delivered_hidden': fields.function(_vals_get_out_step, method=True, type='boolean', string='Delivered Hidden', multi='get_vals_out_step',), 'state_hidden': fields.function(_vals_get_out_step, method=True, type='selection', selection=PICKING_STATE, string='State', multi='get_vals_out_step',), } <NEW_LINE> _defaults = { 'delivered': False, } <NEW_LINE> def copy_data(self, cr, uid, id, default=None, context=None): <NEW_LINE> <INDENT> if default is None: <NEW_LINE> <INDENT> default = {} <NEW_LINE> <DEDENT> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> default.update(delivered=False) <NEW_LINE> res = super(stock_picking, self).copy_data(cr, uid, id, default=default, context=context) <NEW_LINE> return res <NEW_LINE> <DEDENT> def set_delivered(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> self.write(cr, uid, ids, {'delivered': True,}, context=context) <NEW_LINE> return True | add a check boolean for confirmation of delivery | 62599076a8370b77170f1d46 |
class UserTag(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=10, verbose_name=u'Тег', unique=True) <NEW_LINE> slug = models.CharField(max_length=20, verbose_name=u'Slug для тега', unique=True) <NEW_LINE> author = models.ForeignKey(User, verbose_name=u'Автор тега', related_name='author_tags') <NEW_LINE> target = models.ForeignKey(User, verbose_name=u'Кому тег был проставлен', related_name='tags', null=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = u'Пользовательский тег' <NEW_LINE> verbose_name_plural = u'Пользовательские теги' | Модель для пользовательских тегов. Один пользователь другому может их проставить | 625990761b99ca40022901f2 |
class IMultiSelect2Widget(Interface): <NEW_LINE> <INDENT> pass | Marker interface for multi select2 widget | 6259907699fddb7c1ca63a92 |
class FakeRunner: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.exelines=[] <NEW_LINE> self.np=0 <NEW_LINE> self.nn=0 <NEW_LINE> self.jobname='FAKERUNNER' <NEW_LINE> self.queue='FAKEQUEUE' <NEW_LINE> self.walltime='0:00:00' <NEW_LINE> self.prefix=[] <NEW_LINE> self.postfix=[] <NEW_LINE> self.queueid=[] <NEW_LINE> <DEDENT> def check_status(self,qstat=None): <NEW_LINE> <INDENT> return 'unknown' <NEW_LINE> <DEDENT> def add_command(self,cmdstr): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add_task(self,exestr): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def script(self,scriptfile): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def submit(self,jobname=None): <NEW_LINE> <INDENT> return '' | Object that can be used as a runner, but will ignore run commands.
Useful for debugging. | 625990765166f23b2e244d50 |
class State: <NEW_LINE> <INDENT> def handle(self, event): <NEW_LINE> <INDENT> if event.type == QUIT: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> if event.type == KEYDOWN and event.key == K_ESCAPE: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> <DEDENT> def firstDisplay(self, screen): <NEW_LINE> <INDENT> screen.fill(config.background_color) <NEW_LINE> pygame.display.flip() <NEW_LINE> <DEDENT> def display(self, screen): <NEW_LINE> <INDENT> pass | 状态 | 6259907655399d3f05627e8d |
class DecimalPrinter: <NEW_LINE> <INDENT> def __init__(self, nbits, name, val): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.val = val <NEW_LINE> self.nbits = nbits <NEW_LINE> <DEDENT> def to_string(self): <NEW_LINE> <INDENT> dec = Decimal.from_bits(self.nbits, self.val) <NEW_LINE> return f"{self.name}({int(dec)})" | Pretty-printer for Arrow decimal values. | 625990763d592f4c4edbc81a |
class MetricMetadata(object): <NEW_LINE> <INDENT> __slots__ = ( "aggregator", "retention", "carbon_xfilesfactor", ) <NEW_LINE> _DEFAULT_AGGREGATOR = Aggregator.average <NEW_LINE> _DEFAULT_RETENTION = Retention.from_string("86400*1s:10080*60s") <NEW_LINE> _DEFAULT_XFILESFACTOR = 0.5 <NEW_LINE> def __init__(self, aggregator=None, retention=None, carbon_xfilesfactor=None): <NEW_LINE> <INDENT> self.aggregator = aggregator or self._DEFAULT_AGGREGATOR <NEW_LINE> assert isinstance(self.aggregator, Aggregator), self.aggregator <NEW_LINE> self.retention = retention or self._DEFAULT_RETENTION <NEW_LINE> if carbon_xfilesfactor is None: <NEW_LINE> <INDENT> self.carbon_xfilesfactor = self._DEFAULT_XFILESFACTOR <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.carbon_xfilesfactor = carbon_xfilesfactor <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> if name not in self.__slots__: <NEW_LINE> <INDENT> raise AttributeError("can't set attribute") <NEW_LINE> <DEDENT> super(MetricMetadata, self).__setattr__(name, value) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, MetricMetadata): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.as_string_dict() == other.as_string_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) <NEW_LINE> <DEDENT> def as_json(self): <NEW_LINE> <INDENT> return json.dumps(self.as_string_dict()) <NEW_LINE> <DEDENT> def as_string_dict(self): <NEW_LINE> <INDENT> return { "aggregator": self.aggregator.name, "retention": self.retention.as_string, "carbon_xfilesfactor": "%f" % self.carbon_xfilesfactor, } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_json(cls, s): <NEW_LINE> <INDENT> return cls.from_string_dict(json.loads(s)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string_dict(cls, d): <NEW_LINE> <INDENT> if d is None: <NEW_LINE> <INDENT> return cls() <NEW_LINE> <DEDENT> return cls( aggregator=Aggregator.from_config_name(d.get("aggregator")), retention=Retention.from_string(d.get("retention")), carbon_xfilesfactor=float(d.get("carbon_xfilesfactor")), ) | Represents all information about a metric except its name.
Not meant to be mutated. | 625990762c8b7c6e89bd5163 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.