code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class RouterStatusEntryV3(RouterStatusEntry): <NEW_LINE> <INDENT> def __init__(self, content, validate = True, document = None): <NEW_LINE> <INDENT> self.or_addresses = [] <NEW_LINE> self.digest = None <NEW_LINE> self.bandwidth = None <NEW_LINE> self.measured = None <NEW_LINE> self.is_unmeasured = False <NEW_LINE> self.unrecognized_bandwidth_entries = [] <NEW_LINE> self.exit_policy = None <NEW_LINE> self.microdescriptor_hashes = [] <NEW_LINE> super(RouterStatusEntryV3, self).__init__(content, validate, document) <NEW_LINE> <DEDENT> def _parse(self, entries, validate): <NEW_LINE> <INDENT> for keyword, values in list(entries.items()): <NEW_LINE> <INDENT> value, _, _ = values[0] <NEW_LINE> if keyword == 'r': <NEW_LINE> <INDENT> _parse_r_line(self, value, validate, True) <NEW_LINE> del entries['r'] <NEW_LINE> <DEDENT> elif keyword == 'a': <NEW_LINE> <INDENT> for entry, _, _ in values: <NEW_LINE> <INDENT> _parse_a_line(self, entry, validate) <NEW_LINE> <DEDENT> del entries['a'] <NEW_LINE> <DEDENT> elif keyword == 'w': <NEW_LINE> <INDENT> _parse_w_line(self, value, validate) <NEW_LINE> del entries['w'] <NEW_LINE> <DEDENT> elif keyword == 'p': <NEW_LINE> <INDENT> _parse_p_line(self, value, validate) <NEW_LINE> del entries['p'] <NEW_LINE> <DEDENT> elif keyword == 'm': <NEW_LINE> <INDENT> for entry, _, _ in values: <NEW_LINE> <INDENT> _parse_m_line(self, entry, validate) <NEW_LINE> <DEDENT> del entries['m'] <NEW_LINE> <DEDENT> <DEDENT> RouterStatusEntry._parse(self, entries, validate) <NEW_LINE> <DEDENT> def _name(self, is_plural = False): <NEW_LINE> <INDENT> if is_plural: <NEW_LINE> <INDENT> return 'Router status entries (v3)' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Router status entry (v3)' <NEW_LINE> <DEDENT> <DEDENT> def _required_fields(self): <NEW_LINE> <INDENT> return ('r', 's') <NEW_LINE> <DEDENT> def _single_fields(self): <NEW_LINE> <INDENT> return ('r', 's', 'v', 'w', 'p') <NEW_LINE> <DEDENT> def _compare(self, other, method): <NEW_LINE> <INDENT> if not isinstance(other, RouterStatusEntryV3): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return method(str(self).strip(), str(other).strip()) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._compare(other, lambda s, o: s == o) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self._compare(other, lambda s, o: s < o) <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return self._compare(other, lambda s, o: s <= o)
Information about an individual router stored within a version 3 network status document. :var list or_addresses: **\*** relay's OR addresses, this is a tuple listing of the form (address (**str**), port (**int**), is_ipv6 (**bool**)) :var str digest: **\*** router's upper-case hex digest :var int bandwidth: bandwidth claimed by the relay (in kb/s) :var int measured: bandwidth measured to be available by the relay, this is a unit-less heuristic generated by the Bandwidth authoritites to weight relay selection :var bool is_unmeasured: bandwidth measurement isn't based on three or more measurements :var list unrecognized_bandwidth_entries: **\*** bandwidth weighting information that isn't yet recognized :var stem.exit_policy.MicroExitPolicy exit_policy: router's exit policy :var list microdescriptor_hashes: **\*** tuples of two values, the list of consensus methods for generating a set of digests and the 'algorithm => digest' mappings **\*** attribute is either required when we're parsed with validation or has a default value, others are left as **None** if undefined
62598fb68a349b6b43686343
class FunctionOptionsDialogTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_buildForm(self): <NEW_LINE> <INDENT> myFunctionId = 'I T B Fatality Function Configurable' <NEW_LINE> myFunctionList = get_plugins(myFunctionId) <NEW_LINE> assert len(myFunctionList) == 1 <NEW_LINE> assert myFunctionList[0].keys()[0] == myFunctionId <NEW_LINE> myFunction = myFunctionList[0] <NEW_LINE> myDialog = FunctionOptionsDialog(None) <NEW_LINE> myParameters = {'foo': 'bar'} <NEW_LINE> myDialog.buildForm(myFunction, myParameters) <NEW_LINE> myWidget = myDialog.findChild(QLineEdit, 'fooLineEdit') <NEW_LINE> assert myWidget is not None <NEW_LINE> assert myWidget.text() == 'bar'
Test the InaSAFE GUI for Configurable Impact Functions
62598fb644b2445a339b69f7
class DupCheckLoader(yaml.Loader): <NEW_LINE> <INDENT> pass
Local class to prevent pollution of global yaml.Loader.
62598fb69c8ee823130401f7
class Model(Validator): <NEW_LINE> <INDENT> def __init__(self, model): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not isinstance(value, self.model): <NEW_LINE> <INDENT> raise InvalidModelFieldError("should be an instance of '{}'".format(self.model.__name__)) <NEW_LINE> <DEDENT> value.validate()
Validate the field is a model
62598fb671ff763f4b5e787e
class TumorExtent(Outcome): <NEW_LINE> <INDENT> length = fields.IntField() <NEW_LINE> width = fields.IntField() <NEW_LINE> depth = fields.IntField()
The tumor 3D measurements in millimeters.
62598fb6627d3e7fe0e06fb8
class Hash: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def hash(block): <NEW_LINE> <INDENT> block_string = json.dumps(block, sort_keys=True).encode() <NEW_LINE> return hashlib.sha256(block_string).hexdigest()
Hashing Operations.
62598fb6236d856c2adc94c3
class ProxyDialog(ProxyWindow): <NEW_LINE> <INDENT> declaration = ForwardTyped(lambda: Dialog) <NEW_LINE> def exec_(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def done(self, result): <NEW_LINE> <INDENT> raise NotImplementedError
The abstract definition of a proxy Dialog object.
62598fb655399d3f0562661c
@compat.python_2_unicode_compatible <NEW_LINE> class BaseNgramModel(object): <NEW_LINE> <INDENT> def __init__(self, ngram_counter): <NEW_LINE> <INDENT> self.ngram_counter = ngram_counter <NEW_LINE> self.ngrams = ngram_counter.ngrams[ngram_counter.order] <NEW_LINE> self._ngrams = ngram_counter.ngrams <NEW_LINE> self._order = ngram_counter.order <NEW_LINE> self._check_against_vocab = self.ngram_counter.check_against_vocab <NEW_LINE> <DEDENT> def check_context(self, context): <NEW_LINE> <INDENT> if len(context) >= self._order: <NEW_LINE> <INDENT> raise ValueError("Context is too long for this ngram order: {0}".format(context)) <NEW_LINE> <DEDENT> return tuple(context) <NEW_LINE> <DEDENT> def score(self, word, context): <NEW_LINE> <INDENT> return 0.5 <NEW_LINE> <DEDENT> def logscore(self, word, context): <NEW_LINE> <INDENT> score = self.score(word, context) <NEW_LINE> if score == 0.0: <NEW_LINE> <INDENT> return NEG_INF <NEW_LINE> <DEDENT> return log(score, 2) <NEW_LINE> <DEDENT> def entropy(self, text, perItem=True): <NEW_LINE> <INDENT> normed_text = (self._check_against_vocab(word) for word in text) <NEW_LINE> H = 0.0 <NEW_LINE> processed_ngrams = 0 <NEW_LINE> for ngram in self.ngram_counter.to_ngrams(normed_text): <NEW_LINE> <INDENT> context, word = tuple(ngram[:-1]), ngram[-1] <NEW_LINE> H += self.logscore(word, context) <NEW_LINE> processed_ngrams += 1 <NEW_LINE> <DEDENT> if perItem: <NEW_LINE> <INDENT> return - (H / processed_ngrams) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -H <NEW_LINE> <DEDENT> <DEDENT> def perplexity(self, text): <NEW_LINE> <INDENT> return pow(2.0, self.entropy(text))
An example of how to consume NgramCounter to create a language model. This class isn't intended to be used directly, folks should inherit from it when writing their own ngram models.
62598fb67cff6e4e811b5b28
class BadValue(ErrorResponse): <NEW_LINE> <INDENT> DEFAULT_MESSAGE = "Bad value" <NEW_LINE> def __init__(self, offending_oid, message=""): <NEW_LINE> <INDENT> super().__init__(3, offending_oid, message)
This error is returned whenever a variable is set using an incompatible type.
62598fb6a05bb46b3848a973
class PriorBox(object): <NEW_LINE> <INDENT> def __init__(self, input_size, feature_maps, cfg): <NEW_LINE> <INDENT> super(PriorBox, self).__init__() <NEW_LINE> self.imh = input_size[0] <NEW_LINE> self.imw = input_size[1] <NEW_LINE> self.variance = cfg.VARIANCE or [0.1] <NEW_LINE> self.num_priors = len(cfg.ASPECT_RATIOS) <NEW_LINE> self.min_sizes = cfg.MIN_SIZES <NEW_LINE> self.max_sizes = cfg.MAX_SIZES <NEW_LINE> self.steps = cfg.STEPS <NEW_LINE> self.aspect_ratios = cfg.ASPECT_RATIOS <NEW_LINE> self.clip = cfg.CLIP <NEW_LINE> for v in self.variance: <NEW_LINE> <INDENT> if v <= 0: <NEW_LINE> <INDENT> raise ValueError('Variances must be greater than 0') <NEW_LINE> <DEDENT> <DEDENT> self.feature_maps = feature_maps <NEW_LINE> <DEDENT> def forward(self): <NEW_LINE> <INDENT> mean = [] <NEW_LINE> for k in range(len(self.feature_maps)): <NEW_LINE> <INDENT> feath = self.feature_maps[k][0] <NEW_LINE> featw = self.feature_maps[k][1] <NEW_LINE> for i, j in product(range(feath), range(featw)): <NEW_LINE> <INDENT> f_kw = self.imw / self.steps[k] <NEW_LINE> f_kh = self.imh / self.steps[k] <NEW_LINE> cx = (j + 0.5) / f_kw <NEW_LINE> cy = (i + 0.5) / f_kh <NEW_LINE> s_kw = self.min_sizes[k] / self.imw <NEW_LINE> s_kh = self.min_sizes[k] / self.imh <NEW_LINE> mean += [cx, cy, s_kw, s_kh] <NEW_LINE> s_k_primew = sqrt(s_kw * (self.max_sizes[k] / self.imw)) <NEW_LINE> s_k_primeh = sqrt(s_kh * (self.max_sizes[k] / self.imh)) <NEW_LINE> mean += [cx, cy, s_k_primew, s_k_primeh] <NEW_LINE> for ar in self.aspect_ratios[k]: <NEW_LINE> <INDENT> mean += [cx, cy, s_kw * sqrt(ar), s_kh / sqrt(ar)] <NEW_LINE> mean += [cx, cy, s_kw / sqrt(ar), s_kh * sqrt(ar)] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> output = torch.Tensor(mean).view(-1, 4) <NEW_LINE> if self.clip: <NEW_LINE> <INDENT> output.clamp_(max=1, min=0) <NEW_LINE> <DEDENT> return output
docstring for PriorBox
62598fb656b00c62f0fb29c1
class AddEditTaskForm(ModelForm): <NEW_LINE> <INDENT> def __init__(self, user, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> task_list = kwargs.get("initial").get("task_list") <NEW_LINE> members = task_list.group.user_set.all() <NEW_LINE> self.fields["assigned_to"].queryset = members <NEW_LINE> self.fields["assigned_to"].label_from_instance = lambda obj: "%s (%s)" % ( obj.get_full_name(), obj.username, ) <NEW_LINE> self.fields["assigned_to"].widget.attrs = { "id": "id_assigned_to", "class": "custom-select mb-3", "name": "assigned_to", } <NEW_LINE> self.fields["task_list"].value = kwargs["initial"]["task_list"].id <NEW_LINE> <DEDENT> due_date = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}), required=False) <NEW_LINE> title = forms.CharField(widget=forms.widgets.TextInput()) <NEW_LINE> note = forms.CharField(widget=forms.Textarea(), required=False) <NEW_LINE> completed = forms.BooleanField(required=False) <NEW_LINE> def clean_created_by(self): <NEW_LINE> <INDENT> return self.instance.created_by <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Task <NEW_LINE> exclude = []
The picklist showing the users to which a new task can be assigned must find other members of the group this TaskList is attached to.
62598fb6a17c0f6771d5c33e
class getRows_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT,(TRowResult, TRowResult.thrift_spec)), None, ), (1, TType.STRUCT, 'io', (IOError, IOError.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, io=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.io = io <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.success = [] <NEW_LINE> (_etype198, _size195) = iprot.readListBegin() <NEW_LINE> for _i199 in xrange(_size195): <NEW_LINE> <INDENT> _elem200 = TRowResult() <NEW_LINE> _elem200.read(iprot) <NEW_LINE> self.success.append(_elem200) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.io = IOError() <NEW_LINE> self.io.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getRows_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.LIST, 0) <NEW_LINE> oprot.writeListBegin(TType.STRUCT, len(self.success)) <NEW_LINE> for iter201 in self.success: <NEW_LINE> <INDENT> iter201.write(oprot) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.io is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('io', TType.STRUCT, 1) <NEW_LINE> self.io.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success - io
62598fb67b180e01f3e490d5
class ListenerUpdateEnd(ListenerNotificationBase): <NEW_LINE> <INDENT> event_types = ['listener.update.end'] <NEW_LINE> def process_notification(self, message): <NEW_LINE> <INDENT> LOG.warn('Do action for event: %s, resource_id: %s', message['event_type'], message['payload']['listener']['id']) <NEW_LINE> quantity = int(message['payload']['listener']['connection_limit']) / 1000 <NEW_LINE> admin_state_up = message['payload']['listener']['admin_state_up'] <NEW_LINE> resource_id = message['payload']['listener']['id'] <NEW_LINE> order = self.get_order_by_resource_id(resource_id) <NEW_LINE> if order.get('unit') in ['month', 'year']: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> subs = self.get_subscriptions(order_id=order['order_id'], type=const.STATE_RUNNING) <NEW_LINE> if not subs: <NEW_LINE> <INDENT> LOG.warn("The order %s has no subscriptions" % order['order_id']) <NEW_LINE> return <NEW_LINE> <DEDENT> action_time = message['timestamp'] <NEW_LINE> if subs[0]['quantity'] != quantity: <NEW_LINE> <INDENT> remarks = 'Listener Has Been Resized' <NEW_LINE> self.resource_resized(order['order_id'], action_time, quantity, remarks) <NEW_LINE> <DEDENT> status = const.STATE_RUNNING if admin_state_up else const.STATE_STOPPED <NEW_LINE> if status == order['status']: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if status == const.STATE_STOPPED: <NEW_LINE> <INDENT> remarks = 'Listener Has Been Stopped.' <NEW_LINE> self.resource_stopped(order['order_id'], action_time, remarks) <NEW_LINE> <DEDENT> elif status == const.STATE_RUNNING: <NEW_LINE> <INDENT> remarks = 'Listener Has Been Started.' <NEW_LINE> self.resource_started(order['order_id'], action_time, remarks)
Handle the events that listener's connection_limit or admin_state_up be changed
62598fb68a43f66fc4bf2282
class ContextNotFound(EnvironmentError): <NEW_LINE> <INDENT> pass
Raised when bigip or Infra does not find a context for a given Object
62598fb6fff4ab517ebcd8ef
class Views(db.Model): <NEW_LINE> <INDENT> post_id = db.Column(db.Integer, db.ForeignKey('post.id'), primary_key=True) <NEW_LINE> view_total = db.Column(db.Integer) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return f"Total views is('{self.view_total}')"
Post Views model
62598fb699cbb53fe6830fdf
class Webapp2Session(interfaces.BaseSession): <NEW_LINE> <INDENT> def __init__(self, handler, session=None, secret=None, cookie_name='webapp2authomatic', backend='memcache', config=None): <NEW_LINE> <INDENT> self.handler = handler <NEW_LINE> if session is None: <NEW_LINE> <INDENT> if not secret: <NEW_LINE> <INDENT> raise GAEError('Either session or secret must be specified!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cfg = config or dict(secret_key=secret, cookie_name=cookie_name) <NEW_LINE> session_store = sessions.SessionStore(handler.request, cfg) <NEW_LINE> self.session_dict = session_store.get_session(backend=backend) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.session_dict = session <NEW_LINE> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> return self.session_dict.container.save_session(self.handler.response) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> return self.session_dict.__setitem__(key, value) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.session_dict.__getitem__(key) <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> return self.session_dict.__delitem__(key) <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> return self.session_dict.get(key)
A simple wrapper for |webapp2|_ sessions. If you provide a session it wraps it and adds the :meth:`.save` method. If you don't provide a session it creates a new one but you must provide the :data:`.secret`. For more about |webapp2| sessions see: http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html.
62598fb64a966d76dd5eefe0
class RSS(object): <NEW_LINE> <INDENT> def __init__(self, url='', referrer='http://yandex.ru'): <NEW_LINE> <INDENT> self.rssurl = url <NEW_LINE> self.rss = fp.parse(self.rssurl, referrer=referrer) <NEW_LINE> try: <NEW_LINE> <INDENT> self.status = self.rss.status <NEW_LINE> if self.status != 200: <NEW_LINE> <INDENT> logging.debug(self.status) <NEW_LINE> raise Exception(self.status) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.status = None <NEW_LINE> <DEDENT> <DEDENT> def count(self): <NEW_LINE> <INDENT> return len(self.rss.entries) <NEW_LINE> <DEDENT> def gettitles(self): <NEW_LINE> <INDENT> titles = list() <NEW_LINE> for entry in self.rss.entries: <NEW_LINE> <INDENT> titles.append(entry['title']) <NEW_LINE> <DEDENT> return titles <NEW_LINE> <DEDENT> def getitems(self): <NEW_LINE> <INDENT> items = dict() <NEW_LINE> for entry in self.rss.entries: <NEW_LINE> <INDENT> items[entry['title']] = entry['link'] <NEW_LINE> <DEDENT> return items
RSS related stuff is here
62598fb6ff9c53063f51a757
class LazyString(object): <NEW_LINE> <INDENT> __slots__ = ('_func', '_args') <NEW_LINE> def __init__(self, func, *args): <NEW_LINE> <INDENT> self._func = func <NEW_LINE> self._args = args <NEW_LINE> <DEDENT> value = property(lambda x: x._func(*x._args)) <NEW_LINE> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self.value <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return bool(self.value) <NEW_LINE> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> return dir(unicode) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.value) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.value) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return unicode(self.value) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return self.value + other <NEW_LINE> <DEDENT> def __radd__(self, other): <NEW_LINE> <INDENT> return other + self.value <NEW_LINE> <DEDENT> def __mod__(self, other): <NEW_LINE> <INDENT> return self.value % other <NEW_LINE> <DEDENT> def __rmod__(self, other): <NEW_LINE> <INDENT> return other % self.value <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> return self.value * other <NEW_LINE> <DEDENT> def __rmul__(self, other): <NEW_LINE> <INDENT> return other * self.value <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.value < other <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return self.value <= other <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.value == other <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return self.value != other <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return self.value > other <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> return self.value >= other <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> if name == '__members__': <NEW_LINE> <INDENT> return self.__dir__() <NEW_LINE> <DEDENT> return getattr(self.value, name) <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> return self._func, self._args <NEW_LINE> <DEDENT> def __setstate__(self, tup): <NEW_LINE> <INDENT> self._func, self._args = tup <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.value[key] <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return 'l' + repr(unicode(self.value)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return '<%s broken>' % self.__class__.__name__
Class for strings created by a function call. The proxy implementation attempts to be as complete as possible, so that the lazy objects should mostly work as expected, for example for sorting.
62598fb671ff763f4b5e7880
class MaxRetryLimit(MyError): <NEW_LINE> <INDENT> pass
If re-try count for requests reached
62598fb656ac1b37e63022f5
class DeleteLiveCallbackTemplateRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TemplateId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TemplateId = params.get("TemplateId")
DeleteLiveCallbackTemplate请求参数结构体
62598fb6bd1bec0571e15147
class Teacher: <NEW_LINE> <INDENT> def __init__(self, tname, tclass): <NEW_LINE> <INDENT> self._tname = tname <NEW_LINE> self._tclass = tclass <NEW_LINE> if len(teacher_list)==0: <NEW_LINE> <INDENT> self._tid = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._tid = teacher_list[-1].get_tid()+1 <NEW_LINE> <DEDENT> teacher_list.append(self) <NEW_LINE> <DEDENT> def get_tname(self): <NEW_LINE> <INDENT> return self._tname <NEW_LINE> <DEDENT> def get_tclass(self): <NEW_LINE> <INDENT> return self._tclass <NEW_LINE> <DEDENT> def get_tid(self): <NEW_LINE> <INDENT> return self._tid <NEW_LINE> <DEDENT> def update(self, tname, tclass): <NEW_LINE> <INDENT> self._tname = tname <NEW_LINE> self._tclass = tclass
Teachers have a name and a class they are attached to.
62598fb6851cf427c66b83c0
class KuntzmannButcher6: <NEW_LINE> <INDENT> A = array([[5./36, 2./9 - sqrt(15.)/15., 5./36 - sqrt(15.)/30], [5./36 + sqrt(15.)/24, 2./9 , 5./36 - sqrt(15.)/24], [5./36 + sqrt(15.)/30, 2./9 + sqrt(15.)/15 , 5./36]]) <NEW_LINE> b = array([ 5./18, 4./9., 5./18]) <NEW_LINE> c = array([1./2 - sqrt(15.)/10., 1./2, 1./2 + sqrt(15.)/10]) <NEW_LINE> order = 6
IRK, Gauss-Legendre based.
62598fb6956e5f7376df5702
class DummyDetectorRandomClass(DetectorBase): <NEW_LINE> <INDENT> DETECTOR_STATUS_IDLE, DETECTOR_STATUS_BUSY, DETECTOR_STATUS_PAUSED, DETECTOR_STATUS_STANDBY, DETECTOR_STATUS_FAULT, DETECTOR_STATUS_MONITORING = range(6); <NEW_LINE> def __init__(self, name, numberOfChannels=32): <NEW_LINE> <INDENT> self.setName(name); <NEW_LINE> self.setLevel(7); <NEW_LINE> self.exposureTime = 0.1; <NEW_LINE> self.numberOfChannels=numberOfChannels; <NEW_LINE> self.currentPosition = 0; <NEW_LINE> self.scannableSetup(); <NEW_LINE> <DEDENT> def scannableSetup(self): <NEW_LINE> <INDENT> self.setInputNames([]); <NEW_LINE> extraNames = ['ExposureTime']; <NEW_LINE> outputFormat = ['%f']; <NEW_LINE> for c in range(self.numberOfChannels): <NEW_LINE> <INDENT> extraNames.append('ch_%s' %c ) <NEW_LINE> outputFormat.append( '%f' ) <NEW_LINE> <DEDENT> self.setExtraNames(extraNames); <NEW_LINE> self.setOutputFormat(outputFormat); <NEW_LINE> <DEDENT> def getCollectionTime(self): <NEW_LINE> <INDENT> return self.exposureTime; <NEW_LINE> <DEDENT> def setCollectionTime(self, newExpos): <NEW_LINE> <INDENT> self.exposureTime = newExpos; <NEW_LINE> <DEDENT> def collectData(self): <NEW_LINE> <INDENT> time.sleep(self.exposureTime); <NEW_LINE> self.currentPosition += 1; <NEW_LINE> return; <NEW_LINE> <DEDENT> def getStatus(self): <NEW_LINE> <INDENT> return Detector.IDLE; <NEW_LINE> <DEDENT> def readout(self): <NEW_LINE> <INDENT> result = [self.exposureTime]; <NEW_LINE> for c in range(self.numberOfChannels): <NEW_LINE> <INDENT> counts = random.randint(1, 10000); <NEW_LINE> result.append( counts ); <NEW_LINE> <DEDENT> return result; <NEW_LINE> <DEDENT> def createsOwnFiles(self): <NEW_LINE> <INDENT> return False;
A dummy detector that can returns many channels of Gaussian output with random parameters
62598fb60fa83653e46f4feb
class Projectile(object): <NEW_LINE> <INDENT> def __init__(self, mass): <NEW_LINE> <INDENT> self._mass = mass <NEW_LINE> self.pos = np.array([0.0, 0.0]) <NEW_LINE> self.speed = np.array([0.0, 0.0]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def mass(self): <NEW_LINE> <INDENT> return self._mass <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return Projectile(self.mass) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "({}, {})".format(self.pos, self.speed)
Defines a Projectile with mass m. Speed and position are set by default at zero 2-dim.
62598fb656ac1b37e63022f6
class AbstractConsumer(object): <NEW_LINE> <INDENT> def _unhandled_section(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _unhandled(self, data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> if attr[:6] == 'start_' or attr[:4] == 'end_': <NEW_LINE> <INDENT> method = self._unhandled_section <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> method = self._unhandled <NEW_LINE> <DEDENT> return method
Base class for other Consumers. Derive Consumers from this class and implement appropriate methods for each event that you want to receive.
62598fb6a05bb46b3848a975
class CallTreeNode(object): <NEW_LINE> <INDENT> def __init__(self, percentage, function_name): <NEW_LINE> <INDENT> self.percentage = percentage <NEW_LINE> self.call_stack = [function_name] <NEW_LINE> self.children = [] <NEW_LINE> <DEDENT> def add_call(self, function_name): <NEW_LINE> <INDENT> self.call_stack.append(function_name) <NEW_LINE> <DEDENT> def add_child(self, node): <NEW_LINE> <INDENT> self.children.append(node) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> strs = self.dump() <NEW_LINE> return '\n'.join(strs) <NEW_LINE> <DEDENT> def dump(self): <NEW_LINE> <INDENT> strs = [] <NEW_LINE> strs.append('CallTreeNode percentage = %.2f' % self.percentage) <NEW_LINE> for function_name in self.call_stack: <NEW_LINE> <INDENT> strs.append(' %s' % function_name) <NEW_LINE> <DEDENT> for child in self.children: <NEW_LINE> <INDENT> child_strs = child.dump() <NEW_LINE> strs.extend([' ' + x for x in child_strs]) <NEW_LINE> <DEDENT> return strs
Representing a node in call-graph.
62598fb67b180e01f3e490d6
class ModelCommand(Command): <NEW_LINE> <INDENT> scaffold_name = "Model" <NEW_LINE> template = '/masonite/snippets/scaffold/model' <NEW_LINE> base_directory = 'app/' <NEW_LINE> def handle(self): <NEW_LINE> <INDENT> class_name = self.argument('name') <NEW_LINE> view = View(App()) <NEW_LINE> class_directory = '{}{}.py'.format(self.base_directory, class_name) <NEW_LINE> if not make_directory(class_directory): <NEW_LINE> <INDENT> return self.error('{0} Already Exists!'.format(self.scaffold_name)) <NEW_LINE> <DEDENT> with open(class_directory, 'w+') as f: <NEW_LINE> <INDENT> if view.exists(self.template): <NEW_LINE> <INDENT> f.write( view.render(self.template, { 'class': class_name.split('/')[-1]}).rendered_template ) <NEW_LINE> self.info('{} Created Successfully!'.format(self.scaffold_name)) <NEW_LINE> <DEDENT> <DEDENT> if self.option('migration'): <NEW_LINE> <INDENT> model_name = class_name.lower() + 's' <NEW_LINE> self.call('migration', [ ('name', 'create_{}_table'.format(model_name)), ('-c', model_name) ]) <NEW_LINE> <DEDENT> if self.option('seed'): <NEW_LINE> <INDENT> seed_file = model_name <NEW_LINE> seed_file = self.option('seed') <NEW_LINE> self.call('seed', [ ('table', seed_file) ])
Creates a model. model {name : Name of the model} {--m|migration : Create a migration for specified model} {--s|seed=? : Create a database seed}
62598fb6f548e778e596b6ae
class GroupRoom(BaseRoom): <NEW_LINE> <INDENT> users = models.ManyToManyField(get_user_model(), related_name='group_rooms', through='GroupChatUser', through_fields=('room', 'user','admin','silenced', 'active')) <NEW_LINE> expiry = models.DateTimeField(default=None, blank=True, null=True) <NEW_LINE> private = models.BooleanField(default=False) <NEW_LINE> location = PointField(srid=4326, null=True, blank=True) <NEW_LINE> through_objects = GroupRoomQuerySet().as_manager() <NEW_LINE> def channel_name(self, room_id=None): <NEW_LINE> <INDENT> return room_id if room_id is not None else self.id <NEW_LINE> <DEDENT> def add_join_request(self, requester=None, requested=None, admin=False, message=None): <NEW_LINE> <INDENT> jr = JoinRequest.objects.get_or_create(requester_id=requester, requested_id=requested, admin=admin, message=message, content_object=self) <NEW_LINE> return jr <NEW_LINE> <DEDENT> @property <NEW_LINE> def lat_long(self): <NEW_LINE> <INDENT> return normalize_lat_long(self.location) <NEW_LINE> <DEDENT> @property <NEW_LINE> def expired(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def add_admin_user(self, user=None, users=None): <NEW_LINE> <INDENT> if users is not None and len(users) > 0: <NEW_LINE> <INDENT> return self.users.through.objects.filter(id__in=users).update(admin=True) <NEW_LINE> <DEDENT> if user is not None: <NEW_LINE> <INDENT> instance, created = self.users.through.objects.get_or_create(user_id=user, admin=True, room=self) <NEW_LINE> return instance <NEW_LINE> <DEDENT> raise ValidationError(_('Either a single user id or array of user ids must be sent as parameters'))
GroupRoom extends Room REASONING FOR DUPLICATION: 1) Helps to distribute the data and decouple each chat application
62598fb65fc7496912d48300
class TaggitSelect2(TagSelect2): <NEW_LINE> <INDENT> def value_from_datadict(self, data, files, name): <NEW_LINE> <INDENT> value = super(TaggitSelect2, self).value_from_datadict(data, files, name) <NEW_LINE> if value and ',' not in value: <NEW_LINE> <INDENT> value = '%s,' % value <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def option_value(self, value): <NEW_LINE> <INDENT> return value.tag.name if hasattr(value, 'tag') else value <NEW_LINE> <DEDENT> def render_options(self, *args): <NEW_LINE> <INDENT> selected_choices_arg = 1 if VERSION < (1, 10) else 0 <NEW_LINE> selected_choices = args[selected_choices_arg] <NEW_LINE> if isinstance(selected_choices, six.text_type): <NEW_LINE> <INDENT> choices = [c.strip() for c in selected_choices.split(',')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> choices = [c.tag.name for c in selected_choices if c] <NEW_LINE> <DEDENT> options = [ '<option value="%s" selected="selected">%s</option>' % ( c, c) for c in choices ] <NEW_LINE> return '\n'.join(options)
Select2 tag widget for taggit's TagField.
62598fb62c8b7c6e89bd38ce
class _PriorityQueue(list): <NEW_LINE> <INDENT> def __init__(self, items): <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> self.enqueue(item) <NEW_LINE> <DEDENT> <DEDENT> def enqueue(self, item): <NEW_LINE> <INDENT> heapq.heappush(self, (item.priority(), item)) <NEW_LINE> <DEDENT> def deque(self): <NEW_LINE> <INDENT> return heapq.heappop(self)[1]
PriorityQueue adds and removes items based on the provided priority
62598fb6e1aae11d1e7ce8a9
class WhereEnumerable(Enumerable): <NEW_LINE> <INDENT> def __init__(self, enumerable, predicate): <NEW_LINE> <INDENT> super(WhereEnumerable, self).__init__(enumerable) <NEW_LINE> self.predicate = predicate <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for e in iter(self._iterable): <NEW_LINE> <INDENT> if self.predicate(e): <NEW_LINE> <INDENT> yield e <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, n): <NEW_LINE> <INDENT> for i, e in enumerate(filter(self.predicate, self)): <NEW_LINE> <INDENT> if i == n: <NEW_LINE> <INDENT> return e
Class to hold state for filtering elements in a collection
62598fb657b8e32f525081a2
class Dog: <NEW_LINE> <INDENT> species = ["canius lupus"] <NEW_LINE> def __init__(self, n, c): <NEW_LINE> <INDENT> self.name = n <NEW_LINE> self.state = "sleeping" <NEW_LINE> self.color = c <NEW_LINE> <DEDENT> def command(self, x): <NEW_LINE> <INDENT> if x == self.name: <NEW_LINE> <INDENT> self.bark(2) <NEW_LINE> <DEDENT> elif x == "sit": <NEW_LINE> <INDENT> self.state = "sit" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.state = "wag tail" <NEW_LINE> <DEDENT> <DEDENT> def bark(self, freq): <NEW_LINE> <INDENT> for i in range(freq): <NEW_LINE> <INDENT> print(self.name + ":Woof!")
Blueprint of a dog
62598fb6be383301e0253906
@tags_namespace.route("/") <NEW_LINE> class Tags(Resource): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.datastore = DefaultStore(model=TagModel, database=DATABASE) <NEW_LINE> <DEDENT> @tags_namespace.marshal_list_with(tag_representation) <NEW_LINE> def get(self): <NEW_LINE> <INDENT> return self.datastore.read_all() <NEW_LINE> <DEDENT> @tags_namespace.doc("create_tag") <NEW_LINE> @tags_namespace.expect(tag_representation) <NEW_LINE> @tags_namespace.marshal_with(tag_representation, code=201) <NEW_LINE> def post(self): <NEW_LINE> <INDENT> if not request.json: <NEW_LINE> <INDENT> return None, 400 <NEW_LINE> <DEDENT> created_tag: TagModel = self.datastore.create(document=request.json) <NEW_LINE> return created_tag, 201
Resource representing tags collection.
62598fb63539df3088ecc3b7
class Address(EC2Object): <NEW_LINE> <INDENT> def __init__(self, connection=None, public_ip=None, instance_id=None): <NEW_LINE> <INDENT> EC2Object.__init__(self, connection) <NEW_LINE> self.connection = connection <NEW_LINE> self.public_ip = public_ip <NEW_LINE> self.instance_id = instance_id <NEW_LINE> self.domain = None <NEW_LINE> self.allocation_id = None <NEW_LINE> self.association_id = None <NEW_LINE> self.network_interface_id = None <NEW_LINE> self.network_interface_owner_id = None <NEW_LINE> self.private_ip_address = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Address:%s' % self.public_ip <NEW_LINE> <DEDENT> def endElement(self, name, value, connection): <NEW_LINE> <INDENT> if name == 'publicIp': <NEW_LINE> <INDENT> self.public_ip = value <NEW_LINE> <DEDENT> elif name == 'instanceId': <NEW_LINE> <INDENT> self.instance_id = value <NEW_LINE> <DEDENT> elif name == 'domain': <NEW_LINE> <INDENT> self.domain = value <NEW_LINE> <DEDENT> elif name == 'allocationId': <NEW_LINE> <INDENT> self.allocation_id = value <NEW_LINE> <DEDENT> elif name == 'associationId': <NEW_LINE> <INDENT> self.association_id = value <NEW_LINE> <DEDENT> elif name == 'networkInterfaceId': <NEW_LINE> <INDENT> self.network_interface_id = value <NEW_LINE> <DEDENT> elif name == 'networkInterfaceOwnerId': <NEW_LINE> <INDENT> self.network_interface_owner_id = value <NEW_LINE> <DEDENT> elif name == 'privateIpAddress': <NEW_LINE> <INDENT> self.private_ip_address = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(self, name, value) <NEW_LINE> <DEDENT> <DEDENT> def release(self): <NEW_LINE> <INDENT> if self.allocation_id: <NEW_LINE> <INDENT> return self.connection.release_address(None, self.allocation_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.connection.release_address(self.public_ip) <NEW_LINE> <DEDENT> <DEDENT> delete = release <NEW_LINE> def associate(self, instance_id): <NEW_LINE> <INDENT> return self.connection.associate_address(instance_id, self.public_ip) <NEW_LINE> <DEDENT> def disassociate(self): <NEW_LINE> <INDENT> if self.association_id: <NEW_LINE> <INDENT> return self.connection.disassociate_address(None, self.association_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.connection.disassociate_address(self.public_ip)
Represents an EC2 Elastic IP Address :ivar public_ip: The Elastic IP address. :ivar instance_id: The instance the address is associated with (if any). :ivar domain: Indicates whether the address is a EC2 address or a VPC address (standard|vpc). :ivar allocation_id: The allocation ID for the address (VPC addresses only). :ivar association_id: The association ID for the address (VPC addresses only). :ivar network_interface_id: The network interface (if any) that the address is associated with (VPC addresses only). :ivar network_interface_owner_id: The owner IID (VPC addresses only). :ivar private_ip_address: The private IP address associated with the Elastic IP address (VPC addresses only).
62598fb61f5feb6acb162d29
@ddt.ddt <NEW_LINE> class TestUserInfoApi(MobileAPITestCase, MobileAuthTestMixin): <NEW_LINE> <INDENT> REVERSE_INFO = {'name': 'user-info', 'params': ['api_version']} <NEW_LINE> @ddt.data(API_V05, API_V1) <NEW_LINE> def test_success(self, api_version): <NEW_LINE> <INDENT> self.login() <NEW_LINE> response = self.api_response(expected_response_code=302, api_version=api_version) <NEW_LINE> self.assertIn(self.username, response['location']) <NEW_LINE> <DEDENT> @ddt.data(API_V05, API_V1) <NEW_LINE> def test_last_loggedin_updated(self, api_version): <NEW_LINE> <INDENT> self.login() <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> last_login_before = self.user.last_login <NEW_LINE> self.api_response(expected_response_code=302, api_version=api_version) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> last_login_after = self.user.last_login <NEW_LINE> assert last_login_after > last_login_before
Tests for /api/mobile/{api_version}/my_user_info
62598fb623849d37ff8511bd
class IdentifiableDataTypeAggregator(Rewriter): <NEW_LINE> <INDENT> @contract <NEW_LINE> def _rewrite_data_type(self, data_type: DataType, definitions: Dict) -> Tuple: <NEW_LINE> <INDENT> if isinstance(data_type, IdentifiableDataType): <NEW_LINE> <INDENT> definitions.setdefault('data', {}) <NEW_LINE> if data_type.name not in definitions['data']: <NEW_LINE> <INDENT> definitions['data'][data_type.name] = {} <NEW_LINE> schema, definitions = self._rewrite(data_type.get_json_schema(), definitions) <NEW_LINE> definitions['data'][data_type.name] = schema <NEW_LINE> <DEDENT> return { '$ref': '#/definitions/%s/%s' % ('data', data_type.name), }, definitions <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._rewrite(data_type.get_json_schema(), definitions) <NEW_LINE> <DEDENT> <DEDENT> def rewrite(self, schema): <NEW_LINE> <INDENT> schema, definitions = self._rewrite(schema, {}) <NEW_LINE> for data_type, data_definitions in definitions.items(): <NEW_LINE> <INDENT> for data_name, data_definition in data_definitions.items(): <NEW_LINE> <INDENT> schema.setdefault('definitions', {}) <NEW_LINE> schema['definitions'].setdefault(data_type, {}) <NEW_LINE> schema['definitions'][data_type][data_name] = data_definition <NEW_LINE> <DEDENT> <DEDENT> return schema <NEW_LINE> <DEDENT> @contract <NEW_LINE> def _rewrite(self, data, definitions: Dict): <NEW_LINE> <INDENT> data = copy(data) <NEW_LINE> definitions = copy(definitions) <NEW_LINE> if isinstance(data, DataType): <NEW_LINE> <INDENT> return self._rewrite_data_type(data, definitions) <NEW_LINE> <DEDENT> if isinstance(data, List): <NEW_LINE> <INDENT> for index, item in enumerate(data): <NEW_LINE> <INDENT> data[index], definitions = self._rewrite(item, definitions) <NEW_LINE> <DEDENT> return data, definitions <NEW_LINE> <DEDENT> elif isinstance(data, Dict): <NEW_LINE> <INDENT> for key, item in data.items(): <NEW_LINE> <INDENT> data[key], definitions = self._rewrite(item, definitions) <NEW_LINE> <DEDENT> return data, definitions <NEW_LINE> <DEDENT> return data, definitions
Rewrites a JSON Schema's IdentifiableDataTypes.
62598fb6ec188e330fdf899a
class GasBC(sc.BC): <NEW_LINE> <INDENT> _ghostgeom_ = None <NEW_LINE> def __init__(self, **kw): <NEW_LINE> <INDENT> super(GasBC, self).__init__(**kw) <NEW_LINE> self.bcd = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def alg(self): <NEW_LINE> <INDENT> return self.svr.alg <NEW_LINE> <DEDENT> def init(self, **kw): <NEW_LINE> <INDENT> self.bcd = self.create_bcd() <NEW_LINE> getattr(self.alg, 'ghostgeom_'+self._ghostgeom_)(self.bcd)
Base class for all boundary conditions of the gas solver.
62598fb610dbd63aa1c70cc1
class Abs(VbaLibraryFunc): <NEW_LINE> <INDENT> def eval(self, context, params=None): <NEW_LINE> <INDENT> if ((params is None) or (len(params) < 1)): <NEW_LINE> <INDENT> return "NULL" <NEW_LINE> <DEDENT> r = '' <NEW_LINE> try: <NEW_LINE> <INDENT> num = utils.int_convert(params[0]) <NEW_LINE> r = abs(num) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if (log.getEffectiveLevel() == logging.DEBUG): <NEW_LINE> <INDENT> log.debug("Abs: %r returns %r" % (self, r)) <NEW_LINE> <DEDENT> return r
Abs() math function.
62598fb6f548e778e596b6af
class UserSettingsHolder: <NEW_LINE> <INDENT> SETTINGS_MODULE = None <NEW_LINE> def __init__(self, default_settings): <NEW_LINE> <INDENT> self.__dict__['_deleted'] = set() <NEW_LINE> self.default_settings = default_settings <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> if not name.isupper() or name in self._deleted: <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> return getattr(self.default_settings, name) <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> self._deleted.discard(name) <NEW_LINE> if name == 'PASSWORD_RESET_TIMEOUT_DAYS': <NEW_LINE> <INDENT> setattr(self, 'PASSWORD_RESET_TIMEOUT', value * 60 * 60 * 24) <NEW_LINE> warnings.warn(PASSWORD_RESET_TIMEOUT_DAYS_DEPRECATED_MSG, RemovedInDjango40Warning) <NEW_LINE> <DEDENT> if name == 'DEFAULT_HASHING_ALGORITHM': <NEW_LINE> <INDENT> warnings.warn(DEFAULT_HASHING_ALGORITHM_DEPRECATED_MSG, RemovedInDjango40Warning) <NEW_LINE> <DEDENT> super().__setattr__(name, value) <NEW_LINE> <DEDENT> def __delattr__(self, name): <NEW_LINE> <INDENT> self._deleted.add(name) <NEW_LINE> if hasattr(self, name): <NEW_LINE> <INDENT> super().__delattr__(name) <NEW_LINE> <DEDENT> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> return sorted( s for s in [*self.__dict__, *dir(self.default_settings)] if s not in self._deleted ) <NEW_LINE> <DEDENT> def is_overridden(self, setting): <NEW_LINE> <INDENT> deleted = (setting in self._deleted) <NEW_LINE> set_locally = (setting in self.__dict__) <NEW_LINE> set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting) <NEW_LINE> return deleted or set_locally or set_on_default <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%(cls)s>' % { 'cls': self.__class__.__name__, }
Holder for user configured settings.
62598fb6aad79263cf42e8de
class ServerException(Error): <NEW_LINE> <INDENT> pass
Indicates a problem handling the request.
62598fb6167d2b6e312b707e
@register <NEW_LINE> class CompoundMonitor(Monitor): <NEW_LINE> <INDENT> type = "compound" <NEW_LINE> def __init__(self, name, config_options): <NEW_LINE> <INDENT> Monitor.__init__(self, name, config_options) <NEW_LINE> self.monitors = Monitor.get_config_option( config_options, 'monitors', required_type='[str]', required=True, default=[] ) <NEW_LINE> self.min_fail = Monitor.get_config_option(config_options, 'min_fail', required_type='int', default=len(self.monitors), minimum=1 ) <NEW_LINE> self.m = -1 <NEW_LINE> self.mt = None <NEW_LINE> <DEDENT> def run_test(self): <NEW_LINE> <INDENT> failcount = self.min_fail <NEW_LINE> for i in self.monitors: <NEW_LINE> <INDENT> if self.m[i].get_success_count() > 0 and self.m[i].tests_run > 0: <NEW_LINE> <INDENT> failcount -= 1 <NEW_LINE> <DEDENT> <DEDENT> return (failcount > 0) <NEW_LINE> <DEDENT> def describe(self): <NEW_LINE> <INDENT> return "Checking that these monitors all succeeded: {0}".format(", ".join(self.monitors)) <NEW_LINE> <DEDENT> def get_params(self): <NEW_LINE> <INDENT> return (self.monitors) <NEW_LINE> <DEDENT> def set_mon_refs(self, mmm): <NEW_LINE> <INDENT> self.mt = mmm <NEW_LINE> <DEDENT> def post_config_setup(self): <NEW_LINE> <INDENT> if self.m != -1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.m = {} <NEW_LINE> for i in list(self.mt.monitors.keys()): <NEW_LINE> <INDENT> if i in self.monitors: <NEW_LINE> <INDENT> self.m[i] = self.mt.monitors[i] <NEW_LINE> <DEDENT> <DEDENT> for i in self.monitors: <NEW_LINE> <INDENT> if i not in list(self.m.keys()): <NEW_LINE> <INDENT> raise RuntimeError("No such monitor %s in compound monitor" % i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def virtual_fail_count(self): <NEW_LINE> <INDENT> failcount = self.fail_count() <NEW_LINE> if failcount >= self.min_fail: <NEW_LINE> <INDENT> return failcount <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def fail_count(self): <NEW_LINE> <INDENT> failcount = 0 <NEW_LINE> for i in self.monitors: <NEW_LINE> <INDENT> if self.m[i].virtual_fail_count() > 0: <NEW_LINE> <INDENT> failcount += 1 <NEW_LINE> <DEDENT> <DEDENT> return failcount <NEW_LINE> <DEDENT> def get_result(self): <NEW_LINE> <INDENT> failcount = self.fail_count() <NEW_LINE> monitorcount = self.monitors.__len__() <NEW_LINE> if failcount > 0: <NEW_LINE> <INDENT> return "{0} of {1} services failed. Fail after: {2}".format(failcount, monitorcount, self.min_fail) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "All {0} services OK".format(monitorcount)
Combine (logical-and) multiple failures for emergency escalation. Check most recent proble of provided monitors, if all are fail, then report fail.
62598fb632920d7e50bc6159
class FreeboxFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._host = None <NEW_LINE> self._port = None <NEW_LINE> <DEDENT> def _show_setup_form(self, user_input=None, errors=None): <NEW_LINE> <INDENT> if user_input is None: <NEW_LINE> <INDENT> user_input = {} <NEW_LINE> <DEDENT> return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_HOST, default=user_input.get(CONF_HOST, "")): str, vol.Required(CONF_PORT, default=user_input.get(CONF_PORT, "")): int, } ), errors=errors or {}, ) <NEW_LINE> <DEDENT> async def async_step_user(self, user_input=None): <NEW_LINE> <INDENT> errors = {} <NEW_LINE> if user_input is None: <NEW_LINE> <INDENT> return self._show_setup_form(user_input, errors) <NEW_LINE> <DEDENT> self._host = user_input[CONF_HOST] <NEW_LINE> self._port = user_input[CONF_PORT] <NEW_LINE> await self.async_set_unique_id(self._host) <NEW_LINE> self._abort_if_unique_id_configured() <NEW_LINE> return await self.async_step_link() <NEW_LINE> <DEDENT> async def async_step_link(self, user_input=None): <NEW_LINE> <INDENT> if user_input is None: <NEW_LINE> <INDENT> return self.async_show_form(step_id="link") <NEW_LINE> <DEDENT> errors = {} <NEW_LINE> fbx = await get_api(self.hass, self._host) <NEW_LINE> try: <NEW_LINE> <INDENT> await fbx.open(self._host, self._port) <NEW_LINE> await fbx.system.get_config() <NEW_LINE> await fbx.lan.get_hosts_list() <NEW_LINE> await self.hass.async_block_till_done() <NEW_LINE> await fbx.close() <NEW_LINE> return self.async_create_entry( title=self._host, data={CONF_HOST: self._host, CONF_PORT: self._port}, ) <NEW_LINE> <DEDENT> except AuthorizationError as error: <NEW_LINE> <INDENT> _LOGGER.error(error) <NEW_LINE> errors["base"] = "register_failed" <NEW_LINE> <DEDENT> except HttpRequestError: <NEW_LINE> <INDENT> _LOGGER.error("Error connecting to the Freebox router at %s", self._host) <NEW_LINE> errors["base"] = "cannot_connect" <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _LOGGER.exception( "Unknown error connecting with Freebox router at %s", self._host ) <NEW_LINE> errors["base"] = "unknown" <NEW_LINE> <DEDENT> return self.async_show_form(step_id="link", errors=errors) <NEW_LINE> <DEDENT> async def async_step_import(self, user_input=None): <NEW_LINE> <INDENT> return await self.async_step_user(user_input) <NEW_LINE> <DEDENT> async def async_step_discovery(self, discovery_info): <NEW_LINE> <INDENT> return await self.async_step_user(discovery_info)
Handle a config flow.
62598fb660cbc95b06364449
class GetPrepaysResponse(messages.Message): <NEW_LINE> <INDENT> ok = messages.BooleanField(1) <NEW_LINE> prepays = messages.MessageField(Prepay, 2, repeated=True) <NEW_LINE> error = messages.StringField(3)
Response to a location search ok: (Boolean) Bill search successful or failed prepays: (String) If search successful contains a list of prepay events (see class Prepay on messages.py) error: (String) If search failed, contains the reason, otherwise empty.
62598fb6236d856c2adc94c5
class ResNetUpSample(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_shape, block, layers, num_classes=1, **kwargs): <NEW_LINE> <INDENT> super(ResNetUpSample, self).__init__() <NEW_LINE> self.base = ResNet( input_shape, block, layers, num_classes=num_classes, **kwargs) <NEW_LINE> last_layer = [ obj for obj in self.base.modules() if isinstance(obj, nn.Conv2d) ][-1] <NEW_LINE> self.classifier = nn.Sequential( nn.Conv2d( last_layer.out_channels, num_classes, kernel_size=1, padding=0)) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> orig_size = x.size() <NEW_LINE> x = self.base(x)[0][0] <NEW_LINE> x = self.classifier(x) <NEW_LINE> x = F.upsample(x, size=orig_size[-2:], mode='bilinear') <NEW_LINE> return x
Upsampled variant of ResNet This is a simpler variant which does not rely on complex reconstruction methods, instead it employs a naive interpolation (nearest neighbor/bilinear) at the very end to recover the original size.
62598fb630bbd722464699ff
class seq_region: <NEW_LINE> <INDENT> def __init__(self, seq): <NEW_LINE> <INDENT> self.seq = seq <NEW_LINE> self.coords = [] <NEW_LINE> self.exon = [] <NEW_LINE> for i, char in enumerate(self.seq): <NEW_LINE> <INDENT> if char.isupper(): <NEW_LINE> <INDENT> self.coords.append(i) <NEW_LINE> self.exon.append(char) <NEW_LINE> <DEDENT> <DEDENT> self.exon = ''.join(self.exon) <NEW_LINE> self.exon_coord = (min(self.coords), max(self.coords)) <NEW_LINE> <DEDENT> def find_motif_coords(self, motif_match): <NEW_LINE> <INDENT> self.motif_coords_list = [] <NEW_LINE> m = re.finditer(r'(?i)'+motif_match, self.seq) <NEW_LINE> for i in m: <NEW_LINE> <INDENT> self.motif_coords_list.append(str(i.start())) <NEW_LINE> <DEDENT> return self.motif_coords_list
Class for each exon region
62598fb756b00c62f0fb29c5
class Address(BaseModel): <NEW_LINE> <INDENT> receiver_name = models.CharField(max_length=20, verbose_name="收件人") <NEW_LINE> receiver_mobile = models.CharField(max_length=11, verbose_name="联系电话") <NEW_LINE> detail_addr = models.CharField(max_length=256, verbose_name="详细地址") <NEW_LINE> zip_code = models.CharField(max_length=6, null=True, verbose_name="邮政编码") <NEW_LINE> is_default = models.BooleanField(default=False, verbose_name='默认地址') <NEW_LINE> user = models.ForeignKey(User, verbose_name="所属用户") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "df_address" <NEW_LINE> verbose_name = '地址' <NEW_LINE> verbose_name_plural = verbose_name
地址模型类
62598fb73d592f4c4edbafcc
class LoginPage(BasePage): <NEW_LINE> <INDENT> username_loc=(By.NAME,'email') <NEW_LINE> password_loc=(By.NAME,'password') <NEW_LINE> sumbit_loc=(By.ID,'dologin') <NEW_LINE> turnright_button_loc=(By.ID,'nextTheme') <NEW_LINE> turnleft_button_loc=(By.ID,'prevTheme') <NEW_LINE> user_loc = (By.ID, 'spnUid') <NEW_LINE> '''============Action============''' <NEW_LINE> def open(self): <NEW_LINE> <INDENT> self._open(self.url) <NEW_LINE> <DEDENT> def inputUsername(self,username): <NEW_LINE> <INDENT> self.elementClick(self.username_loc) <NEW_LINE> self.elementClear(self.username_loc) <NEW_LINE> self.elementInput(self.username_loc,username) <NEW_LINE> <DEDENT> def inputPassword(self,password): <NEW_LINE> <INDENT> self.elementClick(self.password_loc) <NEW_LINE> self.elementInput(self.password_loc,password) <NEW_LINE> <DEDENT> def submit(self): <NEW_LINE> <INDENT> self.elementClick(self.sumbit_loc) <NEW_LINE> <DEDENT> def clickNextTheme(self): <NEW_LINE> <INDENT> self.elementClick(self.turnright_button_loc) <NEW_LINE> <DEDENT> def clickPrevTheme(self): <NEW_LINE> <INDENT> self.elementClick(self.turnleft_button_loc) <NEW_LINE> <DEDENT> def get_error(self): <NEW_LINE> <INDENT> error_info=super(LoginPage,self).js_element_loc_text('nerror') <NEW_LINE> return error_info
============定位器============
62598fb78e7ae83300ee91ab
class CommandAPDURegister(CommandAPDU): <NEW_LINE> <INDENT> APDU_INS = const.U2F.REGISTER <NEW_LINE> APDU_RESPONSE = ResponseAPDURegister <NEW_LINE> def verify_request_data(self, *, untrusted_request_data): <NEW_LINE> <INDENT> assert len(untrusted_request_data ) == const.U2F_NONCE_SIZE + const.U2F_APPID_SIZE <NEW_LINE> request_data = untrusted_request_data <NEW_LINE> return request_data <NEW_LINE> <DEDENT> def verify_p1(self, *, untrusted_p1): <NEW_LINE> <INDENT> p1 = const.U2F_AUTH(untrusted_p1) <NEW_LINE> return p1 <NEW_LINE> <DEDENT> def hexdump_request_data(self): <NEW_LINE> <INDENT> return util.hexlify_with_parition(self.request_data, const.U2F_NONCE_SIZE)
U2F_REGISTER
62598fb7cc0a2c111447b118
class LFWTrainer(GRUTrainer): <NEW_LINE> <INDENT> def __init__(self, folder): <NEW_LINE> <INDENT> super(LFWTrainer, self).__init__() <NEW_LINE> self.folder = folder <NEW_LINE> self.env = neighbors.KNeighborsClassifier(3) <NEW_LINE> self.cv = StratifiedKFold(n_splits=3) <NEW_LINE> <DEDENT> def load_data(self, data_dir): <NEW_LINE> <INDENT> from sklearn.decomposition import PCA, TruncatedSVD <NEW_LINE> from collections import Counter <NEW_LINE> data = datasets.fetch_lfw_people() <NEW_LINE> majority_person = 1871 <NEW_LINE> minority_person = 531 <NEW_LINE> majority_idxs = np.flatnonzero(data.target == majority_person) <NEW_LINE> minority_idxs = np.flatnonzero(data.target == minority_person) <NEW_LINE> idxs = np.hstack((majority_idxs, minority_idxs)) <NEW_LINE> x = data.data[idxs] <NEW_LINE> y = data.target[idxs] <NEW_LINE> y[y == majority_person] = 0 <NEW_LINE> y[y == minority_person] = 1 <NEW_LINE> train_x = TruncatedSVD(n_components=100).fit_transform(x) <NEW_LINE> i = 1 <NEW_LINE> for train, test in self.cv.split(x, y): <NEW_LINE> <INDENT> if i == self.folder: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> y = np.eye(2)[y.astype('int32')] <NEW_LINE> return train_x[train], y[train], x[train], y[train], x[test], y[test] <NEW_LINE> <DEDENT> def get_reward(self, train_x, train_y, train_weights, valid_x, valid_y, test_x, test_y): <NEW_LINE> <INDENT> from imblearn.metrics import geometric_mean_score <NEW_LINE> from sklearn.metrics import matthews_corrcoef <NEW_LINE> idx = train_weights == 1 <NEW_LINE> x = valid_x[idx] <NEW_LINE> y = valid_y[idx] <NEW_LINE> self.env.fit(x, np.argmax(y, axis=1).astype('int32')) <NEW_LINE> preds = self.env.predict_proba(test_x) <NEW_LINE> if preds.shape[1] == 2: <NEW_LINE> <INDENT> preds = preds[:, 1] <NEW_LINE> <DEDENT> valid_reward = evaluate_auc_roc(np.argmax(test_y, axis=1).astype('int32'), preds) <NEW_LINE> return valid_reward, valid_reward, valid_reward
Train on real data set (LFW)
62598fb744b2445a339b69f9
class RevokedNotSigning(DNSKEYError): <NEW_LINE> <INDENT> _abstract = False <NEW_LINE> description_template = "The key was revoked but was not found signing the RRset." <NEW_LINE> code = 'REVOKED_NOT_SIGNING'
>>> e = RevokedNotSigning() >>> e.description 'The key was revoked but was not found signing the RRset.'
62598fb7377c676e912f6df4
class _SequenceType(_BuiltinType): <NEW_LINE> <INDENT> def __init__(cls, name, bases, namespace): <NEW_LINE> <INDENT> super().__init__(name, bases, namespace) <NEW_LINE> cls._elem_type = None <NEW_LINE> cls._bases = bases <NEW_LINE> cls._namespace = namespace <NEW_LINE> <DEDENT> def __instancecheck__(cls, inst): <NEW_LINE> <INDENT> if not issubclass(type(inst), cls): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if cls._elem_type is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return all(isinstance(c, cls._elem_type) for c in inst) <NEW_LINE> <DEDENT> def __getitem__(cls, elem_type): <NEW_LINE> <INDENT> if not isinstance(elem_type, type): <NEW_LINE> <INDENT> raise TypeError('{0} is not a valid type'.format(elem_type)) <NEW_LINE> <DEDENT> if isinstance(elem_type, tuple): <NEW_LINE> <INDENT> raise TypeError('invalid type specification for container type: ' 'expected ContainerType[elem_type]') <NEW_LINE> <DEDENT> ret = _SequenceType('%s[%s]' % (cls.__name__, elem_type.__name__), cls._bases, cls._namespace) <NEW_LINE> ret._elem_type = elem_type <NEW_LINE> cls.register(ret) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def __rfm_cast_str__(cls, s): <NEW_LINE> <INDENT> container_type = cls._type <NEW_LINE> elem_type = cls._elem_type <NEW_LINE> return container_type(elem_type(e) for e in s.split(','))
A metaclass for containers with uniformly typed elements.
62598fb7a05bb46b3848a977
class CheckerForm(AlwaysChangedModelForm): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> super(CheckerForm, self).__init__(**args) <NEW_LINE> self.fields["_flags"].initial = "-Wall -static" <NEW_LINE> self.fields["_output_flags"].initial = "--main=%s" <NEW_LINE> self.fields["_file_pattern"].initial = r"^[a-zA-Z0-9_]*\.[jJ][aA][vV][aA]$"
override default values for the model fields
62598fb74a966d76dd5eefe3
class BadPlugin(Exception): <NEW_LINE> <INDENT> pass
Invalid plugin exception
62598fb73d592f4c4edbafcd
class GymnasiumDeleteView(DeleteView): <NEW_LINE> <INDENT> model = Gymnasium <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if True not in [request.user.is_superuser, request.user.is_staff]: <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> return super().get(request, args, kwargs) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if True not in [request.user.is_superuser, request.user.is_staff]: <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> return super().post(request, args, kwargs) <NEW_LINE> <DEDENT> def get_success_url(self, **kwargs): <NEW_LINE> <INDENT> messages.success(self.request, "Gymnasium '{}' deleted successfully".format(self.object.name)) <NEW_LINE> return reverse('gymnasiums:list')
Delete of a Gymnasium.
62598fb72ae34c7f260ab1e8
class IndexFileSHA1Writer(object): <NEW_LINE> <INDENT> __slots__ = ("f", "sha1") <NEW_LINE> def __init__(self, f: IO) -> None: <NEW_LINE> <INDENT> self.f = f <NEW_LINE> self.sha1 = make_sha(b"") <NEW_LINE> <DEDENT> def write(self, data: AnyStr) -> int: <NEW_LINE> <INDENT> self.sha1.update(data) <NEW_LINE> return self.f.write(data) <NEW_LINE> <DEDENT> def write_sha(self) -> bytes: <NEW_LINE> <INDENT> sha = self.sha1.digest() <NEW_LINE> self.f.write(sha) <NEW_LINE> return sha <NEW_LINE> <DEDENT> def close(self) -> bytes: <NEW_LINE> <INDENT> sha = self.write_sha() <NEW_LINE> self.f.close() <NEW_LINE> return sha <NEW_LINE> <DEDENT> def tell(self) -> int: <NEW_LINE> <INDENT> return self.f.tell()
Wrapper around a file-like object that remembers the SHA1 of the data written to it. It will write a sha when the stream is closed or if the asked for explicitly using write_sha. Only useful to the indexfile :note: Based on the dulwich project
62598fb7a8370b77170f04ea
class Freespace: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._ranges = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return [[r.start, r.stop] for r in self._ranges] <NEW_LINE> <DEDENT> def _ranges_with(self, start, size): <NEW_LINE> <INDENT> merged_start = start <NEW_LINE> merged_stop = start + size <NEW_LINE> merged_written = False <NEW_LINE> for r in self._ranges: <NEW_LINE> <INDENT> if r.stop < merged_start: <NEW_LINE> <INDENT> yield r <NEW_LINE> <DEDENT> elif r.start > merged_stop: <NEW_LINE> <INDENT> if not merged_written: <NEW_LINE> <INDENT> yield range(merged_start, merged_stop) <NEW_LINE> <DEDENT> merged_written = True <NEW_LINE> yield r <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> merged_start = min(merged_start, r.start) <NEW_LINE> merged_stop = max(merged_stop, r.stop) <NEW_LINE> <DEDENT> <DEDENT> if not merged_written: <NEW_LINE> <INDENT> yield range(merged_start, merged_stop) <NEW_LINE> <DEDENT> <DEDENT> def including(self, start, size): <NEW_LINE> <INDENT> result = Freespace() <NEW_LINE> result._ranges = list(self._ranges_with(start, size)) <NEW_LINE> return result <NEW_LINE> <DEDENT> def add(self, start, size): <NEW_LINE> <INDENT> self._ranges = list(self._ranges_with(start, size)) <NEW_LINE> <DEDENT> def _ranges_without(self, start, size): <NEW_LINE> <INDENT> removed_start = start <NEW_LINE> removed_stop = start + size <NEW_LINE> for r in self._ranges: <NEW_LINE> <INDENT> if r.stop <= removed_start or r.start >= removed_stop: <NEW_LINE> <INDENT> yield r <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if r.start < removed_start: <NEW_LINE> <INDENT> yield range(r.start, removed_start) <NEW_LINE> <DEDENT> if r.stop > removed_stop: <NEW_LINE> <INDENT> yield range(removed_stop, r.stop) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def excluding(self, start, size): <NEW_LINE> <INDENT> result = Freespace() <NEW_LINE> result._ranges = list(self._ranges_without(start, size)) <NEW_LINE> return result <NEW_LINE> <DEDENT> def remove(self, start, size): <NEW_LINE> <INDENT> self._ranges = list(self._ranges_without(start, size)) <NEW_LINE> <DEDENT> def _candidate_ranges(self, size, pointer_gamut): <NEW_LINE> <INDENT> for r in self._ranges: <NEW_LINE> <INDENT> if size == 0: <NEW_LINE> <INDENT> yield range(0, 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield range_intersect( range(r.start, r.stop - size + 1), pointer_gamut ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def candidates(self, size, pointer_gamut): <NEW_LINE> <INDENT> return Candidates(tuple(self._candidate_ranges(size, pointer_gamut)))
Represents a set of "free" locations in the file to be patched.
62598fb7cc40096d6161a25f
class Portfolio(object): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> @abstractmethod <NEW_LINE> def update_signal(self, event): <NEW_LINE> <INDENT> raise NotImplementedError("Should implement update_signal()") <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def update_fill(self, event): <NEW_LINE> <INDENT> raise NotImplementedError("Should implement update_fill()")
The Portfolio class handles the positions and market value of all instruments at a resolution of a "bar", i.e. secondly, minutely, 5-min, 30-min, 60-min, or EOD.
62598fb7bf627c535bcb15ae
class VirtualNetworkPeeringListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[VirtualNetworkPeering]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(VirtualNetworkPeeringListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None)
Response for ListSubnets API service call. Retrieves all subnets that belong to a virtual network. :param value: The peerings in a virtual network. :type value: list[~azure.mgmt.network.v2016_09_01.models.VirtualNetworkPeering] :param next_link: The URL to get the next set of results. :type next_link: str
62598fb730dc7b766599f959
class CompleteServiceJobByServiceJobIdResponse(__BaseDictObject): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> super().__init__(data) <NEW_LINE> if "errors" in data: <NEW_LINE> <INDENT> self.errors: ErrorList = self._get_value(ErrorList, "errors") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.errors: ErrorList = None
Response schema for CompleteServiceJobByServiceJobId operation.
62598fb767a9b606de5460dd
class _Cache(MutableMapping): <NEW_LINE> <INDENT> def __init__(self, registry, tags): <NEW_LINE> <INDENT> self._registry = registry <NEW_LINE> self._tags = tags <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self._registry[self._tags | set([key])] <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self._registry[self._tags | set([key])] = value <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> del self._registry[self._tags | set([key])] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for item in self._registry.iterate(*self._tags): <NEW_LINE> <INDENT> yield list(item.difference(self._tags))[0] <NEW_LINE> <DEDENT> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return list(iter(self)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(list(iter(self))) <NEW_LINE> <DEDENT> def expire(self, key=None): <NEW_LINE> <INDENT> if key is None: <NEW_LINE> <INDENT> return expire(*self._tags) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tags = self._tags | set([key]) <NEW_LINE> kwargs = dict(exact=True) <NEW_LINE> return expire(*tags, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(dict(self)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(dict(self))
The object returned by :func:`Bcfg2.Server.Cache.Cache` that presents a dict-like interface to the portion of the unified cache that uses the specified tags.
62598fb74527f215b58e9fe2
class CliAlarmShow(show.ShowOne): <NEW_LINE> <INDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> return _add_name_to_parser( _add_id_to_parser( super(CliAlarmShow, self).get_parser(prog_name))) <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> _check_name_and_id(parsed_args, 'query') <NEW_LINE> c = utils.get_client(self) <NEW_LINE> if parsed_args.name: <NEW_LINE> <INDENT> alarm = _find_alarm_by_name(c, parsed_args.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if uuidutils.is_uuid_like(parsed_args.id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> alarm = c.alarm.get(alarm_id=parsed_args.id) <NEW_LINE> <DEDENT> except exceptions.NotFound: <NEW_LINE> <INDENT> alarm = _find_alarm_by_name(c, parsed_args.id) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> alarm = _find_alarm_by_name(c, parsed_args.id) <NEW_LINE> <DEDENT> <DEDENT> return self.dict2columns(_format_alarm(alarm))
Show an alarm
62598fb792d797404e388be9
class Ethertype(enum.Enum): <NEW_LINE> <INDENT> IPv4 = 4 <NEW_LINE> IPv6 = 6
A rule's ethertype
62598fb73346ee7daa3376ce
class SampleInput(unittest.TestCase): <NEW_LINE> <INDENT> def test_sample_input(self): <NEW_LINE> <INDENT> inputs = [] <NEW_LINE> inputs.append('42') <NEW_LINE> inputs.append('5') <NEW_LINE> inputs.append('END') <NEW_LINE> inputs = '\n'.join(inputs) + '\n' <NEW_LINE> outputs = [] <NEW_LINE> outputs.append('3') <NEW_LINE> outputs.append('2') <NEW_LINE> outputs = '\n'.join(outputs) + '\n' <NEW_LINE> with patch('sys.stdin', io.StringIO(inputs)) as stdin, patch('sys.stdout', new_callable=io.StringIO) as stdout: <NEW_LINE> <INDENT> k_digits.main() <NEW_LINE> self.assertEqual(stdout.getvalue(), outputs) <NEW_LINE> self.assertEqual(stdin.read(), '') <NEW_LINE> <DEDENT> <DEDENT> def test_search_for_wa(self): <NEW_LINE> <INDENT> inputs = [] <NEW_LINE> inputs.append('42 ') <NEW_LINE> inputs.append('5') <NEW_LINE> inputs.append('1') <NEW_LINE> inputs.append('0') <NEW_LINE> inputs.append('10') <NEW_LINE> inputs.append('12345678901') <NEW_LINE> inputs.append('END') <NEW_LINE> inputs = '\n'.join(inputs) + '\n' <NEW_LINE> outputs = [] <NEW_LINE> outputs.append('3') <NEW_LINE> outputs.append('2') <NEW_LINE> outputs.append('1') <NEW_LINE> outputs.append('2') <NEW_LINE> outputs.append('3') <NEW_LINE> outputs.append('4') <NEW_LINE> outputs = '\n'.join(outputs) + '\n' <NEW_LINE> with patch('sys.stdin', io.StringIO(inputs)) as stdin, patch('sys.stdout', new_callable=io.StringIO) as stdout: <NEW_LINE> <INDENT> k_digits.main() <NEW_LINE> self.assertEqual(stdout.getvalue(), outputs) <NEW_LINE> self.assertEqual(stdin.read(), '')
Problem statement sample inputs and outputs
62598fb7ec188e330fdf899c
class NamedTemporaryFile(io.BufferedIOBase): <NEW_LINE> <INDENT> def __init__(self, dir=None, suffix='.tmp', prefix='obspy-'): <NEW_LINE> <INDENT> fd, self.name = tempfile.mkstemp(dir=dir, prefix=prefix, suffix=suffix) <NEW_LINE> self._fileobj = os.fdopen(fd, 'w+b', 0) <NEW_LINE> <DEDENT> def read(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._fileobj.read(*args, **kwargs) <NEW_LINE> <DEDENT> def write(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._fileobj.write(*args, **kwargs) <NEW_LINE> <DEDENT> def seek(self, *args, **kwargs): <NEW_LINE> <INDENT> self._fileobj.seek(*args, **kwargs) <NEW_LINE> return self._fileobj.tell() <NEW_LINE> <DEDENT> def tell(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._fileobj.tell(*args, **kwargs) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.close() <NEW_LINE> self._fileobj.close() <NEW_LINE> os.remove(self.name)
Weak replacement for the Python's tempfile.TemporaryFile. This class is a replacement for :func:`tempfile.NamedTemporaryFile` but will work also with Windows 7/Vista's UAC. :type dir: str :param dir: If specified, the file will be created in that directory, otherwise the default directory for temporary files is used. :type suffix: str :param suffix: The temporary file name will end with that suffix. Defaults to ``'.tmp'``. .. rubric:: Example >>> with NamedTemporaryFile() as tf: ... _ = tf.write(b"test") ... os.path.exists(tf.name) True >>> # when using the with statement, the file is deleted at the end: >>> os.path.exists(tf.name) False >>> with NamedTemporaryFile() as tf: ... filename = tf.name ... with open(filename, 'wb') as fh: ... _ = fh.write(b"just a test") ... with open(filename, 'r') as fh: ... print(fh.read()) just a test >>> # when using the with statement, the file is deleted at the end: >>> os.path.exists(tf.name) False
62598fb721bff66bcd722d74
class Manager(object): <NEW_LINE> <INDENT> model = Model <NEW_LINE> def __init__(self, datastore, model=None): <NEW_LINE> <INDENT> if model: <NEW_LINE> <INDENT> self.model = model <NEW_LINE> <DEDENT> self.datastore = ObjectDatastore(datastore, model=self.model) <NEW_LINE> <DEDENT> def key(self, key_or_name): <NEW_LINE> <INDENT> if not isinstance(key_or_name, Key): <NEW_LINE> <INDENT> return self.model.key.instance(key_or_name) <NEW_LINE> <DEDENT> if key_or_name.type != self.model.key.name: <NEW_LINE> <INDENT> err = 'key %s must have key type %s' <NEW_LINE> raise TypeError(err % (key_or_name, self.model.key.name)) <NEW_LINE> <DEDENT> return key_or_name <NEW_LINE> <DEDENT> def contains(self, key): <NEW_LINE> <INDENT> return self.datastore.contains(self.key(key)) <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> return self.datastore.get(self.key(key)) <NEW_LINE> <DEDENT> def put(self, instance): <NEW_LINE> <INDENT> if not isinstance(instance, self.model): <NEW_LINE> <INDENT> raise TypeError('%s must be of type %s' % (instance, self.model)) <NEW_LINE> <DEDENT> self.datastore.put(instance.key, instance) <NEW_LINE> <DEDENT> def delete(self, key_or_name): <NEW_LINE> <INDENT> self.datastore.delete(self.key(key_or_name))
Simplified manager for model instances.
62598fb710dbd63aa1c70cc4
class SignalRKeys(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'primary_key': {'key': 'primaryKey', 'type': 'str'}, 'secondary_key': {'key': 'secondaryKey', 'type': 'str'}, 'primary_connection_string': {'key': 'primaryConnectionString', 'type': 'str'}, 'secondary_connection_string': {'key': 'secondaryConnectionString', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, primary_key: Optional[str] = None, secondary_key: Optional[str] = None, primary_connection_string: Optional[str] = None, secondary_connection_string: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(SignalRKeys, self).__init__(**kwargs) <NEW_LINE> self.primary_key = primary_key <NEW_LINE> self.secondary_key = secondary_key <NEW_LINE> self.primary_connection_string = primary_connection_string <NEW_LINE> self.secondary_connection_string = secondary_connection_string
A class represents the access keys of the resource. :param primary_key: The primary access key. :type primary_key: str :param secondary_key: The secondary access key. :type secondary_key: str :param primary_connection_string: Connection string constructed via the primaryKey. :type primary_connection_string: str :param secondary_connection_string: Connection string constructed via the secondaryKey. :type secondary_connection_string: str
62598fb7d486a94d0ba2c0da
class TestFranchisereferalincomeCreateObjectV1Request(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 testFranchisereferalincomeCreateObjectV1Request(self): <NEW_LINE> <INDENT> pass
FranchisereferalincomeCreateObjectV1Request unit test stubs
62598fb74527f215b58e9fe3
class MapboxQuery(MultipleResultsQuery): <NEW_LINE> <INDENT> provider = 'mapbox' <NEW_LINE> method = 'geocode' <NEW_LINE> _URL = u'https://api.mapbox.com/geocoding/v5/mapbox.places/{0}.json' <NEW_LINE> _RESULT_CLASS = MapboxResult <NEW_LINE> _KEY = mapbox_access_token <NEW_LINE> def _build_params(self, location, provider_key, **kwargs): <NEW_LINE> <INDENT> base_params = { 'access_token': provider_key, 'country': kwargs.get('country'), 'types': kwargs.get('types'), } <NEW_LINE> proximity = kwargs.get('proximity', None) <NEW_LINE> if proximity is not None: <NEW_LINE> <INDENT> proximity = Location(proximity) <NEW_LINE> base_params['proximity'] = u'{longitude},{latitude}'.format( longitude=proximity.longitude, latitude=proximity.latitude ) <NEW_LINE> <DEDENT> bbox = kwargs.get('bbox') <NEW_LINE> if bbox: <NEW_LINE> <INDENT> bbox = BBox(bbox=bbox) <NEW_LINE> base_params['bbox'] = u'{west},{south},{east},{north}'.format( west=bbox.west, east=bbox.east, south=bbox.south, north=bbox.north ) <NEW_LINE> <DEDENT> return base_params <NEW_LINE> <DEDENT> def _before_initialize(self, location, **kwargs): <NEW_LINE> <INDENT> self.url = self.url.format(location) <NEW_LINE> <DEDENT> def _adapt_results(self, json_response): <NEW_LINE> <INDENT> return json_response.get('features', [])
Mapbox Geocoding ================ The Mapbox Geocoding API lets you convert location text into geographic coordinates (1600 Pennsylvania Ave NW → -77.0366,38.8971). API Reference ------------- https://www.mapbox.com/developers/api/geocoding/ Get Mapbox Access Token ----------------------- https://www.mapbox.com/account
62598fb7fff4ab517ebcd8f4
class HTTPException(BaseException): <NEW_LINE> <INDENT> code = 'N/A' <NEW_LINE> def __init__(self, message=None, code=None): <NEW_LINE> <INDENT> super(HTTPException, self).__init__(message) <NEW_LINE> try: <NEW_LINE> <INDENT> self.error = jsonutils.loads(message) <NEW_LINE> if 'error' not in self.error: <NEW_LINE> <INDENT> raise KeyError(_('Key "error" not exists')) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.error = {'error': {'message': self.__class__.__doc__}} <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.error = {'error': {'message': self.message or self.__class__.__doc__}} <NEW_LINE> <DEDENT> if self.code == "N/A" and code is not None: <NEW_LINE> <INDENT> self.code = code <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> message = self.error['error'].get('message', 'Internal Error') <NEW_LINE> if verbose: <NEW_LINE> <INDENT> traceback = self.error['error'].get('traceback', '') <NEW_LINE> return (_('ERROR: %(message)s\n%(traceback)s') % {'message': message, 'traceback': traceback}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return _('ERROR: %s') % message
Base exception for all HTTP-derived exceptions.
62598fb77c178a314d78d5aa
class NoCsvError(RwrtrackException): <NEW_LINE> <INDENT> pass
Raised when there are no CSV files to migrate.
62598fb771ff763f4b5e7884
class IRCBot(SocketBot): <NEW_LINE> <INDENT> def __init__(self, host, port=6667, channel=None, nickname="ircbot", fullname="IRC Bot", *args, **kwargs): <NEW_LINE> <INDENT> super(IRCBot, self).__init__(host, port, *args, **kwargs) <NEW_LINE> if channel and not channel.startswith("#"): <NEW_LINE> <INDENT> channel = "#" + channel <NEW_LINE> <DEDENT> self.channel = channel <NEW_LINE> self.nickname = nickname <NEW_LINE> self.fullname = fullname <NEW_LINE> self.connect() <NEW_LINE> self.write("NICK {}".format(nickname)) <NEW_LINE> self.write("USER {} * * :{}".format(nickname, fullname)) <NEW_LINE> self.msg("nickserv", "iNOOPE") <NEW_LINE> self.join(channel) <NEW_LINE> <DEDENT> def close(self, exit=True): <NEW_LINE> <INDENT> self.write("QUIT :End of session") <NEW_LINE> super(IRCBot, self).close(exit) <NEW_LINE> <DEDENT> def join(self, channel=None): <NEW_LINE> <INDENT> channel = channel or self.channel <NEW_LINE> if channel is not None: <NEW_LINE> <INDENT> if not channel.startswith("#"): <NEW_LINE> <INDENT> channel = "#" + channel <NEW_LINE> <DEDENT> self.logger.debug("Joining channel {}...".format(channel)) <NEW_LINE> self.channel = channel <NEW_LINE> self.write("JOIN {}".format(channel)) <NEW_LINE> self.logger.debug("Handling PING if any...") <NEW_LINE> self.buffer = self.read() <NEW_LINE> if "PING " in self.buffer: <NEW_LINE> <INDENT> pong = self.buffer.split("PING ")[1].strip() <NEW_LINE> self.write("PING {}".format(pong), eol="\r\n") <NEW_LINE> self.buffer = self.read() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def msg(self, dest, msg): <NEW_LINE> <INDENT> self.write("PRIVMSG {} :{}".format(dest, msg), eol="\r\n") <NEW_LINE> <DEDENT> def read(self, length=1024, disp=None): <NEW_LINE> <INDENT> data = super(IRCBot, self).read(length, disp) <NEW_LINE> if "ERROR" in data: <NEW_LINE> <INDENT> self.logger.error(data.strip()) <NEW_LINE> self.close() <NEW_LINE> <DEDENT> return data
Internet Relay Chat bot. :param host: hostname or IP address :param port: port number :param channel: IRC channel :param nickname: bot's nickname :param fullname: bot's fullname :param disp: display all exchanged messages or not :param verbose: verbose mode or not :param prefix: prefix messages for display or not :param no_proxy: force ignoring the proxy Example usage: from pybots import IRCBot with IRCBot('127.0.0.1', channel="test") as bot: bot.msg("world", "Hello !")
62598fb756ac1b37e63022f9
class TestNodeStatusNvramNodeBattery(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 testNodeStatusNvramNodeBattery(self): <NEW_LINE> <INDENT> pass
NodeStatusNvramNodeBattery unit test stubs
62598fb756b00c62f0fb29c7
class NotificationStageName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> SHIPPED = "Shipped" <NEW_LINE> DELIVERED = "Delivered"
Name of the stage.
62598fb77047854f4633f4e3
class MediaRatios(object): <NEW_LINE> <INDENT> standard = 4.0 / 5.0, 90.0 / 47.0 <NEW_LINE> __device_ratios = [(3, 4), (2, 3), (5, 8), (3, 5), (9, 16), (10, 16), (40, 71)] <NEW_LINE> __aspect_ratios = [1.0 * x[0] / x[1] for x in __device_ratios] <NEW_LINE> reel = min(__aspect_ratios), max(__aspect_ratios)
Class holding valid aspect ratios (width: height) for media uploads.
62598fb78e7ae83300ee91ad
class SparseGPLVM(SparseGPRegression, GPLVM): <NEW_LINE> <INDENT> def __init__(self, Y, input_dim, kernel=None, init='PCA', num_inducing=10): <NEW_LINE> <INDENT> X = self.initialise_latent(init, input_dim, Y) <NEW_LINE> SparseGPRegression.__init__(self, X, Y, kernel=kernel, num_inducing=num_inducing) <NEW_LINE> <DEDENT> def _get_param_names(self): <NEW_LINE> <INDENT> return (sum([['X_%i_%i' % (n, q) for q in range(self.input_dim)] for n in range(self.num_data)], []) + SparseGPRegression._get_param_names(self)) <NEW_LINE> <DEDENT> def _get_params(self): <NEW_LINE> <INDENT> return np.hstack((self.X.flatten(), SparseGPRegression._get_params(self))) <NEW_LINE> <DEDENT> def _set_params(self, x): <NEW_LINE> <INDENT> self.X = x[:self.X.size].reshape(self.num_data, self.input_dim).copy() <NEW_LINE> SparseGPRegression._set_params(self, x[self.X.size:]) <NEW_LINE> <DEDENT> def log_likelihood(self): <NEW_LINE> <INDENT> return SparseGPRegression.log_likelihood(self) <NEW_LINE> <DEDENT> def dL_dX(self): <NEW_LINE> <INDENT> dL_dX = self.kern.dKdiag_dX(self.dL_dpsi0, self.X) <NEW_LINE> dL_dX += self.kern.dK_dX(self.dL_dpsi1, self.X, self.Z) <NEW_LINE> return dL_dX <NEW_LINE> <DEDENT> def _log_likelihood_gradients(self): <NEW_LINE> <INDENT> return np.hstack((self.dL_dX().flatten(), SparseGPRegression._log_likelihood_gradients(self))) <NEW_LINE> <DEDENT> def plot(self): <NEW_LINE> <INDENT> GPLVM.plot(self) <NEW_LINE> mu, var, upper, lower = SparseGPRegression.predict(self, self.Z + np.random.randn(*self.Z.shape) * 0.0001) <NEW_LINE> pb.plot(mu[:, 0] , mu[:, 1], 'ko') <NEW_LINE> <DEDENT> def plot_latent(self, *args, **kwargs): <NEW_LINE> <INDENT> input_1, input_2 = GPLVM.plot_latent(*args, **kwargs) <NEW_LINE> pb.plot(m.Z[:, input_1], m.Z[:, input_2], '^w')
Sparse Gaussian Process Latent Variable Model :param Y: observed data :type Y: np.ndarray :param input_dim: latent dimensionality :type input_dim: int :param init: initialisation method for the latent space :type init: 'PCA'|'random'
62598fb7851cf427c66b83c4
class AnalyticLineValidator(orm.TransientModel): <NEW_LINE> <INDENT> _name = 'analytic.line.validator' <NEW_LINE> def action_confirm(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> import pdb <NEW_LINE> pdb.set_trace() <NEW_LINE> aa_line_ids = context.get('active_ids', []) <NEW_LINE> return self.pool['account.analytic.line'].action_confirm( cr, uid, aa_line_ids, context=context) <NEW_LINE> <DEDENT> def action_reset_to_draft(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> import pdb <NEW_LINE> pdb.set_trace() <NEW_LINE> aa_line_ids = context.get('active_ids', []) <NEW_LINE> return self.pool['account.analytic.line'].action_reset_to_draft( cr, uid, aa_line_ids, context=context)
This wizard allows to change state for massive amount of analytic AnalyticLineValidator
62598fb7a05bb46b3848a979
class TicketFile(Base): <NEW_LINE> <INDENT> __tablename__ = 'tickets_files' <NEW_LINE> __table_args__ = ( Comment('File mappings to tickets'), Index('tickets_files_u_tfl', 'ticketid', 'fileid', unique=True), Index('tickets_files_i_fileid', 'fileid'), { 'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8', 'info': { 'cap_menu': 'BASE_TICKETS', 'cap_read': 'TICKETS_LIST', 'cap_create': 'FILES_ATTACH_2TICKETS', 'cap_edit': '__NOPRIV__', 'cap_delete': 'FILES_ATTACH_2TICKETS', 'menu_name': _('Files'), 'grid_view': ('tfid', 'ticket', 'file'), 'grid_hidden': ('tfid',), 'create_wizard': SimpleWizard(title=_('Attach file')) } }) <NEW_LINE> id = Column( 'tfid', UInt32(), Sequence('tickets_files_tfid_seq'), Comment('Ticket-file mapping ID'), primary_key=True, nullable=False, info={ 'header_string': _('ID') }) <NEW_LINE> ticket_id = Column( 'ticketid', UInt32(), ForeignKey('tickets_def.ticketid', name='tickets_files_fk_ticketid', ondelete='CASCADE', onupdate='CASCADE'), Comment('Ticket ID'), nullable=False, info={ 'header_string': _('Ticket'), 'column_flex': 1 }) <NEW_LINE> file_id = Column( 'fileid', UInt32(), ForeignKey('files_def.fileid', name='tickets_files_fk_fileid', ondelete='CASCADE', onupdate='CASCADE'), Comment('File ID'), nullable=False, info={ 'header_string': _('File'), 'column_flex': 1, 'editor_xtype': 'fileselect' }) <NEW_LINE> file = relationship( 'File', innerjoin=True, backref=backref('linked_tickets', cascade='all, delete-orphan', passive_deletes=True)) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.file)
Many-to-many relationship object. Links tickets and files from VFS.
62598fb799cbb53fe6830fe4
class Order(Option): <NEW_LINE> <INDENT> __metaclass__ = OptionType <NEW_LINE> option = 'order' <NEW_LINE> requires = [] <NEW_LINE> excludes = [] <NEW_LINE> @classmethod <NEW_LINE> def default(cls): <NEW_LINE> <INDENT> return sympy.polys.orderings.lex <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def preprocess(cls, order): <NEW_LINE> <INDENT> return sympy.polys.orderings.monomial_key(order)
``order`` option to polynomial manipulation functions.
62598fb73d592f4c4edbafcf
class ClasseFonction(Fonction): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def init_types(cls): <NEW_LINE> <INDENT> cls.ajouter_types(cls.est_allume, "Objet") <NEW_LINE> cls.ajouter_types(cls.prototype_est_allume, "PrototypeObjet") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def est_allume(objet): <NEW_LINE> <INDENT> if not objet.est_de_type("lumière"): <NEW_LINE> <INDENT> raise ErreurExecution("L'objet {} n'est pas une lumière.".format( objet.identifiant)) <NEW_LINE> <DEDENT> return objet.allumee_depuis is not None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def prototype_est_allume(prototype): <NEW_LINE> <INDENT> return False
Retourne vrai si est allumé.
62598fb73317a56b869be5d4
class InvalidBundleError(BundleError): <NEW_LINE> <INDENT> pass
Raised when the bundle (.xo) is not a valid packaged bundle
62598fb7adb09d7d5dc0a69c
class NonTerminalOp(Operation): <NEW_LINE> <INDENT> is_block_terminal = False <NEW_LINE> @property <NEW_LINE> def dwarfname(self): <NEW_LINE> <INDENT> return self.ast.tokens[0].text
Base class for all operations that don't terminate basic blocks.
62598fb77d847024c075c4ca
class Receipt(object): <NEW_LINE> <INDENT> _date_format = '%Y-%m-%d' <NEW_LINE> def __init__(self, vat, price, when): <NEW_LINE> <INDENT> self.vat = Vat(vat) <NEW_LINE> self.price = Price(price) <NEW_LINE> self.date = self._date_from_string(when) <NEW_LINE> self._pk = None <NEW_LINE> <DEDENT> def _date_from_string(self, when): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return date.fromtimestamp( time.mktime(time.strptime(when, self._date_format)) ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> msg = "Wrong date value passed: %s. Correct format is YYYY-MM-DD." <NEW_LINE> logger.error(msg % when, exc_info=True) <NEW_LINE> raise TypeError(unicode(e)) <NEW_LINE> <DEDENT> <DEDENT> def _db_values(self): <NEW_LINE> <INDENT> return [self.vat, self.price, self.date, ] <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> if self._pk is None: <NEW_LINE> <INDENT> insert_receipt(self)
Receipt type.
62598fb7f548e778e596b6b3
class QAObject: <NEW_LINE> <INDENT> def __init__(self, start_idx, end_idx, name, synset): <NEW_LINE> <INDENT> self.start_idx = start_idx <NEW_LINE> self.end_idx = end_idx <NEW_LINE> self.name = name <NEW_LINE> self.synset = synset <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self)
Question Answer Objects are localized in the image and refer to a part of the question text or the answer text. start_idx int end_idx int name string synset_name string synset_definition string
62598fb7498bea3a75a57c30
class Solution: <NEW_LINE> <INDENT> def twoSumClosest(self, nums, target): <NEW_LINE> <INDENT> diff = float('inf') <NEW_LINE> nums.sort() <NEW_LINE> left, right = 0, len(nums) - 1 <NEW_LINE> while left < right: <NEW_LINE> <INDENT> total = nums[left] + nums[right] <NEW_LINE> if total == target: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif total > target: <NEW_LINE> <INDENT> right -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> left += 1 <NEW_LINE> <DEDENT> diff = min(diff, abs(target - total)) <NEW_LINE> <DEDENT> return diff
@param: nums: an integer array @param: target: An integer @return: the difference between the sum and the target
62598fb7236d856c2adc94c7
class GamificationPublisher(object): <NEW_LINE> <INDENT> def publish_event(self, event): <NEW_LINE> <INDENT> publish_event_to_gamma(params, event, settings.GAMMA_FIRST_SLEEP_INTERVAL)
Gamification publisher. Work with Gamma default storage to interact with storage backend.
62598fb79c8ee823130401fb
class NullBooleanSelectForm(forms.Form, BaseFormFieldPluginForm): <NEW_LINE> <INDENT> plugin_data_fields = [ ("label", ""), ("name", ""), ("help_text", ""), ("initial", ""), ("required", False) ] <NEW_LINE> label = forms.CharField( label=_("Label"), required=True, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class} ) ) <NEW_LINE> name = forms.CharField( label=_("Name"), required=True, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class} ) ) <NEW_LINE> help_text = forms.CharField( label=_("Help text"), required=False, widget=forms.widgets.Textarea( attrs={'class': theme.form_element_html_class} ) ) <NEW_LINE> initial = forms.NullBooleanField( label=_("Initial"), required=False, widget=forms.widgets.NullBooleanSelect( attrs={'class': theme.form_element_checkbox_html_class} ) ) <NEW_LINE> required = forms.BooleanField( label=_("Required"), required=False, widget=forms.widgets.CheckboxInput( attrs={'class': theme.form_element_checkbox_html_class} ) )
Form for ``NullBooleanSelectPlugin``.
62598fb7a17c0f6771d5c346
class Task(TimeStampedModel): <NEW_LINE> <INDENT> task_name = models.CharField(max_length=50) <NEW_LINE> task_description = models.TextField(max_length=3000, blank=True) <NEW_LINE> topic = models.ForeignKey(Topic, on_delete=models.CASCADE) <NEW_LINE> NOT_IMPORTANT = 0 <NEW_LINE> LESS_IMPORTANT = 1 <NEW_LINE> IMPORTANT = 2 <NEW_LINE> VERY_IMPORTANT = 3 <NEW_LINE> IMPORTANCE_OPTIONS = ( (NOT_IMPORTANT, 'not important'), (LESS_IMPORTANT, 'less important'), (IMPORTANT, 'important'), (VERY_IMPORTANT, 'very important'), ) <NEW_LINE> importance = models.IntegerField( choices=IMPORTANCE_OPTIONS, default=LESS_IMPORTANT ) <NEW_LINE> due_date = models.DateTimeField(auto_now=False, auto_now_add=False) <NEW_LINE> done = models.BooleanField(default=False) <NEW_LINE> duration = models.FloatField(blank=True, null=False, default=1) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.task_name <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('matrix:tasks', kwargs={'task_id': self.pk})
define model Task. Fremdschluessel: Topic: Topic Name: String (max=50) Beschreibung: String (max=3000) Wichtigkeit: String Due Date Erledigt Duration
62598fb71b99ca400228f5b8
class IActivityRecordRemovedEvent(IActivityRecordEvent): <NEW_LINE> <INDENT> pass
record removed
62598fb72ae34c7f260ab1ec
class UserTicketsApiView(APIView): <NEW_LINE> <INDENT> authentication_classes = (authentication.TokenAuthentication,) <NEW_LINE> permission_classes = (permissions.IsAuthenticated,) <NEW_LINE> def get(self, request): <NEW_LINE> <INDENT> tickets = Ticket.objects.filter(Q(reporter=request.user) | Q(assignee=request.user)) <NEW_LINE> serializer = TicketSerializer(tickets, many=True) <NEW_LINE> return Response(serializer.data)
get: Returns all the Tickets where user is a 'reporter' or 'assignee'.
62598fb75fcc89381b2661d4
class MTAPI: <NEW_LINE> <INDENT> def __init__(self, sock): <NEW_LINE> <INDENT> self.sock = sock <NEW_LINE> self.state = self.read_sof <NEW_LINE> <DEDENT> def read_sof(self): <NEW_LINE> <INDENT> byte = self.sock.read(1) <NEW_LINE> if len(byte) == 1 and byte[0] == 0xfe: <NEW_LINE> <INDENT> self.state = self.read_len <NEW_LINE> <DEDENT> <DEDENT> def read_len(self): <NEW_LINE> <INDENT> byte = self.sock.read(3) <NEW_LINE> if len(byte) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.len = byte[0] <NEW_LINE> self.state = self.read_cmd0 <NEW_LINE> if len(byte) > 1: <NEW_LINE> <INDENT> self.read_cmd0(byte[1:]) <NEW_LINE> <DEDENT> <DEDENT> def read_cmd0(self, byte=None): <NEW_LINE> <INDENT> if byte is None: <NEW_LINE> <INDENT> byte = self.sock.read(2) <NEW_LINE> <DEDENT> if len(byte) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.type = MTAPIType(byte[0]) <NEW_LINE> self.subsystem = MTAPISubsystem(byte[0]) <NEW_LINE> self.state = self.read_cmd1 <NEW_LINE> if len(byte) > 1: <NEW_LINE> <INDENT> self.read_cmd1(byte[1:]) <NEW_LINE> <DEDENT> <DEDENT> def read_cmd1(self, byte=None): <NEW_LINE> <INDENT> if byte is None: <NEW_LINE> <INDENT> byte = self.sock.read(1) <NEW_LINE> <DEDENT> if len(byte) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.cmd = byte[0] <NEW_LINE> self.data = bytes(0) <NEW_LINE> if self.len > 0: <NEW_LINE> <INDENT> self.bytes_to_read = self.len <NEW_LINE> self.state = self.read_data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.state = self.read_sof <NEW_LINE> self.execute() <NEW_LINE> <DEDENT> <DEDENT> def read_data(self): <NEW_LINE> <INDENT> bytestream = self.sock.read(self.bytes_to_read) <NEW_LINE> if len(bytestream) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.bytes_to_read -= len(bytestream) <NEW_LINE> self.data = self.data + bytestream <NEW_LINE> if self.bytes_to_read == 0: <NEW_LINE> <INDENT> self.state = self.read_sof <NEW_LINE> self.execute() <NEW_LINE> <DEDENT> <DEDENT> def execute(self): <NEW_LINE> <INDENT> print(self.type, self.subsystem, "Cmd = %02x" % self.cmd) <NEW_LINE> key = (str(self.type), str(self.subsystem)) <NEW_LINE> if key in MT_COMMANDS: <NEW_LINE> <INDENT> command_table = MT_COMMANDS[key] <NEW_LINE> if self.cmd in command_table: <NEW_LINE> <INDENT> command = command_table[self.cmd] <NEW_LINE> print(" ", command.name) <NEW_LINE> offset = command(self.data) <NEW_LINE> if offset != len(self.data): <NEW_LINE> <INDENT> raise ParseError("Unparsed data in " + command.name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.data = None <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> self.state() <NEW_LINE> return True
State machine for managing serial comms reception from a device talking the MTAPI protocols.
62598fb776e4537e8c3ef6b6
class Describe(base.Command): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> parser.add_argument('id', help='The ID of the reference to be described.') <NEW_LINE> <DEDENT> @genomics_util.ReraiseHttpException <NEW_LINE> def Run(self, args): <NEW_LINE> <INDENT> apitools_client = self.context[lib.GENOMICS_APITOOLS_CLIENT_KEY] <NEW_LINE> genomics_messages = self.context[lib.GENOMICS_MESSAGES_MODULE_KEY] <NEW_LINE> request = genomics_messages.GenomicsReferencesGetRequest( referenceId=args.id, ) <NEW_LINE> return apitools_client.references.Get(request) <NEW_LINE> <DEDENT> def Display(self, args_unused, reference): <NEW_LINE> <INDENT> self.format(reference)
Returns details about a reference.
62598fb799fddb7c1ca62e73
class Menu(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=32) <NEW_LINE> url_type_choice = ((1,'alias'), (2,'abslute_url'),) <NEW_LINE> url_type = models.SmallIntegerField(choices=url_type_choice,default=2) <NEW_LINE> url_name = models.CharField(max_length=64) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = '菜单表' <NEW_LINE> verbose_name_plural = '菜单表'
菜单
62598fb7adb09d7d5dc0a69e
class LogMessage(Base): <NEW_LINE> <INDENT> __tablename__ = 'log_once' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> md5sum = Column(String) <NEW_LINE> added = Column(DateTime, default=datetime.now()) <NEW_LINE> def __init__(self, md5sum): <NEW_LINE> <INDENT> self.md5sum = md5sum <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<LogMessage('%s')>" % (self.md5sum)
Declarative
62598fb7f9cc0f698b1c5354
class PackageAvailability(NotContainerizedMixin, OpenShiftCheck): <NEW_LINE> <INDENT> name = "package_availability" <NEW_LINE> tags = ["preflight"] <NEW_LINE> def run(self, tmp, task_vars): <NEW_LINE> <INDENT> rpm_prefix = get_var(task_vars, "openshift", "common", "service_type") <NEW_LINE> group_names = get_var(task_vars, "group_names", default=[]) <NEW_LINE> packages = set() <NEW_LINE> if "masters" in group_names: <NEW_LINE> <INDENT> packages.update(self.master_packages(rpm_prefix)) <NEW_LINE> <DEDENT> if "nodes" in group_names: <NEW_LINE> <INDENT> packages.update(self.node_packages(rpm_prefix)) <NEW_LINE> <DEDENT> args = {"packages": sorted(set(packages))} <NEW_LINE> return self.module_executor("check_yum_update", args, tmp, task_vars) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def master_packages(rpm_prefix): <NEW_LINE> <INDENT> return [ "{rpm_prefix}".format(rpm_prefix=rpm_prefix), "{rpm_prefix}-clients".format(rpm_prefix=rpm_prefix), "{rpm_prefix}-master".format(rpm_prefix=rpm_prefix), "bash-completion", "cockpit-bridge", "cockpit-docker", "cockpit-kubernetes", "cockpit-shell", "cockpit-ws", "etcd", "httpd-tools", ] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def node_packages(rpm_prefix): <NEW_LINE> <INDENT> return [ "{rpm_prefix}".format(rpm_prefix=rpm_prefix), "{rpm_prefix}-node".format(rpm_prefix=rpm_prefix), "{rpm_prefix}-sdn-ovs".format(rpm_prefix=rpm_prefix), "bind", "ceph-common", "dnsmasq", "docker", "firewalld", "flannel", "glusterfs-fuse", "iptables-services", "iptables", "iscsi-initiator-utils", "libselinux-python", "nfs-utils", "ntp", "openssl", "pyparted", "python-httplib2", "PyYAML", "yum-utils", ]
Check that required RPM packages are available.
62598fb766673b3332c304df
class Driver(object): <NEW_LINE> <INDENT> def __init__(self, transport, protocol=None, *args, **kw): <NEW_LINE> <INDENT> self._transport = transport <NEW_LINE> self._protocol = protocol or protocol_module.IEC60488() <NEW_LINE> super(Driver, self).__init__(*args, **kw) <NEW_LINE> <DEDENT> def _write(self, cmd, *datas): <NEW_LINE> <INDENT> cmd = Command(write=cmd) <NEW_LINE> cmd.write(self._transport, self._protocol, *datas) <NEW_LINE> <DEDENT> def _query(self, cmd, *datas): <NEW_LINE> <INDENT> cmd = Command(query=cmd) <NEW_LINE> return cmd.query(self._transport, self._protocol, *datas) <NEW_LINE> <DEDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> attr = object.__getattribute__(self, name) <NEW_LINE> if isinstance(attr, Command): <NEW_LINE> <INDENT> return attr.query(self._transport, self._protocol) <NEW_LINE> <DEDENT> return attr <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> attr = object.__getattribute__(self, name) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> object.__setattr__(self, name, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(attr, Command): <NEW_LINE> <INDENT> if (isinstance(value, collections.Sequence) and not isinstance(value, (str, bytes))): <NEW_LINE> <INDENT> attr.write(self._transport, self._protocol, *value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attr.write(self._transport, self._protocol, value) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> object.__setattr__(self, name, value)
Base class of all instruments. The Driver class applies some *magic* to simplify the Command interaction. Read access on :class:`~.Command` attributes is redirected to the :class:`Command.query`, write access to the :class:`Command.write` member function. :param transport: The transport object. :param protocol: The protocol object. If no protocol is given, a :class:`IEC60488` protocol is used as default.
62598fb797e22403b383b016
class CampaignStatistics(object): <NEW_LINE> <INDENT> swagger_types = { 'bounce_rate': 'float', 'click_rate': 'float', 'num_recipients': 'int', 'open_rate': 'float' } <NEW_LINE> attribute_map = { 'bounce_rate': 'bounce_rate', 'click_rate': 'click_rate', 'num_recipients': 'num_recipients', 'open_rate': 'open_rate' } <NEW_LINE> def __init__(self, bounce_rate=None, click_rate=None, num_recipients=None, open_rate=None): <NEW_LINE> <INDENT> self._bounce_rate = None <NEW_LINE> self._click_rate = None <NEW_LINE> self._num_recipients = None <NEW_LINE> self._open_rate = None <NEW_LINE> self.discriminator = None <NEW_LINE> if bounce_rate is not None: <NEW_LINE> <INDENT> self.bounce_rate = bounce_rate <NEW_LINE> <DEDENT> if click_rate is not None: <NEW_LINE> <INDENT> self.click_rate = click_rate <NEW_LINE> <DEDENT> if num_recipients is not None: <NEW_LINE> <INDENT> self.num_recipients = num_recipients <NEW_LINE> <DEDENT> if open_rate is not None: <NEW_LINE> <INDENT> self.open_rate = open_rate <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def bounce_rate(self): <NEW_LINE> <INDENT> return self._bounce_rate <NEW_LINE> <DEDENT> @bounce_rate.setter <NEW_LINE> def bounce_rate(self, bounce_rate): <NEW_LINE> <INDENT> self._bounce_rate = bounce_rate <NEW_LINE> <DEDENT> @property <NEW_LINE> def click_rate(self): <NEW_LINE> <INDENT> return self._click_rate <NEW_LINE> <DEDENT> @click_rate.setter <NEW_LINE> def click_rate(self, click_rate): <NEW_LINE> <INDENT> self._click_rate = click_rate <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_recipients(self): <NEW_LINE> <INDENT> return self._num_recipients <NEW_LINE> <DEDENT> @num_recipients.setter <NEW_LINE> def num_recipients(self, num_recipients): <NEW_LINE> <INDENT> self._num_recipients = num_recipients <NEW_LINE> <DEDENT> @property <NEW_LINE> def open_rate(self): <NEW_LINE> <INDENT> return self._open_rate <NEW_LINE> <DEDENT> @open_rate.setter <NEW_LINE> def open_rate(self, open_rate): <NEW_LINE> <INDENT> self._open_rate = open_rate <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <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> if issubclass(CampaignStatistics, 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, CampaignStatistics): <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
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fb74527f215b58e9fe7
class Fmow(base_dataset.MutliEnvironmentImageDataset): <NEW_LINE> <INDENT> _ALL_ENVIRONMENTS = ['train', 'val_id', 'val_ood', 'test_id', 'test_ood'] <NEW_LINE> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return 'fmow' <NEW_LINE> <DEDENT> def get_builder(self, name): <NEW_LINE> <INDENT> return fmow_builder.Fmow(data_dir='PATH_TO_DATA') <NEW_LINE> <DEDENT> def set_static_dataset_configs(self): <NEW_LINE> <INDENT> self._channels = 3 <NEW_LINE> train_splits = {} <NEW_LINE> for env in self.train_environments: <NEW_LINE> <INDENT> train_splits[env] = f'{env}' <NEW_LINE> <DEDENT> test_splits = {} <NEW_LINE> valid_splits = {} <NEW_LINE> for env in self.eval_environments: <NEW_LINE> <INDENT> valid_splits[env] = f'{env}' <NEW_LINE> test_splits[env] = f'{env}' <NEW_LINE> <DEDENT> self._splits_dict = { 'train': train_splits, 'test': test_splits, 'validation': valid_splits } <NEW_LINE> self._crop_padding = 32 <NEW_LINE> self._mean_rgb = [0.485, 0.456, 0.406] <NEW_LINE> self._stddev_rgb = [0.229, 0.224, 0.225] <NEW_LINE> self.resolution = self.resolution or 224 <NEW_LINE> self.resize_mode = 'resize' <NEW_LINE> self.data_augmentations = self.data_augmentations or ['center_crop'] <NEW_LINE> self.teacher_data_augmentations = self.teacher_data_augmentations or [ 'center_crop' ] <NEW_LINE> self.eval_augmentations = ['center_crop'] <NEW_LINE> self.if_cache = True <NEW_LINE> <DEDENT> def get_tfds_env_name(self, name): <NEW_LINE> <INDENT> return name <NEW_LINE> <DEDENT> def get_tfds_ds_and_info(self, name, data_range): <NEW_LINE> <INDENT> del name <NEW_LINE> ds = self.builder.as_dataset(split=data_range) <NEW_LINE> return ds, self.builder.info <NEW_LINE> <DEDENT> def get_num_classes(self): <NEW_LINE> <INDENT> return self.builder.info.features['label'].num_classes
Data loader for FMoW.
62598fb7a219f33f346c6916
class Monster(LivingObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> LivingObject.__init__(self) <NEW_LINE> self.mDNA = random_beast() <NEW_LINE> self.parts = [] <NEW_LINE> self.rect = None <NEW_LINE> self.render() <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> d = self.mDNA.d <NEW_LINE> color = (200,200,200) <NEW_LINE> scratch = Surface((150, 150)) <NEW_LINE> s = Surface((150,150)) <NEW_LINE> s.lock() <NEW_LINE> body_rect = body(s, d, (40,40)) <NEW_LINE> if d["limbNum"] > 0: <NEW_LINE> <INDENT> limb_rect = limb(scratch, d, (0, 0)) <NEW_LINE> t = d["limbLocation"] <NEW_LINE> if t == 0: <NEW_LINE> <INDENT> x, y = body_rect.bottomleft <NEW_LINE> y -= body_rect.height / 4 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x, y = body_rect.midleft <NEW_LINE> <DEDENT> dx = body_rect.width / d["limbNum"] <NEW_LINE> for i in range(0, d["limbNum"]): <NEW_LINE> <INDENT> limb_rect = limb(s, d, (x, y)) <NEW_LINE> x += dx <NEW_LINE> <DEDENT> <DEDENT> t = d["headLocation"] <NEW_LINE> if t == 0: <NEW_LINE> <INDENT> x, y = body_rect.midleft <NEW_LINE> <DEDENT> elif t == 1: <NEW_LINE> <INDENT> x, y = body_rect.topleft <NEW_LINE> y -= body_rect.height / 4 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x, y = body_rect.topleft <NEW_LINE> <DEDENT> head_rect = head(s, d, (x, y)) <NEW_LINE> x, y = head_rect.center <NEW_LINE> y = y + head_rect.height / 6 <NEW_LINE> mouth_rect = mouth(s, d, (x, y)) <NEW_LINE> t = d["eyeLocation"] <NEW_LINE> if t == 0: <NEW_LINE> <INDENT> x, y = head_rect.center <NEW_LINE> y -= head_rect.height / 4 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x, y = head_rect.topleft <NEW_LINE> <DEDENT> for i in range(0, d["eyeNum"]): <NEW_LINE> <INDENT> eye = MonsterEye(d) <NEW_LINE> eye.rect.center = (x, y) <NEW_LINE> eye.render() <NEW_LINE> self.parts.append(eye) <NEW_LINE> x += (d["eyeSkill"] + 1) * 5 <NEW_LINE> <DEDENT> s.unlock() <NEW_LINE> [ s.blit(part.image, part.rect) for part in self.parts ] <NEW_LINE> self.image = s <NEW_LINE> self.rect = s.get_rect()
this is a monster.
62598fb757b8e32f525081a5
class NcbiDownload: <NEW_LINE> <INDENT> def __init__(self, ftp_path, outdir): <NEW_LINE> <INDENT> self.ftp_dir = ftp_path <NEW_LINE> self.outdir = outdir <NEW_LINE> self.gbff = None <NEW_LINE> self.checksum_file = self.outdir + '/md5checksums.txt' <NEW_LINE> <DEDENT> def unzip_gbff(self): <NEW_LINE> <INDENT> call(['gunzip', self.gbff]) <NEW_LINE> self.gbff = self.gbff.replace('.gbff.gz', '.gbff') <NEW_LINE> <DEDENT> def download(self, ftp, all_files=True): <NEW_LINE> <INDENT> ftp.cwd(self.ftp_dir) <NEW_LINE> listing = [] <NEW_LINE> ftp.retrlines("LIST", listing.append) <NEW_LINE> call(['mkdir', '-p', self.outdir]) <NEW_LINE> for row in listing: <NEW_LINE> <INDENT> ncbi_filename = row.split(None, 8)[-1].lstrip().split(' ')[0] <NEW_LINE> if (all_files or ncbi_filename == 'md5checksums.txt' or ncbi_filename.endswith('gbff.gz')): <NEW_LINE> <INDENT> if 'assembly_structure' not in ncbi_filename: <NEW_LINE> <INDENT> local_file = self.outdir + '/' + ncbi_filename <NEW_LINE> with open(local_file, "wb") as lf: <NEW_LINE> <INDENT> ftp.retrbinary("RETR " + ncbi_filename, lf.write, 8*1024) <NEW_LINE> <DEDENT> if local_file.endswith('.gbff.gz'): <NEW_LINE> <INDENT> self.gbff = local_file
Files related to an ncbi genome assembly
62598fb74f6381625f19954a
class GscData: <NEW_LINE> <INDENT> def __init__(self, service_gsc): <NEW_LINE> <INDENT> self.service_gsc = service_gsc <NEW_LINE> self._siteUrl = None <NEW_LINE> <DEDENT> def list_sites(self) -> pd.DataFrame: <NEW_LINE> <INDENT> tmp = self.service_gsc.sites().list().execute() <NEW_LINE> if tmp.get('siteEntry'): <NEW_LINE> <INDENT> return pd.DataFrame(tmp['siteEntry']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("no site entried") <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> def search_analyics(self, url:str=None, start_date=None, end_date=None) -> pd.DataFrame: <NEW_LINE> <INDENT> if url is None: <NEW_LINE> <INDENT> url = self._siteUrl <NEW_LINE> <DEDENT> if start_date is None: <NEW_LINE> <INDENT> start_date = (pd.datetime.now() - pd.Timedelta(12, 'D')).strftime("%Y-%m-%d") <NEW_LINE> <DEDENT> if end_date is None: <NEW_LINE> <INDENT> end_date = (pd.datetime.now() - pd.Timedelta(5, 'D')).strftime("%Y-%m-%d") <NEW_LINE> <DEDENT> print(f"start_date:{start_date}, end_date:{end_date}") <NEW_LINE> date_range = pd.date_range( pd.to_datetime(start_date), pd.to_datetime(end_date), freq="D") <NEW_LINE> for day in date_range: <NEW_LINE> <INDENT> yield from self._search_analytics(url, day) <NEW_LINE> <DEDENT> <DEDENT> def _search_analytics(self, url, day): <NEW_LINE> <INDENT> d_list = ['query', 'page'] <NEW_LINE> row_limit = 25000 <NEW_LINE> body = { 'startDate': day.strftime("%Y-%m-%d"), 'endDate': day.strftime("%Y-%m-%d"), 'dimensions': d_list, 'rowLimit': row_limit } <NEW_LINE> response = (self.service_gsc.searchanalytics() .query(siteUrl=url, body=body).execute()) <NEW_LINE> print(f"get:{day}") <NEW_LINE> df = pd.io.json.json_normalize(response['rows']) <NEW_LINE> for i, d in enumerate(body['dimensions']): <NEW_LINE> <INDENT> df[d] = df['keys'].apply(lambda x: x[i]) <NEW_LINE> <DEDENT> df.drop(columns='keys', inplace=True) <NEW_LINE> df['date'] = day <NEW_LINE> yield df.rename(columns={'query':'q'})
Google Search Console reporter
62598fb756ac1b37e63022fe