code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Container(LatexObject, UserList): <NEW_LINE> <INDENT> def __init__(self, data=None, packages=None): <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> data = [] <NEW_LINE> <DEDENT> elif not isinstance(data, list): <NEW_LINE> <INDENT> data = [data] <NEW_LINE> <DEDENT> self.data = data <NEW_LINE> self.real_data = data <NEW_LINE> super().__init__(packages=packages) <NEW_LINE> <DEDENT> def dumps(self, **kwargs): <NEW_LINE> <INDENT> self._propagate_packages() <NEW_LINE> return dumps_list(self, **kwargs) <NEW_LINE> <DEDENT> def _propagate_packages(self): <NEW_LINE> <INDENT> for item in self.data: <NEW_LINE> <INDENT> if isinstance(item, LatexObject): <NEW_LINE> <INDENT> if isinstance(item, Container): <NEW_LINE> <INDENT> item._propagate_packages() <NEW_LINE> <DEDENT> for p in item.packages: <NEW_LINE> <INDENT> self.packages.add(p) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def dumps_packages(self): <NEW_LINE> <INDENT> self._propagate_packages() <NEW_LINE> return dumps_list(self.packages) <NEW_LINE> <DEDENT> @contextmanager <NEW_LINE> def create(self, child): <NEW_LINE> <INDENT> prev_data = self.data <NEW_LINE> self.data = child.data <NEW_LINE> yield child <NEW_LINE> self.data = prev_data <NEW_LINE> self.append(child) | A base class that groups multiple LaTeX classes.
This class should be subclassed when a LaTeX class has content that is
variable of variable length. It subclasses UserList, so it holds a list
of elements that can simply be accessed by using normal list functionality,
like indexing or appending.
:param data: LaTeX code or class instances
:param packages: :class:`pylatex.package.Package` instances
:type data: list
:type packages: list | 62598fad7d847024c075c3a9 |
class SettingsEditor(forms.BaseForm): <NEW_LINE> <INDENT> def __iter__(self): <NEW_LINE> <INDENT> for field in super(SettingsEditor, self).__iter__(): <NEW_LINE> <INDENT> yield self.specialize(field) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, name): <NEW_LINE> <INDENT> field = super(SettingsEditor, self).__getitem__(name) <NEW_LINE> return self.specialize(field) <NEW_LINE> <DEDENT> def specialize(self, field): <NEW_LINE> <INDENT> field.label = capfirst(field.label) <NEW_LINE> module_name, class_name, _ = RE_FIELD_NAME.match(field.name).groups() <NEW_LINE> app_label = self.apps[field.name] <NEW_LINE> field.module_name = app_label <NEW_LINE> if class_name: <NEW_LINE> <INDENT> model = apps.get_model(app_label, class_name) <NEW_LINE> if model: <NEW_LINE> <INDENT> class_name = model._meta.verbose_name <NEW_LINE> <DEDENT> <DEDENT> field.class_name = class_name <NEW_LINE> field.verbose_name = self.verbose_names[field.name] <NEW_LINE> return field | Base editor, from which customized forms are created | 62598fadcc0a2c111447aff7 |
class UserTester(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> conf.database_url = "sqlite://" <NEW_LINE> self.temp_config_folder = tempfile.mkdtemp() <NEW_LINE> self.temp_projects_folder = tempfile.mkdtemp() <NEW_LINE> os.environ["OYPROJECTMANAGER_PATH"] = self.temp_config_folder <NEW_LINE> os.environ[conf.repository_env_key] = self.temp_projects_folder <NEW_LINE> self.kwargs = { "name":"Test User", "initials":"tu", "email":"testuser@test.com", "active":True } <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> db.session = None <NEW_LINE> shutil.rmtree(self.temp_config_folder) <NEW_LINE> shutil.rmtree(self.temp_projects_folder) | tests the User class
| 62598fadf548e778e596b58a |
class itkNumericTraitsVUC1(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> __swig_destroy__ = _itkNumericTraitsPython.delete_itkNumericTraitsVUC1 <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> _itkNumericTraitsPython.itkNumericTraitsVUC1_swiginit(self,_itkNumericTraitsPython.new_itkNumericTraitsVUC1(*args)) <NEW_LINE> <DEDENT> def max(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVUC1_max() <NEW_LINE> <DEDENT> max = staticmethod(max) <NEW_LINE> def min(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVUC1_min() <NEW_LINE> <DEDENT> min = staticmethod(min) <NEW_LINE> def NonpositiveMin(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVUC1_NonpositiveMin() <NEW_LINE> <DEDENT> NonpositiveMin = staticmethod(NonpositiveMin) <NEW_LINE> def ZeroValue(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVUC1_ZeroValue() <NEW_LINE> <DEDENT> ZeroValue = staticmethod(ZeroValue) <NEW_LINE> def OneValue(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVUC1_OneValue() <NEW_LINE> <DEDENT> OneValue = staticmethod(OneValue) | Proxy of C++ itkNumericTraitsVUC1 class | 62598fad32920d7e50bc603a |
class TimelineArgs(rdf_structs.RDFProtoStruct): <NEW_LINE> <INDENT> protobuf = timeline_pb2.TimelineArgs <NEW_LINE> rdf_deps = [] | An RDF wrapper class for the timeline arguments message. | 62598fade5267d203ee6b8f0 |
class anisotropicsphericaldf(sphericaldf): <NEW_LINE> <INDENT> def __init__(self,pot=None,denspot=None,rmax=None, scale=None,ro=None,vo=None): <NEW_LINE> <INDENT> sphericaldf.__init__(self,pot=pot,denspot=denspot,rmax=rmax, scale=scale,ro=ro,vo=vo) | Superclass for anisotropic spherical distribution functions | 62598fad99cbb53fe6830ebe |
class ConditionAnd(TriggerBase): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.trigger_received = defaultdict(self.trigger_received_factory) <NEW_LINE> self.trigger_params = defaultdict(dict) <NEW_LINE> self.triggers = [] <NEW_LINE> for trigger in args: <NEW_LINE> <INDENT> if not isinstance(trigger, TriggerBase): <NEW_LINE> <INDENT> raise TypeError("All parameters must inherit from urban_journey.TriggerBase") <NEW_LINE> <DEDENT> if isinstance(trigger, ConditionAnd): <NEW_LINE> <INDENT> for tr in trigger.triggers: <NEW_LINE> <INDENT> self.add_trigger(tr) <NEW_LINE> tr.remove_activity(trigger) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.add_trigger(trigger) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_trigger(self, trigger): <NEW_LINE> <INDENT> self.triggers.append(trigger) <NEW_LINE> trigger.add_activity(self) <NEW_LINE> for trigger_received_instance in self.trigger_received: <NEW_LINE> <INDENT> trigger_received_instance[trigger] = False <NEW_LINE> <DEDENT> <DEDENT> def trigger_received_factory(self): <NEW_LINE> <INDENT> r = {} <NEW_LINE> for trigger in self.triggers: <NEW_LINE> <INDENT> r[trigger] = False <NEW_LINE> <DEDENT> return r <NEW_LINE> <DEDENT> def all_received(self, instance): <NEW_LINE> <INDENT> for _, value in self.trigger_received[instance].items(): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> async def trigger(self, senders, sender_params, instance, *args, **kwargs): <NEW_LINE> <INDENT> sender = senders[0] <NEW_LINE> trigger_received_instance = self.trigger_received[instance] <NEW_LINE> if sender not in trigger_received_instance: <NEW_LINE> <INDENT> if isinstance(sender, DescriptorInstance): <NEW_LINE> <INDENT> if sender.static_descriptor in trigger_received_instance: <NEW_LINE> <INDENT> trigger_received_instance.pop(sender.static_descriptor) <NEW_LINE> trigger_received_instance[sender] = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Received trigger from non registered trigger.") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Received trigger from non registered trigger.") <NEW_LINE> <DEDENT> <DEDENT> trigger_received_instance[sender] = True <NEW_LINE> trigger_params_instance = self.trigger_params[instance] <NEW_LINE> for param, value in sender_params.items(): <NEW_LINE> <INDENT> trigger_params_instance[param] = value <NEW_LINE> <DEDENT> if self.all_received(instance): <NEW_LINE> <INDENT> for activity in self._activities: <NEW_LINE> <INDENT> await activity.trigger([self] + senders, trigger_params_instance, instance, *args, **kwargs) <NEW_LINE> <DEDENT> for trigger in trigger_received_instance: <NEW_LINE> <INDENT> trigger_received_instance[trigger] = False <NEW_LINE> <DEDENT> trigger_params_instance.clear() | This class is a trigger that can be used to combine multiple triggers. It will
only trigger once all of the child triggers have triggered at least once.
:param *args: Child triggers that this trigger will wait for. | 62598fad38b623060ffa9080 |
class R1(object): <NEW_LINE> <INDENT> index = 1 | Register 1, stack pointer. | 62598fadf9cc0f698b1c52bc |
class ApplicationTypeUpdateParameters(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'tags': {'key': 'tags', 'type': '{str}'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationTypeUpdateParameters, self).__init__(**kwargs) <NEW_LINE> self.tags = kwargs.get('tags', None) | Application type update request.
:param tags: A set of tags. Application type update parameters.
:type tags: dict[str, str] | 62598fad4e4d56256637240c |
class CPE(OnePort): <NEW_LINE> <INDENT> def __init__(self, K, alpha=0.5, **kwargs): <NEW_LINE> <INDENT> self.kwargs = kwargs <NEW_LINE> self.args = (K, alpha) <NEW_LINE> K = cexpr(K) <NEW_LINE> alpha = cexpr(alpha) <NEW_LINE> self.K = K <NEW_LINE> self.alpha = alpha <NEW_LINE> self._Z = impedance(1 / (s ** alpha * K), causal=True) | Constant phase element
This has an impedance 1 / (s**alpha * K). When alpha == 0, the CPE is
equivalent to a resistor of resistance 1 / K. When alpha == 1, the CPE is
equivalent to a capacitor of capacitance K.
When alpha == 0.5 (default), the CPE is a Warburg element.
The phase of the impedance is -pi * alpha / 2.
Note, when alpha is non-integral, the impedance cannot be represented
as a rational function and so there are no poles or zeros. So
don't be suprised if Lcapy throws an occasional wobbly. | 62598fadd486a94d0ba2bfb4 |
class UnprocessableException(BaseException): <NEW_LINE> <INDENT> pass | request param is unprocessable | 62598fad32920d7e50bc603b |
class CredentialsError(Exception): <NEW_LINE> <INDENT> pass | Generic credentials error. | 62598fad2c8b7c6e89bd37ac |
class MiniEnumSymbol(MiniAst): <NEW_LINE> <INDENT> def __init__(self, enumType, enumValue, low, high): <NEW_LINE> <INDENT> self.enumType = enumType <NEW_LINE> self.enumValue = enumValue <NEW_LINE> super(MiniEnumSymbol, self).__init__(low, high) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "MiniEnumSymbols({0}, {1})".format(self.enumType, self.enumValue) <NEW_LINE> <DEDENT> def asExpr(self, state): <NEW_LINE> <INDENT> return Literal(state.avroTypeBuilder.makePlaceholder(jsonlib.dumps(self.enumType), state.avroTypeMemo), jsonlib.dumps(self.enumValue), self.pos) | Mini-AST element representing an enumeration symbol. | 62598fadd58c6744b42dc2ca |
class MyTicketsListFilter(SimpleListFilter): <NEW_LINE> <INDENT> title = 'Tickets' <NEW_LINE> parameter_name = 'my_tickets' <NEW_LINE> def lookups(self, request, model_admin): <NEW_LINE> <INDENT> return ( ('True', _("My Tickets")), ('False', _("All")), ) <NEW_LINE> <DEDENT> def queryset(self, request, queryset): <NEW_LINE> <INDENT> if self.value() == 'True': <NEW_LINE> <INDENT> return queryset.involved_by(request.user) <NEW_LINE> <DEDENT> <DEDENT> def choices(self, cl): <NEW_LINE> <INDENT> choices = iter(super(MyTicketsListFilter, self).choices(cl)) <NEW_LINE> next(choices) <NEW_LINE> return choices | Filter tickets by created_by according to request.user | 62598fad6e29344779b00642 |
class SMSCodeView(APIView): <NEW_LINE> <INDENT> def get(self, request, mobile): <NEW_LINE> <INDENT> redis_conn = get_redis_connection('verify_codes') <NEW_LINE> send_flag = redis_conn.get('send_flag_%s' % mobile) <NEW_LINE> if send_flag: <NEW_LINE> <INDENT> return Response({'message': '请求过于频繁'}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> sms_code = 123456 <NEW_LINE> print('123456') <NEW_LINE> pl = redis_conn.pipeline() <NEW_LINE> pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code) <NEW_LINE> pl.setex('send_flag_%s'% mobile, constants.SEND_SMS_CODE_INTERVAL, 1) <NEW_LINE> pl.execute() <NEW_LINE> sms_code_expire = constants.SMS_CODE_REDIS_EXPIRES // 60 <NEW_LINE> return Response({'message': 'OK'}) | smscode | 62598fad3346ee7daa33763b |
class Login(Handler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> return self.render("login.html") <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> username = self.request.get("username") <NEW_LINE> password = self.request.get("password") <NEW_LINE> user = User.login(username, password) <NEW_LINE> if user: <NEW_LINE> <INDENT> self.login(user) <NEW_LINE> return self.redirect("/welcome") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error_message = "Invalid login" <NEW_LINE> return self.render("login.html", error = error_message) | This class is a child of Handler and is for Login. | 62598fad97e22403b383aef4 |
class IterRelevantCIFLines(object): <NEW_LINE> <INDENT> def __init__(self, f): <NEW_LINE> <INDENT> self.f = f <NEW_LINE> self.cache = [] <NEW_LINE> self.in_comment = False <NEW_LINE> <DEDENT> def iter(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def rewind(self, line): <NEW_LINE> <INDENT> self.cache.append(line) <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if len(self.cache) == 0: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> line = self.f.next() <NEW_LINE> line = line[:line.find('#')].strip() <NEW_LINE> if self.in_comment: <NEW_LINE> <INDENT> if line == ';': <NEW_LINE> <INDENT> self.in_comment = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if line == ';': <NEW_LINE> <INDENT> self.in_comment = True <NEW_LINE> <DEDENT> elif len(line) > 0: <NEW_LINE> <INDENT> return line <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return self.cache.pop(-1) | A wrapper that reads lines from the CIF file.
Irrelevant lines are ignored and a rewind method is present such that
one can easily 'undo' a line read. | 62598fad167d2b6e312b6f59 |
class ProxyStatus(Enum): <NEW_LINE> <INDENT> disabled = None <NEW_LINE> enabled = None <NEW_LINE> def __init__(self, string): <NEW_LINE> <INDENT> Enum.__init__(string) | ``Proxy.ProxyStatus`` class Defines state of proxy
.. note::
This class represents an enumerated type in the interface language
definition. The class contains class attributes which represent the
values in the current version of the enumerated type. Newer versions of
the enumerated type may contain new values. To use new values of the
enumerated type in communication with a server that supports the newer
version of the API, you instantiate this class. See :ref:`enumerated
type description page <enumeration_description>`. | 62598fad1f5feb6acb162c06 |
class BrownPaperBagLight(LightEntity, RestoreEntity): <NEW_LINE> <INDENT> def __init__(self, light_address, gate: BpbGate): <NEW_LINE> <INDENT> self._gate = gate <NEW_LINE> self._light_id = light_address <NEW_LINE> self._state = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def light_id(self): <NEW_LINE> <INDENT> return self._light_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "myhomeserver1_" + self._light_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> async def async_turn_on(self, **kwargs) -> None: <NEW_LINE> <INDENT> self._state = await self._gate.turn_on_light(self._light_id) <NEW_LINE> <DEDENT> async def async_turn_off(self, **kwargs) -> None: <NEW_LINE> <INDENT> self._state = await self._gate.turn_off_light(self._light_id) <NEW_LINE> <DEDENT> async def async_update(self): <NEW_LINE> <INDENT> self._state = await self._gate.is_light_on(self._light_id) <NEW_LINE> <DEDENT> async def async_added_to_hass(self): <NEW_LINE> <INDENT> await super().async_added_to_hass() <NEW_LINE> state = await self.async_get_last_state() <NEW_LINE> if not state: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._state = state.state == "on" | Representation of an BrownPaperBag Light. | 62598fad851cf427c66b82a3 |
class FluxLimitFlatFileParser( FlatFileParser ): <NEW_LINE> <INDENT> def __init__( self, delimiter='\t', comment='#' ): <NEW_LINE> <INDENT> FlatFileParser.__init__( self, delimiter, comment ) <NEW_LINE> self.setHeader( ["Flux", "Lower", "Upper"] ) <NEW_LINE> self.noLimit = ['None'] <NEW_LINE> self.posInf = 1e3 <NEW_LINE> self.negInf = -1e3 <NEW_LINE> <DEDENT> def parse( self, fluxlimitfile ): <NEW_LINE> <INDENT> fluxLimit = FluxLimit() <NEW_LINE> lines = open( fluxlimitfile, 'r' ) <NEW_LINE> isHeader = True <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if not self.isComment( line ): <NEW_LINE> <INDENT> if isHeader: <NEW_LINE> <INDENT> self.checkHeader( line ) <NEW_LINE> isHeader = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d = self.parseTagedLine( line ) <NEW_LINE> lower = d["Lower"] <NEW_LINE> upper = d["Upper"] <NEW_LINE> if lower in self.noLimit: <NEW_LINE> <INDENT> lower = None <NEW_LINE> <DEDENT> elif self.negInf != None: <NEW_LINE> <INDENT> if float(lower) < self.negInf: <NEW_LINE> <INDENT> lower = None <NEW_LINE> <DEDENT> <DEDENT> if upper in self.noLimit: <NEW_LINE> <INDENT> upper = None <NEW_LINE> <DEDENT> elif self.posInf != None: <NEW_LINE> <INDENT> if float(upper) > self.posInf: <NEW_LINE> <INDENT> upper = None <NEW_LINE> <DEDENT> <DEDENT> fluxLimit[d["Flux"]] = ( lower, upper ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return fluxLimit | @summary: parser for reaction limit flat file | 62598fad4428ac0f6e65850c |
class InitializeOAuthResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_AuthorizationURL(self): <NEW_LINE> <INDENT> return self._output.get('AuthorizationURL', None) <NEW_LINE> <DEDENT> def get_OAuthTokenSecret(self): <NEW_LINE> <INDENT> return self._output.get('OAuthTokenSecret', None) <NEW_LINE> <DEDENT> def get_CallbackID(self): <NEW_LINE> <INDENT> return self._output.get('CallbackID', None) | A ResultSet with methods tailored to the values returned by the InitializeOAuth Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 62598fad460517430c432051 |
class PoolFull(PoolError): <NEW_LINE> <INDENT> pass | Raised when putting a resource when the pool is full.
| 62598fad8e7ae83300ee908a |
class Motor(Projectile): <NEW_LINE> <INDENT> accel: int <NEW_LINE> delay: int | A missile motor. | 62598fadf548e778e596b58c |
class WorkloadMetadataConfig(_messages.Message): <NEW_LINE> <INDENT> class NodeMetadataValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> UNSPECIFIED = 0 <NEW_LINE> SECURE = 1 <NEW_LINE> EXPOSE = 2 <NEW_LINE> <DEDENT> nodeMetadata = _messages.EnumField('NodeMetadataValueValuesEnum', 1) | WorkloadMetadataConfig defines the metadata configuration to expose to
workloads on the node pool.
Enums:
NodeMetadataValueValuesEnum: NodeMetadata is the configuration for if and
how to expose the node metadata to the workload running on the node.
Fields:
nodeMetadata: NodeMetadata is the configuration for if and how to expose
the node metadata to the workload running on the node. | 62598fad2c8b7c6e89bd37ad |
class OscMessage(object): <NEW_LINE> <INDENT> def __init__(self, dgram): <NEW_LINE> <INDENT> self._dgram = dgram <NEW_LINE> self.parameters = [] <NEW_LINE> self._parse_datagram() <NEW_LINE> <DEDENT> def _parse_datagram(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._address_regexp, index = osc_types.get_string(self._dgram, 0) <NEW_LINE> if not self._dgram[index:]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> type_tag, index = osc_types.get_string(self._dgram, index) <NEW_LINE> if type_tag.startswith(','): <NEW_LINE> <INDENT> type_tag = type_tag[1:] <NEW_LINE> <DEDENT> for param in type_tag: <NEW_LINE> <INDENT> if param == "i": <NEW_LINE> <INDENT> val, index = osc_types.get_int(self._dgram, index) <NEW_LINE> <DEDENT> elif param == "f": <NEW_LINE> <INDENT> val, index = osc_types.get_float(self._dgram, index) <NEW_LINE> <DEDENT> elif param == "s": <NEW_LINE> <INDENT> val, index = osc_types.get_string(self._dgram, index) <NEW_LINE> <DEDENT> elif param == "b": <NEW_LINE> <INDENT> val, index = osc_types.get_blob(self._dgram, index) <NEW_LINE> <DEDENT> elif param == "T": <NEW_LINE> <INDENT> val = True <NEW_LINE> <DEDENT> elif param == "F": <NEW_LINE> <INDENT> val = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.warning('Unhandled parameter type: {0}'.format(param)) <NEW_LINE> continue <NEW_LINE> <DEDENT> self.parameters.append(val) <NEW_LINE> <DEDENT> <DEDENT> except osc_types.ParseError as pe: <NEW_LINE> <INDENT> raise ParseError('Found incorrect datagram, ignoring it', pe) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def address(self): <NEW_LINE> <INDENT> return self._address_regexp <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def dgram_is_message(dgram): <NEW_LINE> <INDENT> return dgram.startswith(b'/') <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return len(self._dgram) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dgram(self): <NEW_LINE> <INDENT> return self._dgram <NEW_LINE> <DEDENT> @property <NEW_LINE> def params(self): <NEW_LINE> <INDENT> return list(self) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.parameters) | Representation of a parsed datagram representing an OSC message.
An OSC message consists of an OSC Address Pattern followed by an OSC
Type Tag String followed by zero or more OSC Arguments. | 62598fad23849d37ff85109c |
class RedditContentObject(RedditObject): <NEW_LINE> <INDENT> def __init__(self, reddit_session, name=None, json_dict=None, fetch=True, info_url=None): <NEW_LINE> <INDENT> if name is None and json_dict is None: <NEW_LINE> <INDENT> raise TypeError("Either the name or json dict is required.") <NEW_LINE> <DEDENT> if info_url: <NEW_LINE> <INDENT> self._info_url = info_url <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._info_url = urls["info"] <NEW_LINE> <DEDENT> self.reddit_session = reddit_session <NEW_LINE> self._populate(json_dict, fetch) <NEW_LINE> <DEDENT> def _populate(self, json_dict, fetch): <NEW_LINE> <INDENT> if json_dict is None: <NEW_LINE> <INDENT> if fetch: <NEW_LINE> <INDENT> json_dict = self._get_json_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> json_dict = {} <NEW_LINE> <DEDENT> <DEDENT> for name, value in json_dict.iteritems(): <NEW_LINE> <INDENT> setattr(self, name, value) <NEW_LINE> <DEDENT> self._populated = bool(json_dict) or fetch <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> retrievable_attrs = ("user", "modhash", "_request", "_request_json") <NEW_LINE> if attr in retrievable_attrs: <NEW_LINE> <INDENT> return getattr(self.reddit_session, attr) <NEW_LINE> <DEDENT> if not self._populated: <NEW_LINE> <INDENT> self._populate(None, True) <NEW_LINE> return getattr(self, attr) <NEW_LINE> <DEDENT> raise AttributeError("'{0}' object has no attribute '{1}'".format( self.__class__.__name__, attr)) <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> if name == "subreddit": <NEW_LINE> <INDENT> value = Subreddit(self.reddit_session, value, fetch=False) <NEW_LINE> <DEDENT> elif name == "redditor" or name == "author": <NEW_LINE> <INDENT> if value != '[deleted]': <NEW_LINE> <INDENT> value = Redditor(self.reddit_session, value, fetch=False) <NEW_LINE> <DEDENT> <DEDENT> object.__setattr__(self, name, value) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (type(self) == type(other) and self.content_id == other.content_id) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return (type(self) != type(other) or self.content_id != other.content_id) <NEW_LINE> <DEDENT> def _get_json_dict(self): <NEW_LINE> <INDENT> response = self._request_json(self._info_url, as_objects=False) <NEW_LINE> return response["data"] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_api_response(cls, reddit_session, json_dict): <NEW_LINE> <INDENT> return cls(reddit_session, json_dict=json_dict) <NEW_LINE> <DEDENT> @property <NEW_LINE> def content_id(self): <NEW_LINE> <INDENT> return "_".join((self.kind, self.id)) | Base class for everything besides the Reddit class.
Represents actual reddit objects (Comment, Redditor, etc.). | 62598fade5267d203ee6b8f1 |
class BatchNorm3d(_BatchNorm): <NEW_LINE> <INDENT> def _check_input_dim(self, input): <NEW_LINE> <INDENT> if input.dim() != 5: <NEW_LINE> <INDENT> raise ValueError('expected 5D input (got {}D input)' .format(input.dim())) <NEW_LINE> <DEDENT> super(BatchNorm3d, self)._check_input_dim(input) | Applies Batch Normalization over a 5d input that is seen as a mini-batch of 4d inputs
.. math::
y = \frac{x - mean[x]}{ \sqrt{Var[x]} + \epsilon} * gamma + beta
The mean and standard-deviation are calculated per-dimension over
the mini-batches and gamma and beta are learnable parameter vectors
of size N (where N is the input size).
During training, this layer keeps a running estimate of its computed mean
and variance. The running sum is kept with a default momentum of 0.1.
During evaluation, this running mean/variance is used for normalization.
Args:
num_features: num_features from an expected input of size batch_size x num_features x height x width
eps: a value added to the denominator for numerical stability. Default: 1e-5
momentum: the value used for the running_mean and running_var computation. Default: 0.1
affine: a boolean value that when set to true, gives the layer learnable affine parameters.
Shape:
- Input: :math:`(N, C, D, H, W)`
- Output: :math:`(N, C, D, H, W)` (same shape as input)
Examples:
>>> # With Learnable Parameters
>>> m = nn.BatchNorm3d(100)
>>> # Without Learnable Parameters
>>> m = nn.BatchNorm3d(100, affine=False)
>>> input = autograd.Variable(torch.randn(20, 100, 35, 45, 10))
>>> output = m(input) | 62598fadb7558d5895463612 |
class NoInventory(Exception): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "The requested operation failed as no inventory is available." | When requesting nodes from Duffy and no inventory is available | 62598fade5267d203ee6b8f2 |
class CharBasedFoldDetector(FoldDetector): <NEW_LINE> <INDENT> def __init__(self, open_chars=('{'), close_chars=('}')): <NEW_LINE> <INDENT> super(CharBasedFoldDetector, self).__init__() <NEW_LINE> self.open_chars = open_chars <NEW_LINE> self.close_chars = close_chars <NEW_LINE> <DEDENT> def detect_fold_level(self, prev_block, block): <NEW_LINE> <INDENT> if prev_block: <NEW_LINE> <INDENT> prev_text = prev_block.text().strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prev_text = '' <NEW_LINE> <DEDENT> text = block.text().strip() <NEW_LINE> if text in self.open_chars: <NEW_LINE> <INDENT> return TextBlockHelper.get_fold_lvl(prev_block) + 1 <NEW_LINE> <DEDENT> if prev_text.endswith(self.open_chars) and prev_text not in self.open_chars: <NEW_LINE> <INDENT> return TextBlockHelper.get_fold_lvl(prev_block) + 1 <NEW_LINE> <DEDENT> if self.close_chars in prev_text: <NEW_LINE> <INDENT> return TextBlockHelper.get_fold_lvl(prev_block) - 1 <NEW_LINE> <DEDENT> return TextBlockHelper.get_fold_lvl(prev_block) | Fold detector based on trigger charachters (e.g. a { increase fold level
and } decrease fold level). | 62598fad32920d7e50bc603c |
class computechi2(object): <NEW_LINE> <INDENT> def __init__(self, bvec, sqivar, amatrix): <NEW_LINE> <INDENT> self.sqivar = sqivar <NEW_LINE> self.amatrix = amatrix <NEW_LINE> if len(amatrix.shape) > 1: <NEW_LINE> <INDENT> self.nstar = amatrix.shape[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nstar = 1 <NEW_LINE> <DEDENT> self.bvec = bvec * sqivar <NEW_LINE> self.mmatrix = self.amatrix * np.tile(sqivar, self.nstar).reshape( self.nstar, bvec.size).transpose() <NEW_LINE> mm = np.dot(self.mmatrix.T, self.mmatrix) <NEW_LINE> self.uu, self.ww, self.vv = svd(mm, full_matrices=False) <NEW_LINE> self.mmi = np.dot((self.vv.T / np.tile(self.ww, self.nstar).reshape( self.nstar, self.nstar)), self.uu.T) <NEW_LINE> return <NEW_LINE> <DEDENT> @au.lazyproperty <NEW_LINE> def acoeff(self): <NEW_LINE> <INDENT> return np.dot(self.mmi, np.dot(self.mmatrix.T, self.bvec)) <NEW_LINE> <DEDENT> @au.lazyproperty <NEW_LINE> def chi2(self): <NEW_LINE> <INDENT> return np.sum((np.dot(self.mmatrix, self.acoeff) - self.bvec)**2) <NEW_LINE> <DEDENT> @au.lazyproperty <NEW_LINE> def yfit(self): <NEW_LINE> <INDENT> return np.dot(self.amatrix, self.acoeff) <NEW_LINE> <DEDENT> @au.lazyproperty <NEW_LINE> def dof(self): <NEW_LINE> <INDENT> return (self.sqivar > 0).sum() - self.nstar <NEW_LINE> <DEDENT> @au.lazyproperty <NEW_LINE> def covar(self): <NEW_LINE> <INDENT> wwt = self.ww.copy() <NEW_LINE> wwt[self.ww > 0] = 1.0/self.ww[self.ww > 0] <NEW_LINE> covar = np.zeros((self.nstar, self.nstar), dtype=self.ww.dtype) <NEW_LINE> for i in range(self.nstar): <NEW_LINE> <INDENT> for j in range(i + 1): <NEW_LINE> <INDENT> covar[i, j] = np.sum(wwt * self.vv[:, i] * self.vv[:, j]) <NEW_LINE> covar[j, i] = covar[i, j] <NEW_LINE> <DEDENT> <DEDENT> return covar <NEW_LINE> <DEDENT> @au.lazyproperty <NEW_LINE> def var(self): <NEW_LINE> <INDENT> return np.diag(self.covar) | Solve the linear set of equations :math:`A x = b` using SVD.
The attributes of this class are all read-only properties, implemented
with :class:`~astropy.utils.decorators.lazyproperty`.
Parameters
----------
bvec : :class:`numpy.ndarray`
The :math:`b` vector in :math:`A x = b`. This vector has length
:math:`N`.
sqivar : :class:`numpy.ndarray`
The reciprocal of the errors in `bvec`. The name comes from the square
root of the inverse variance, which is what this is.
amatrix : :class:`numpy.ndarray`
The matrix :math:`A` in :math:`A x = b`.
The shape of this matrix is (:math:`N`, :math:`M`). | 62598fad7047854f4633f3c2 |
class I2c(_object): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, I2c, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, I2c, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, bus, raw=False): <NEW_LINE> <INDENT> this = _mraa.new_I2c(bus, raw) <NEW_LINE> try: <NEW_LINE> <INDENT> self.this.append(this) <NEW_LINE> <DEDENT> except __builtin__.Exception: <NEW_LINE> <INDENT> self.this = this <NEW_LINE> <DEDENT> <DEDENT> __swig_destroy__ = _mraa.delete_I2c <NEW_LINE> __del__ = lambda self: None <NEW_LINE> def frequency(self, mode): <NEW_LINE> <INDENT> return _mraa.I2c_frequency(self, mode) <NEW_LINE> <DEDENT> def address(self, address): <NEW_LINE> <INDENT> return _mraa.I2c_address(self, address) <NEW_LINE> <DEDENT> def readByte(self): <NEW_LINE> <INDENT> return _mraa.I2c_readByte(self) <NEW_LINE> <DEDENT> def read(self, data): <NEW_LINE> <INDENT> return _mraa.I2c_read(self, data) <NEW_LINE> <DEDENT> def readReg(self, reg): <NEW_LINE> <INDENT> return _mraa.I2c_readReg(self, reg) <NEW_LINE> <DEDENT> def readWordReg(self, reg): <NEW_LINE> <INDENT> return _mraa.I2c_readWordReg(self, reg) <NEW_LINE> <DEDENT> def readBytesReg(self, reg, data): <NEW_LINE> <INDENT> return _mraa.I2c_readBytesReg(self, reg, data) <NEW_LINE> <DEDENT> def writeByte(self, data): <NEW_LINE> <INDENT> return _mraa.I2c_writeByte(self, data) <NEW_LINE> <DEDENT> def write(self, data): <NEW_LINE> <INDENT> return _mraa.I2c_write(self, data) <NEW_LINE> <DEDENT> def writeReg(self, reg, data): <NEW_LINE> <INDENT> return _mraa.I2c_writeReg(self, reg, data) <NEW_LINE> <DEDENT> def writeWordReg(self, reg, data): <NEW_LINE> <INDENT> return _mraa.I2c_writeWordReg(self, reg, data) | API to Inter-Integrated Circuit.
An I2c object represents an i2c master and can talk multiple i2c
slaves by selecting the correct addressIt is considered best practice
to make sure the address is correct before doing any calls on i2c, in
case another application or even thread changed the addres on that
bus. Multiple instances of the same bus can exist.
C++ includes: i2c.hpp | 62598fadd486a94d0ba2bfb7 |
class Like(TimeStampedModel): <NEW_LINE> <INDENT> creator = models.ForeignKey(user_models.User, null=True) <NEW_LINE> image = models.ForeignKey(Image, null=True, related_name='likes') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return 'User: {} - Image Caption: {}'.format(self.creator.username, self.image.caption) | Like Model | 62598fadfff4ab517ebcd7ce |
class BettingMachine(object): <NEW_LINE> <INDENT> def prepareTicket(self, BettingTicket, UserSession, betList, currentBet): <NEW_LINE> <INDENT> BettingTicket.updateWinnerChoices(betList, currentBet) <NEW_LINE> BettingTicket.updateBetAmount(UserSession) <NEW_LINE> BettingTicket.updateOdds(UserSession) <NEW_LINE> BettingTicket.updateWinnings() <NEW_LINE> return BettingTicket <NEW_LINE> <DEDENT> def placeBet(self, BettingTicket, UserSession): <NEW_LINE> <INDENT> url = 'http://www.neopets.com/pirates/process_foodclub.phtml' <NEW_LINE> return UserSession.post(url, data=BettingTicket.formatTicket()) | Betting Machine for Neopets Food Club. | 62598fad4527f215b58e9ec9 |
class IContentTypeScopeProfileItem(zope.interface.Interface): <NEW_LINE> <INDENT> name = zope.schema.ASCII( title=_(u'Permitted Views'), description=_(u'List of views identified by their name that are ' 'permitted for this content type.'), required=False, ) | Fields for the scope profile edit form. This is for the individual
items. | 62598fad3539df3088ecc29b |
@_py3_str_compat <NEW_LINE> class StringTable: <NEW_LINE> <INDENT> def __init__(self, name=None, kids=None): <NEW_LINE> <INDENT> self.name = name or u'' <NEW_LINE> self.kids = kids or [] <NEW_LINE> <DEDENT> def fromRaw(self, data, i, limit): <NEW_LINE> <INDENT> i, (cpsublen, cpwValueLength, cpwType, self.name) = parseCodePage(data, i, limit) <NEW_LINE> i = nextDWord(i) <NEW_LINE> while i < limit: <NEW_LINE> <INDENT> ss = StringStruct() <NEW_LINE> j = ss.fromRaw(data, i, limit) <NEW_LINE> i = j <NEW_LINE> self.kids.append(ss) <NEW_LINE> i = nextDWord(i) <NEW_LINE> <DEDENT> return i <NEW_LINE> <DEDENT> def toRaw(self): <NEW_LINE> <INDENT> raw_name = getRaw(self.name) <NEW_LINE> vallen = 0 <NEW_LINE> typ = 1 <NEW_LINE> sublen = 6 + len(raw_name) + 2 <NEW_LINE> tmp = [] <NEW_LINE> for kid in self.kids: <NEW_LINE> <INDENT> raw = kid.toRaw() <NEW_LINE> if len(raw) % 4: <NEW_LINE> <INDENT> raw = raw + b'\000\000' <NEW_LINE> <DEDENT> tmp.append(raw) <NEW_LINE> <DEDENT> tmp = b''.join(tmp) <NEW_LINE> sublen += len(tmp) <NEW_LINE> return (struct.pack('hhh', sublen, vallen, typ) + raw_name + b'\000\000' + tmp) <NEW_LINE> <DEDENT> def __unicode__(self, indent=u''): <NEW_LINE> <INDENT> newindent = indent + u' ' <NEW_LINE> tmp = (u',\n%s' % newindent).join(u'%s' % (kid,) for kid in self.kids) <NEW_LINE> return (u"%sStringTable(\n%su'%s',\n%s[%s])" % (indent, newindent, self.name, newindent, tmp)) | WORD wLength;
WORD wValueLength;
WORD wType;
WCHAR szKey[];
String Children[]; // list of zero or more String structures. | 62598fad442bda511e95c440 |
class CapsuleLayer(layers.Layer): <NEW_LINE> <INDENT> def __init__(self, num_capsule, dim_capsule, routings=3, kernel_initializer='glorot_uniform', **kwargs): <NEW_LINE> <INDENT> super(CapsuleLayer, self).__init__(**kwargs) <NEW_LINE> self.num_capsule = num_capsule <NEW_LINE> self.dim_capsule = dim_capsule <NEW_LINE> self.routings = routings <NEW_LINE> self.kernel_initializer = initializers.get(kernel_initializer) <NEW_LINE> <DEDENT> def build(self, input_shape): <NEW_LINE> <INDENT> assert len(input_shape) >= 3, "The input Tensor should have shape=[None, input_num_capsule, input_dim_capsule]" <NEW_LINE> self.input_num_capsule = input_shape[1] <NEW_LINE> self.input_dim_capsule = input_shape[2] <NEW_LINE> self.W = self.add_weight(shape=[self.num_capsule, self.input_num_capsule, self.dim_capsule, self.input_dim_capsule], initializer=self.kernel_initializer, name='W') <NEW_LINE> self.built = True <NEW_LINE> <DEDENT> def call(self, inputs, training=None): <NEW_LINE> <INDENT> inputs_expand = K.expand_dims(inputs, 1) <NEW_LINE> inputs_tiled = K.tile(inputs_expand, [1, self.num_capsule, 1, 1]) <NEW_LINE> inputs_hat = K.map_fn(lambda x: K.batch_dot(x, self.W, [2, 3]), elems=inputs_tiled) <NEW_LINE> b = tf.zeros(shape=[K.shape(inputs_hat)[0], self.num_capsule, self.input_num_capsule]) <NEW_LINE> assert self.routings > 0, 'The routings should be > 0.' <NEW_LINE> for i in range(self.routings): <NEW_LINE> <INDENT> c = tf.nn.softmax(b, dim=1) <NEW_LINE> outputs = squash(K.batch_dot(c, inputs_hat, [2, 2])) <NEW_LINE> if i < self.routings - 1: <NEW_LINE> <INDENT> b += K.batch_dot(outputs, inputs_hat, [2, 3]) <NEW_LINE> <DEDENT> <DEDENT> return outputs <NEW_LINE> <DEDENT> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> return tuple([None, self.num_capsule, self.dim_capsule]) | :param num_capsule: number of capsules in this layer
:param dim_capsule: dimension of the output vectors of the capsules in this layer
:param routings: number of iterations for the routing algorithm | 62598fad63d6d428bbee2794 |
class Command(BaseCommand): <NEW_LINE> <INDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> buckets = {} <NEW_LINE> types = ['Actor', 'Campaign', 'Certificate', 'Domain', 'Email', 'Event', 'Indicator', 'IP', 'PCAP', 'RawData', 'Signature', 'Sample', 'Target'] <NEW_LINE> for otype in types: <NEW_LINE> <INDENT> klass = class_from_type(otype) <NEW_LINE> if not klass: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> objs = klass.objects().only('bucket_list') <NEW_LINE> for obj in objs: <NEW_LINE> <INDENT> for bucket in obj.bucket_list: <NEW_LINE> <INDENT> if not bucket: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if bucket not in buckets: <NEW_LINE> <INDENT> buckets[bucket] = Bucket() <NEW_LINE> buckets[bucket].name = bucket <NEW_LINE> setattr(buckets[bucket], otype, 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> buckets[bucket][otype] += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> Bucket.objects().delete() <NEW_LINE> for bucket in buckets.values(): <NEW_LINE> <INDENT> bucket.save() | Script Class. | 62598fad76e4537e8c3ef596 |
class OaipmhForm(Form): <NEW_LINE> <INDENT> baseurl=CharField(max_length=150,required=True, widget=TextInput(attrs={"placeholder":_("baseUrl"),"type":"text", "class":"form-control"})) | OAI-PMH bidez itemak datu-baseratzeko formularioa kargatzen du | 62598fadaad79263cf42e7bd |
class HasPriorityFilter(BaseFilter): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> BaseFilter.__init__(self, 'Priorities') <NEW_LINE> <DEDENT> def isMatch(self, task): <NEW_LINE> <INDENT> return task.priority | Task list filter allowing only tasks with a priority set | 62598fad97e22403b383aef6 |
class ContainerDevice(StorageDevice): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> _formatClassName = abc.abstractproperty(lambda s: None, doc="The type of member devices' required format") <NEW_LINE> _formatUUIDAttr = abc.abstractproperty(lambda s: None, doc="The container UUID attribute in the member format class") <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.formatClass = get_device_format_class(self._formatClassName) <NEW_LINE> if not self.formatClass: <NEW_LINE> <INDENT> raise errors.StorageError("cannot find '%s' class" % self._formatClassName) <NEW_LINE> <DEDENT> super(ContainerDevice, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def _addParent(self, member): <NEW_LINE> <INDENT> log_method_call(self, self.name, member=member.name) <NEW_LINE> if not isinstance(member.format, self.formatClass): <NEW_LINE> <INDENT> raise ValueError("member has wrong format") <NEW_LINE> <DEDENT> if member.format.exists and self.uuid and self._formatUUIDAttr and getattr(member.format, self._formatUUIDAttr) != self.uuid: <NEW_LINE> <INDENT> raise ValueError("cannot add member with mismatched UUID") <NEW_LINE> <DEDENT> super(ContainerDevice, self)._addParent(member) <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def _add(self, member): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def add(self, member): <NEW_LINE> <INDENT> if not self.exists: <NEW_LINE> <INDENT> raise errors.DeviceError("device has not been created", self.name) <NEW_LINE> <DEDENT> if member.format.exists and self.uuid and self._formatUUIDAttr and getattr(member.format, self._formatUUIDAttr) == self.uuid: <NEW_LINE> <INDENT> log.error("cannot re-add member: %s", member) <NEW_LINE> raise ValueError("cannot add members that are already part of the container") <NEW_LINE> <DEDENT> self._add(member) <NEW_LINE> if member not in self.parents: <NEW_LINE> <INDENT> self.parents.append(member) <NEW_LINE> <DEDENT> <DEDENT> @abc.abstractmethod <NEW_LINE> def _remove(self, member): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def remove(self, member): <NEW_LINE> <INDENT> log_method_call(self, self.name, status=self.status) <NEW_LINE> if not self.exists: <NEW_LINE> <INDENT> raise errors.DeviceError("device has not been created", self.name) <NEW_LINE> <DEDENT> if self._formatUUIDAttr and self.uuid and getattr(member.format, self._formatUUIDAttr) != self.uuid: <NEW_LINE> <INDENT> log.error("cannot remove non-member: %s (%s/%s)", member, getattr(member.format, self._formatUUIDAttr), self.uuid) <NEW_LINE> raise ValueError("cannot remove members that are not part of the container") <NEW_LINE> <DEDENT> self._remove(member) <NEW_LINE> if member in self.parents: <NEW_LINE> <INDENT> self.parents.remove(member) | A device that aggregates a set of member devices.
The only interfaces provided by this class are for addition and removal
of member devices -- one set for modifying the member set of the
python objects, and one for writing the changes to disk.
The member set of the instance can be manipulated using the methods
:meth:`~.ParentList.append` and :meth:`~.ParentList.remove` of the
instance's :attr:`~.Device.parents` attribute.
:meth:`add` and :meth:`remove` remove a member from the container's on-
disk representation. These methods should normally only be called from
within :meth:`.deviceaction.ActionAddMember.execute` and
:meth:`.deviceaction.ActionRemoveMember.execute`. | 62598fad5166f23b2e2433c2 |
class StandardPlotLogAnalyzer(StandardLogAnalyzer): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> StandardLogAnalyzer.__init__(self,progress=True,doTimelines=True,doFiles=False) | This analyzer checks the current residuals and generates timelines | 62598fad66673b3332c303b5 |
class NodeSlice(NodeOpr): <NEW_LINE> <INDENT> tag = 'Slice' <NEW_LINE> def __init__(self, indent, lineno, expr, flags, lower, upper): <NEW_LINE> <INDENT> Node.__init__(self, indent, lineno) <NEW_LINE> self.expr = transform(indent, lineno, expr) <NEW_LINE> self.flags = transform(indent, lineno, flags) <NEW_LINE> self.lower = transform(indent, lineno, lower) <NEW_LINE> self.upper = transform(indent, lineno, upper) <NEW_LINE> return <NEW_LINE> <DEDENT> def has_value(self, node): <NEW_LINE> <INDENT> return not (node is None or isinstance(node, NodeConst) and node.is_none()) <NEW_LINE> <DEDENT> def put(self, can_split=False): <NEW_LINE> <INDENT> is_del = self.flags.get_as_str() in ['OP_DELETE'] <NEW_LINE> if is_del: <NEW_LINE> <INDENT> self.line_init() <NEW_LINE> self.line_more('del ') <NEW_LINE> <DEDENT> if (isinstance(self.expr, NodeGetAttr) or isinstance(self.expr, NodeAsgAttr)): <NEW_LINE> <INDENT> self.expr.put(can_split=can_split) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.put_expr(self.expr, can_split=can_split) <NEW_LINE> <DEDENT> self.line_more('[') <NEW_LINE> if self.has_value(self.lower): <NEW_LINE> <INDENT> self.lower.put(can_split=True) <NEW_LINE> <DEDENT> self.line_more(SLICE_COLON) <NEW_LINE> if self.has_value(self.upper): <NEW_LINE> <INDENT> self.upper.put(can_split=True) <NEW_LINE> <DEDENT> self.line_more(']') <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> self.line_more(' /* Subscript flags: ') <NEW_LINE> self.flags.put() <NEW_LINE> self.line_more(' */ ') <NEW_LINE> <DEDENT> if is_del: <NEW_LINE> <INDENT> self.line_term() <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def make_local_name(self): <NEW_LINE> <INDENT> self.expr.make_local_name() <NEW_LINE> return self <NEW_LINE> <DEDENT> def get_hi_lineno(self): <NEW_LINE> <INDENT> lineno = Node.get_hi_lineno(self) <NEW_LINE> if self.has_value(self.lower): <NEW_LINE> <INDENT> lineno = self.lower.get_hi_lineno() <NEW_LINE> <DEDENT> if self.has_value(self.upper): <NEW_LINE> <INDENT> lineno = self.upper.get_hi_lineno() <NEW_LINE> <DEDENT> return lineno | A slice of a series.
| 62598fade1aae11d1e7ce818 |
class WorkflowSampleViewSet(viewsets.ModelViewSet, UpdateModelMixin): <NEW_LINE> <INDENT> serializer_class = serializers.WorkflowSampleSerializer <NEW_LINE> queryset = models.WorkflowSample.objects.all() <NEW_LINE> filter_backends = (filters.SearchFilter, DjangoFilterBackend,) <NEW_LINE> filterset_fields = { 'sample__sample_id': ['iexact'], 'sample__sample_name': ['iexact'], 'workflow_batch__status': ['iexact'] } <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> queryset = models.WorkflowSample.objects.all().order_by('-created') <NEW_LINE> return queryset | ViewSet for retrieving Sample objects from the database | 62598fad56b00c62f0fb289e |
class ClimateData(peewee.Model): <NEW_LINE> <INDENT> timestamp = peewee.DateTimeField() <NEW_LINE> temperature = peewee.IntegerField() <NEW_LINE> humidity = peewee.IntegerField() | ORM model of the ClimateData table | 62598fad283ffb24f3cf3876 |
class PreRes(tf.keras.layers.Layer): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(PreRes, self).__init__(**kwargs) <NEW_LINE> self.conv1 = tf.keras.layers.Conv2D(filters=64, kernel_size=(7, 7), strides=2, padding='same') <NEW_LINE> self.batch_norm = tf.keras.layers.BatchNormalization() <NEW_LINE> self.activate = tf.keras.layers.Activation(tf.keras.activations.relu) <NEW_LINE> self.max_pool = tf.keras.layers.MaxPool2D(pool_size=(3, 3), strides=2) <NEW_LINE> <DEDENT> def call(self, input_tensor, training=None): <NEW_LINE> <INDENT> x = self.conv1(input_tensor) <NEW_LINE> x = self.batch_norm(x) <NEW_LINE> x = self.activate(x) <NEW_LINE> x = self.max_pool(x) <NEW_LINE> return x | # Arguments
input: the tensor you want to pass through the layer
#### Usage: Use it as a keras layer, PreRes has all of the attributes of the Layer API.
#### Description: Conv2D --> BatchNormalization --> RelU --> MaxPool2D | 62598fadf548e778e596b58d |
class Case(ExpressionNode): <NEW_LINE> <INDENT> template = 'CASE %(cases)s ELSE %(default)s END' <NEW_LINE> case_joiner = ' ' <NEW_LINE> def __init__(self, *cases, **extra): <NEW_LINE> <INDENT> if not all(isinstance(case, When) for case in cases): <NEW_LINE> <INDENT> raise TypeError("Positional arguments must all be When objects.") <NEW_LINE> <DEDENT> default = extra.pop('default', None) <NEW_LINE> output_field = extra.pop('output_field', None) <NEW_LINE> super(Case, self).__init__(output_field) <NEW_LINE> self.cases = list(cases) <NEW_LINE> self.default = self._parse_expressions(default)[0] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "CASE %s, ELSE %r" % (', '.join(str(c) for c in self.cases), self.default) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<%s: %s>" % (self.__class__.__name__, self) <NEW_LINE> <DEDENT> def get_source_expressions(self): <NEW_LINE> <INDENT> return self.cases + [self.default] <NEW_LINE> <DEDENT> def set_source_expressions(self, exprs): <NEW_LINE> <INDENT> self.cases = exprs[:-1] <NEW_LINE> self.default = exprs[-1] <NEW_LINE> <DEDENT> def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): <NEW_LINE> <INDENT> c = self.copy() <NEW_LINE> c.is_summary = summarize <NEW_LINE> for pos, case in enumerate(c.cases): <NEW_LINE> <INDENT> c.cases[pos] = case.resolve_expression(query, allow_joins, reuse, summarize, for_save) <NEW_LINE> <DEDENT> c.default = c.default.resolve_expression(query, allow_joins, reuse, summarize, for_save) <NEW_LINE> return c <NEW_LINE> <DEDENT> def as_sql(self, compiler, connection, template=None, extra=None): <NEW_LINE> <INDENT> connection.ops.check_expression_support(self) <NEW_LINE> if not self.cases: <NEW_LINE> <INDENT> return compiler.compile(self.default) <NEW_LINE> <DEDENT> template_params = dict(extra) if extra else {} <NEW_LINE> case_parts = [] <NEW_LINE> sql_params = [] <NEW_LINE> for case in self.cases: <NEW_LINE> <INDENT> case_sql, case_params = compiler.compile(case) <NEW_LINE> case_parts.append(case_sql) <NEW_LINE> sql_params.extend(case_params) <NEW_LINE> <DEDENT> template_params['cases'] = self.case_joiner.join(case_parts) <NEW_LINE> default_sql, default_params = compiler.compile(self.default) <NEW_LINE> template_params['default'] = default_sql <NEW_LINE> sql_params.extend(default_params) <NEW_LINE> template = template or self.template <NEW_LINE> sql = template % template_params <NEW_LINE> if self._output_field_or_none is not None: <NEW_LINE> <INDENT> sql = connection.ops.unification_cast_sql(self.output_field) % sql <NEW_LINE> <DEDENT> return sql, sql_params | An SQL searched CASE expression:
CASE
WHEN n > 0
THEN 'positive'
WHEN n < 0
THEN 'negative'
ELSE 'zero'
END | 62598fadf7d966606f747fce |
class MockSys(object): <NEW_LINE> <INDENT> def __init__(self, current_version): <NEW_LINE> <INDENT> version_info = current_version.split(".") <NEW_LINE> version_info = map(int, version_info) <NEW_LINE> self.version = current_version + " Version details." <NEW_LINE> self.version_info = version_info | A mock sys module for passing to version-checking methods. | 62598fad851cf427c66b82a5 |
class Event(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._links = set() <NEW_LINE> self._todo = set() <NEW_LINE> self._flag = False <NEW_LINE> self.hub = get_hub() <NEW_LINE> self._notifier = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '<%s %s _links[%s]>' % (self.__class__.__name__, (self._flag and 'set') or 'clear', len(self._links)) <NEW_LINE> <DEDENT> def is_set(self): <NEW_LINE> <INDENT> return self._flag <NEW_LINE> <DEDENT> isSet = is_set <NEW_LINE> ready = is_set <NEW_LINE> def set(self): <NEW_LINE> <INDENT> self._flag = True <NEW_LINE> self._todo.update(self._links) <NEW_LINE> if self._todo and not self._notifier: <NEW_LINE> <INDENT> self._notifier = self.hub.loop.run_callback(self._notify_links) <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self._flag = False <NEW_LINE> <DEDENT> def wait(self, timeout=None): <NEW_LINE> <INDENT> if self._flag: <NEW_LINE> <INDENT> return self._flag <NEW_LINE> <DEDENT> switch = getcurrent().switch <NEW_LINE> self.rawlink(switch) <NEW_LINE> try: <NEW_LINE> <INDENT> timer = Timeout.start_new(timeout) <NEW_LINE> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self.hub.switch() <NEW_LINE> assert result is self, 'Invalid switch into Event.wait(): %r' % (result, ) <NEW_LINE> <DEDENT> except Timeout as ex: <NEW_LINE> <INDENT> if ex is not timer: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> timer.cancel() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.unlink(switch) <NEW_LINE> <DEDENT> return self._flag <NEW_LINE> <DEDENT> def rawlink(self, callback): <NEW_LINE> <INDENT> if not callable(callback): <NEW_LINE> <INDENT> raise TypeError('Expected callable: %r' % (callback, )) <NEW_LINE> <DEDENT> self._links.add(callback) <NEW_LINE> if self._flag and not self._notifier: <NEW_LINE> <INDENT> self._todo.add(callback) <NEW_LINE> self._notifier = self.hub.loop.run_callback(self._notify_links) <NEW_LINE> <DEDENT> <DEDENT> def unlink(self, callback): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._links.remove(callback) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def _notify_links(self): <NEW_LINE> <INDENT> while self._todo: <NEW_LINE> <INDENT> link = self._todo.pop() <NEW_LINE> if link in self._links: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> link(self) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.hub.handle_error((link, self), *sys.exc_info()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _reset_internal_locks(self): <NEW_LINE> <INDENT> pass | A synchronization primitive that allows one greenlet to wake up one or more others.
It has the same interface as :class:`threading.Event` but works across greenlets.
An event object manages an internal flag that can be set to true with the
:meth:`set` method and reset to false with the :meth:`clear` method. The :meth:`wait` method
blocks until the flag is true. | 62598fad7d847024c075c3ad |
class SequenceItem(object): <NEW_LINE> <INDENT> def __init__(self, actor): <NEW_LINE> <INDENT> self.shiftoffset = None <NEW_LINE> self.actor = actor <NEW_LINE> self.is_active = False <NEW_LINE> self.position = None <NEW_LINE> self.start = None <NEW_LINE> self.end = None <NEW_LINE> self.player_box = None <NEW_LINE> self.head_box = None <NEW_LINE> self.head_relative = None <NEW_LINE> <DEDENT> def get_frame(self, frame_number): <NEW_LINE> <INDENT> return self.actor.get_frame(self.start + frame_number) <NEW_LINE> <DEDENT> def get_slug(self): <NEW_LINE> <INDENT> return self.actor.recording.get_slug() <NEW_LINE> <DEDENT> def init_shift(self): <NEW_LINE> <INDENT> self.shiftoffset = random.randint(-300, 300) <NEW_LINE> <DEDENT> def shift(self, depth): <NEW_LINE> <INDENT> if self.shiftoffset < 0: <NEW_LINE> <INDENT> depth[depth < abs(self.shiftoffset)] = 0 <NEW_LINE> <DEDENT> depth[depth > 0] = depth[depth > 0] + self.shiftoffset <NEW_LINE> return depth | A single item that will be rendered in a sequence
:param object: An actor object that will be rendered according to the other parameters provided
:return: None | 62598faef548e778e596b58e |
class RelativeTime(Field): <NEW_LINE> <INDENT> MUTABLE = False <NEW_LINE> def _isotime_to_timedelta(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj_time = time.strptime(value, '%H:%M:%S') <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> raise ValueError( "Incorrect RelativeTime value {!r} was set in XML or serialized. " "Original parse message is {}".format(value, e.message) ) <NEW_LINE> <DEDENT> return datetime.timedelta( hours=obj_time.tm_hour, minutes=obj_time.tm_min, seconds=obj_time.tm_sec ) <NEW_LINE> <DEDENT> def from_json(self, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return datetime.timedelta(seconds=0) <NEW_LINE> <DEDENT> if isinstance(value, float): <NEW_LINE> <INDENT> return datetime.timedelta(seconds=value) <NEW_LINE> <DEDENT> if isinstance(value, basestring): <NEW_LINE> <INDENT> return self._isotime_to_timedelta(value) <NEW_LINE> <DEDENT> msg = "RelativeTime Field {0} has bad value '{1!r}'".format(self._name, value) <NEW_LINE> raise TypeError(msg) <NEW_LINE> <DEDENT> def to_json(self, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return "00:00:00" <NEW_LINE> <DEDENT> if isinstance(value, float): <NEW_LINE> <INDENT> value = min(value, 86400) <NEW_LINE> return self.timedelta_to_string(datetime.timedelta(seconds=value)) <NEW_LINE> <DEDENT> if isinstance(value, datetime.timedelta): <NEW_LINE> <INDENT> if value.total_seconds() > 86400: <NEW_LINE> <INDENT> raise ValueError( "RelativeTime max value is 23:59:59=86400.0 seconds, " "but {} seconds is passed".format(value.total_seconds()) ) <NEW_LINE> <DEDENT> return self.timedelta_to_string(value) <NEW_LINE> <DEDENT> raise TypeError("RelativeTime: cannot convert {!r} to json".format(value)) <NEW_LINE> <DEDENT> def timedelta_to_string(self, value): <NEW_LINE> <INDENT> stringified = str(value) <NEW_LINE> if len(stringified) == 7: <NEW_LINE> <INDENT> stringified = '0' + stringified <NEW_LINE> <DEDENT> return stringified | Field for start_time and end_time video module properties.
It was decided, that python representation of start_time and end_time
should be python datetime.timedelta object, to be consistent with
common time representation.
At the same time, serialized representation should be "HH:MM:SS"
This format is convenient to use in XML (and it is used now),
and also it is used in frond-end studio editor of video module as format
for start and end time fields.
In database we previously had float type for start_time and end_time fields,
so we are checking it also.
Python object of RelativeTime is datetime.timedelta.
JSONed representation of RelativeTime is "HH:MM:SS" | 62598faebaa26c4b54d4f29d |
class UserRepos(APIView): <NEW_LINE> <INDENT> keys = ['id', 'name', 'description', 'fork', 'html_url', 'ssh_url'] <NEW_LINE> def get_repos(self): <NEW_LINE> <INDENT> return self.gh.my_repos() <NEW_LINE> <DEDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.gh = GithubClient(request.user.id) <NEW_LINE> repos = self.get_repos() <NEW_LINE> repos = sorted(repos, key=lambda k: (k.fork, k.name)) <NEW_LINE> return Response([ restrict_keys(repo.to_json(), self.keys) for repo in repos ]) | Retrieve user's repos from github. | 62598faeb7558d5895463614 |
class D: <NEW_LINE> <INDENT> def __init__(self, d): <NEW_LINE> <INDENT> self.kgperm3 = d <NEW_LINE> self.lbperft3 = 0.062428 * d | Density | 62598fae009cb60464d0150a |
class APP(BasePage): <NEW_LINE> <INDENT> _package = 'com.xueqiu.android' <NEW_LINE> _activity = '.view.WelcomeActivityAlias' <NEW_LINE> def start_app(self): <NEW_LINE> <INDENT> if self._driver is None: <NEW_LINE> <INDENT> caps = {} <NEW_LINE> caps['platformName'] = 'Android' <NEW_LINE> caps['platformVersion'] = '6.0' <NEW_LINE> caps['automationName'] = 'uiautomator2' <NEW_LINE> caps['deviceName'] = 'Android6.0' <NEW_LINE> caps['appPackage'] = self._package <NEW_LINE> caps['appActivity'] = self._activity <NEW_LINE> caps['noRest'] = True <NEW_LINE> caps['unicodeKeyBoard'] = True <NEW_LINE> caps['resetKeyBoard'] = True <NEW_LINE> self._driver = webdriver.Remote('http://localhost:4723/wd/hub', caps) <NEW_LINE> self._driver.implicitly_wait(2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._driver.start_activity(self._package, self._activity) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def restart_app(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def stop_app(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def quit_appium(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def goto_home_page(self): <NEW_LINE> <INDENT> return HomePage(self._driver) | 封装app的方法,用于启动 打开 重启 停止APP | 62598fae4e4d562566372410 |
class PollfdPrinter(object): <NEW_LINE> <INDENT> def __init__(self, val): <NEW_LINE> <INDENT> self.val = val <NEW_LINE> <DEDENT> def to_string(self): <NEW_LINE> <INDENT> return ( '\n' '\tfd: {:0d} e: 0x{:03x} r: 0x{:03x}' .format( int( self.val['fd'] ), int( self.val['events'] ), int( self.val['revents'] ) ) ) | Print the peer poll array for debugging. | 62598fae26068e7796d4c93f |
class Solution: <NEW_LINE> <INDENT> def repeatedStringMatch(self, A, B): <NEW_LINE> <INDENT> count = 1 <NEW_LINE> originalA = A <NEW_LINE> if B in A: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> while len(A) < 2 * len(B): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> A += originalA <NEW_LINE> if B in A: <NEW_LINE> <INDENT> return count <NEW_LINE> <DEDENT> <DEDENT> return - 1 | @param A: a string
@param B: a string
@return: return an integer | 62598fae6e29344779b00646 |
class DeathThreat(Exception): <NEW_LINE> <INDENT> pass | Greeting was insufficiently kind.
| 62598faea17c0f6771d5c220 |
class BankQuerySession(abc_assessment_sessions.BankQuerySession, osid_sessions.OsidSession): <NEW_LINE> <INDENT> _session_name = 'BankQuerySession' <NEW_LINE> def __init__(self, proxy=None, runtime=None, **kwargs): <NEW_LINE> <INDENT> OsidSession._init_catalog(self, proxy, runtime) <NEW_LINE> self._forms = dict() <NEW_LINE> self._kwargs = kwargs <NEW_LINE> <DEDENT> def can_search_banks(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_bank_query(self): <NEW_LINE> <INDENT> return queries.BankQuery(runtime=self._runtime) <NEW_LINE> <DEDENT> bank_query = property(fget=get_bank_query) <NEW_LINE> @utilities.arguments_not_none <NEW_LINE> def get_banks_by_query(self, bank_query): <NEW_LINE> <INDENT> query_terms = dict(bank_query._query_terms) <NEW_LINE> collection = MongoClientValidated('assessment', collection='Bank', runtime=self._runtime) <NEW_LINE> result = collection.find(query_terms).sort('_id', DESCENDING) <NEW_LINE> return objects.BankList(result, runtime=self._runtime) | This session provides methods for searching among ``Bank`` objects.
The search query is constructed using the ``BankQuery``.
Banks may have aquery record indicated by their respective record
types. The query record is accessed via the ``BankQuery``. | 62598fae01c39578d7f12d69 |
class RelationshipType(OwnerModel): <NEW_LINE> <INDENT> a_is_to_b = models.CharField(max_length=50) <NEW_LINE> b_is_to_a = models.CharField(max_length=50) <NEW_LINE> preffered = models.BooleanField(default=False) <NEW_LINE> dependent = models.BooleanField(default=False) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.a_is_to_b + ' - ' + self.b_is_to_a | try and defile the relationship between a user and another | 62598fae4527f215b58e9eca |
class Perforation(Enum): <NEW_LINE> <INDENT> SOLID = 0 <NEW_LINE> PUNCHED = 1 <NEW_LINE> def toggle(self) -> 'Perforation': <NEW_LINE> <INDENT> return (Perforation.PUNCHED, Perforation.SOLID)[self.value] | represents the state of a position in a `Mask`, `SOLID` or `PUNCHED`
| 62598fae627d3e7fe0e06e98 |
class DNSMethod(Method): <NEW_LINE> <INDENT> def __init__(self, hostname, port): <NEW_LINE> <INDENT> self.hostname = hostname <NEW_LINE> self.port = port <NEW_LINE> <DEDENT> def get_candidates(self): <NEW_LINE> <INDENT> candidates = [] <NEW_LINE> for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(self.hostname, self.port, 0, 0, socket.IPPROTO_TCP): <NEW_LINE> <INDENT> candidates.append(sockaddr[:2]+(family,)) <NEW_LINE> <DEDENT> return candidates <NEW_LINE> <DEDENT> def get_registry(self): <NEW_LINE> <INDENT> for ip_address, port, family in self.get_candidates(): <NEW_LINE> <INDENT> found_address, found_port = self.check_ip(ip_address, port, family=family) <NEW_LINE> if found_address is not None: <NEW_LINE> <INDENT> return self.found_registry(found_address, found_port) <NEW_LINE> <DEDENT> <DEDENT> return None | Checks a DNS RR for the registry
Attributes
----------
hostname : str
port : int | 62598fae56ac1b37e63021d6 |
class ParserMeshSupplementalsTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.file = get_sample_file(mesh_file_type=EnumMeshFileSample.SUPP) <NEW_LINE> self.parser = ParserXmlMeshSupplementals() <NEW_LINE> self.file_xml = self.parser.open_xml_file(filename_xml=self.file.name) <NEW_LINE> elements = self.parser.generate_xml_elements( file_xml=self.file_xml, element_tag="SupplementalRecord" ) <NEW_LINE> self.supplemental_element = next(elements) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.file.close() <NEW_LINE> self.file_xml.close() <NEW_LINE> os.remove(self.file.name) <NEW_LINE> <DEDENT> def test_parse_supplemental_record(self): <NEW_LINE> <INDENT> record = self.parser.parse_supplemental_record( element=self.supplemental_element, ) <NEW_LINE> self.assertEqual(record["SupplementalClass"], SupplementalClassType.ONE) <NEW_LINE> self.assertEqual(record["SupplementalRecordUI"], "C000002") <NEW_LINE> self.assertEqual(record["SupplementalRecordName"], "bevonium") <NEW_LINE> self.assertEqual(record["DateCreated"], datetime.date(1971, 1, 1)) <NEW_LINE> self.assertEqual(record["DateRevised"], datetime.date(2018, 9, 24)) <NEW_LINE> self.assertEqual(record["Note"], "structure given in first source") <NEW_LINE> self.assertEqual(record["Frequency"], "1") <NEW_LINE> <DEDENT> def test_parse_heading_mapped_to_list(self): <NEW_LINE> <INDENT> records = self.parser.parse_heading_mapped_to_list( self.supplemental_element.find("HeadingMappedToList") ) <NEW_LINE> self.assertListEqual( records, [ { 'DescriptorReferredTo': { 'DescriptorName': 'Benzilates', 'DescriptorUI': 'D001561' }, 'QualifierReferredTo': {} }, { 'DescriptorReferredTo': { 'DescriptorName': 'Acetylglucosamine', 'DescriptorUI': 'D000117' }, 'QualifierReferredTo': { 'QualifierName': 'analogs & derivatives', 'QualifierUI': 'Q000031' } } ] ) <NEW_LINE> <DEDENT> def test_parse_indexing_information_list(self): <NEW_LINE> <INDENT> records = self.parser.parse_indexing_information_list( self.supplemental_element.find("IndexingInformationList") ) <NEW_LINE> self.assertListEqual( records, [ { 'DescriptorReferredTo': { 'DescriptorName': 'Leprosy', 'DescriptorUI': 'D007918' }, 'QualifierReferredTo': { 'QualifierName': 'drug therapy', 'QualifierUI': 'Q000188' } }, { 'DescriptorReferredTo': { 'DescriptorName': 'Street Drugs', 'DescriptorUI': 'D013287' }, 'QualifierReferredTo': {} } ] ) <NEW_LINE> <DEDENT> def test_parse_source_list(self): <NEW_LINE> <INDENT> records = self.parser.parse_source_list( self.supplemental_element.find("SourceList") ) <NEW_LINE> self.assertListEqual( records, [ {'Source': 'S Afr Med J 50(1):4;1976'}, {'Source': 'Q J Med 1979;48(191):493'} ] ) <NEW_LINE> <DEDENT> def test_parse(self): <NEW_LINE> <INDENT> self.file = get_sample_file(mesh_file_type=EnumMeshFileSample.SUPP) <NEW_LINE> records = self.parser.parse(self.file.name) <NEW_LINE> self.assertEqual(len(list(records)), 1) | Tests the `ParserXmlMeshSupplementals` class. | 62598fae2ae34c7f260ab0cc |
class ipyparallel_island_test_case(_ut.TestCase): <NEW_LINE> <INDENT> def __init__(self, level): <NEW_LINE> <INDENT> _ut.TestCase.__init__(self) <NEW_LINE> self._level = level <NEW_LINE> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import ipyparallel <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.run_basic_tests() <NEW_LINE> <DEDENT> def run_basic_tests(self): <NEW_LINE> <INDENT> from .core import island, de, rosenbrock <NEW_LINE> from . import ipyparallel_island <NEW_LINE> from copy import copy, deepcopy <NEW_LINE> from pickle import dumps, loads <NEW_LINE> to = .5 <NEW_LINE> try: <NEW_LINE> <INDENT> isl = island(algo=de(), prob=rosenbrock(), size=25, udi=ipyparallel_island(timeout=to)) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> isl = island(algo=de(), prob=rosenbrock(), size=25, udi=ipyparallel_island(timeout=to)) <NEW_LINE> isl = island(algo=de(), prob=rosenbrock(), size=25, udi=ipyparallel_island(timeout=to + .3)) <NEW_LINE> self.assertEqual(isl.get_name(), "Ipyparallel island") <NEW_LINE> self.assertTrue(isl.get_extra_info() != "") <NEW_LINE> isl.evolve(20) <NEW_LINE> isl.wait_check() <NEW_LINE> isl.evolve(20) <NEW_LINE> isl.evolve(20) <NEW_LINE> isl.wait() <NEW_LINE> isl = island(algo=de(), prob=_prob(lambda x, y: x + y), size=25, udi=ipyparallel_island(timeout=to + .3)) <NEW_LINE> isl.evolve() <NEW_LINE> isl.wait_check() <NEW_LINE> isl2 = copy(isl) <NEW_LINE> isl3 = deepcopy(isl) <NEW_LINE> self.assertEqual(str(isl2.get_population()), str(isl.get_population())) <NEW_LINE> self.assertEqual(str(isl2.get_algorithm()), str(isl.get_algorithm())) <NEW_LINE> self.assertEqual(str(isl2.get_name()), str(isl.get_name())) <NEW_LINE> self.assertEqual(str(isl3.get_population()), str(isl.get_population())) <NEW_LINE> self.assertEqual(str(isl3.get_algorithm()), str(isl.get_algorithm())) <NEW_LINE> self.assertEqual(str(isl3.get_name()), str(isl.get_name())) <NEW_LINE> pisl = loads(dumps(isl)) <NEW_LINE> self.assertEqual(str(pisl.get_population()), str(isl.get_population())) <NEW_LINE> self.assertEqual(str(pisl.get_algorithm()), str(isl.get_algorithm())) <NEW_LINE> self.assertEqual(str(pisl.get_name()), str(isl.get_name())) <NEW_LINE> if self._level == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for _ in range(1000): <NEW_LINE> <INDENT> isl = island(algo=de(), prob=_prob( lambda x, y: x + y), size=2, udi=ipyparallel_island(timeout=to + .3)) <NEW_LINE> isl.evolve() <NEW_LINE> isl.wait() <NEW_LINE> self.assertTrue("**error occurred**" in repr(isl)) <NEW_LINE> self.assertRaises(RuntimeError, lambda: isl.wait_check()) | Test case for the :class:`~pygmo.ipyparallel` class.
| 62598fae76e4537e8c3ef598 |
class Comment(models.Model): <NEW_LINE> <INDENT> comment_content = models.CharField(max_length=255) <NEW_LINE> user_id = models.IntegerField() <NEW_LINE> user_name = models.CharField(max_length=50) <NEW_LINE> user_avatar = models.CharField(max_length=255) <NEW_LINE> create_date = models.DateTimeField(default=timezone.now) <NEW_LINE> agree_num = models.IntegerField(default=0) <NEW_LINE> article_id = models.IntegerField() | 评论 | 62598faeadb09d7d5dc0a575 |
class Stats(object): <NEW_LINE> <INDENT> __slots__ = ("total", "files") <NEW_LINE> def __init__(self, total, files): <NEW_LINE> <INDENT> self.total = total <NEW_LINE> self.files = files <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _list_from_string(cls, repo, text): <NEW_LINE> <INDENT> hsh = {'total': {'insertions': 0, 'deletions': 0, 'lines': 0, 'files': 0}, 'files': dict()} <NEW_LINE> for line in text.splitlines(): <NEW_LINE> <INDENT> (raw_insertions, raw_deletions, filename) = line.split("\t") <NEW_LINE> insertions = raw_insertions != '-' and int(raw_insertions) or 0 <NEW_LINE> deletions = raw_deletions != '-' and int(raw_deletions) or 0 <NEW_LINE> hsh['total']['insertions'] += insertions <NEW_LINE> hsh['total']['deletions'] += deletions <NEW_LINE> hsh['total']['lines'] += insertions + deletions <NEW_LINE> hsh['total']['files'] += 1 <NEW_LINE> hsh['files'][filename.strip()] = {'insertions': insertions, 'deletions': deletions, 'lines': insertions + deletions} <NEW_LINE> <DEDENT> return Stats(hsh['total'], hsh['files']) | Represents stat information as presented by git at the end of a merge. It is
created from the output of a diff operation.
``Example``::
c = Commit( sha1 )
s = c.stats
s.total # full-stat-dict
s.files # dict( filepath : stat-dict )
``stat-dict``
A dictionary with the following keys and values::
deletions = number of deleted lines as int
insertions = number of inserted lines as int
lines = total number of lines changed as int, or deletions + insertions
``full-stat-dict``
In addition to the items in the stat-dict, it features additional information::
files = number of changed files as int | 62598faeaad79263cf42e7bf |
class block_pos: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.modelInfo = [] <NEW_LINE> rospy.Subscriber('/gazebo/model_states', ModelStates, self.callback) <NEW_LINE> <DEDENT> def callback(self, data): <NEW_LINE> <INDENT> self.modelInfo = data | The class definition for getting the pose of models in Gazebo | 62598fae8da39b475be031d0 |
class PortMixin(object): <NEW_LINE> <INDENT> def __init__( self, isBehavior=None, isConjugated=None, isService=None, protocol=None, provided=None, redefinedPort=None, required=None, ** kwargs): <NEW_LINE> <INDENT> super(PortMixin, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def port_aggregation(self, diagnostics=None, context=None): <NEW_LINE> <INDENT> raise NotImplementedError( 'operation port_aggregation(...) not yet implemented') <NEW_LINE> <DEDENT> def default_value(self, diagnostics=None, context=None): <NEW_LINE> <INDENT> raise NotImplementedError( 'operation default_value(...) not yet implemented') <NEW_LINE> <DEDENT> def encapsulated_owner(self, diagnostics=None, context=None): <NEW_LINE> <INDENT> raise NotImplementedError( 'operation encapsulated_owner(...) not yet implemented') <NEW_LINE> <DEDENT> def get_provideds(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'operation get_provideds(...) not yet implemented') <NEW_LINE> <DEDENT> def get_requireds(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'operation get_requireds(...) not yet implemented') <NEW_LINE> <DEDENT> def basic_provided(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'operation basic_provided(...) not yet implemented') <NEW_LINE> <DEDENT> def basic_required(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'operation basic_required(...) not yet implemented') | User defined mixin class for Port. | 62598fae4e4d562566372411 |
class SdpDataFileWriter: <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> self.filename = os.path.abspath(filename) <NEW_LINE> if not os.path.isfile(filename): <NEW_LINE> <INDENT> with open(self.filename, 'a') as file: <NEW_LINE> <INDENT> file.write('<sdp>\n') <NEW_LINE> file.write('</sdp>\n') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _updater(xmlel, dict): <NEW_LINE> <INDENT> for key, value in dict.items(): <NEW_LINE> <INDENT> els = xmlel.findall(key) <NEW_LINE> if els: <NEW_LINE> <INDENT> el = els[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> el = ET.SubElement(xmlel, key) <NEW_LINE> <DEDENT> if hasattr(value, "items"): <NEW_LINE> <INDENT> SdpDataFileWriter._updater(el, value) <NEW_LINE> <DEDENT> elif value is None: <NEW_LINE> <INDENT> el.text = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> el.text = str(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _prettify(xmlel, indent=0): <NEW_LINE> <INDENT> lastsubel = None <NEW_LINE> for subel in xmlel: <NEW_LINE> <INDENT> SdpDataFileWriter._prettify(subel, indent + 2) <NEW_LINE> lastsubel = subel <NEW_LINE> <DEDENT> if lastsubel is not None: <NEW_LINE> <INDENT> lastsubel.tail = '\n' + ' ' * indent <NEW_LINE> xmlel.text = '\n' + ' ' * (indent + 2) <NEW_LINE> <DEDENT> xmlel.tail = '\n' + ' ' * indent <NEW_LINE> <DEDENT> def updatefile(self, dict): <NEW_LINE> <INDENT> with open(self.filename, "r+b") as file: <NEW_LINE> <INDENT> maintree = ET.parse(file) <NEW_LINE> root = maintree.getroot() <NEW_LINE> self._updater(root, dict) <NEW_LINE> self._prettify(root) <NEW_LINE> file.seek(0) <NEW_LINE> maintree.write(file) <NEW_LINE> file.truncate() | A class to update (sdp) data xml files.
The xml is supposed to be 'simple', more precisely it has
- no attributes, and
- the only meaningful text/tail is in the leafs.
This form of xml can be captured by Python's 'dict' type, with values
eiher None, string-representable objects, or dicts themselves. Such a
dict should be the argument of updatefile().
Note this is an update function, so elements in the xml file that do
not appear in the dict are left untouched.
The outer tag is not part of this dict. It is commonly called 'sdp' but
this is ignored. | 62598fae7cff6e4e811b5a18 |
class ZwaveActuator: <NEW_LINE> <INDENT> def __init__(self, network): <NEW_LINE> <INDENT> self.network = network.network <NEW_LINE> <DEDENT> def search_switch(self, node_id, label): <NEW_LINE> <INDENT> for val in self.network.nodes[node_id].get_switches(): <NEW_LINE> <INDENT> if self.network.nodes[node_id].values[val].label == label: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> <DEDENT> return -1 <NEW_LINE> <DEDENT> def on(self, node_id, label): <NEW_LINE> <INDENT> val = self.search_switch(node_id, label) <NEW_LINE> if self.network.nodes[node_id].set_switch(val,True): <NEW_LINE> <INDENT> return "on/off : success\n" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Device Not Found/Error in fetching data\n" <NEW_LINE> <DEDENT> <DEDENT> def off(self, node_id, label): <NEW_LINE> <INDENT> val = self.search_switch(node_id, label) <NEW_LINE> if self.network.nodes[node_id].set_switch(val,False): <NEW_LINE> <INDENT> return "on/off : success\n" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Device Not Found/Error in fetching data\n" <NEW_LINE> <DEDENT> <DEDENT> def toggle(self, node_id, label): <NEW_LINE> <INDENT> if self.status(node_id, label): <NEW_LINE> <INDENT> return self.off(node_id,label) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.on(node_id, label) <NEW_LINE> <DEDENT> <DEDENT> def status(self, node_id, label): <NEW_LINE> <INDENT> val = self.search_switch(node_id, label) <NEW_LINE> return self.network.nodes[node_id].get_switch_state(val) | Class of ZwaveActuator: the instance of this class is used to control
zwave device in the contexual of a valid zwave network. | 62598fae2ae34c7f260ab0cd |
class AgnocompleteMixin: <NEW_LINE> <INDENT> widget = AgnocompleteSelect <NEW_LINE> def _setup_agnocomplete_widget(self): <NEW_LINE> <INDENT> self.widget.agnocomplete = self.agnocomplete <NEW_LINE> <DEDENT> def set_agnocomplete(self, klass_or_instance, user): <NEW_LINE> <INDENT> if isinstance(klass_or_instance, str): <NEW_LINE> <INDENT> registry = get_agnocomplete_registry() <NEW_LINE> if klass_or_instance not in registry: <NEW_LINE> <INDENT> raise UnregisteredAgnocompleteException( "Unregistered Agnocomplete class: {} is unknown".format(klass_or_instance) ) <NEW_LINE> <DEDENT> klass_or_instance = registry[klass_or_instance] <NEW_LINE> <DEDENT> if not isinstance(klass_or_instance, AgnocompleteBase): <NEW_LINE> <INDENT> klass_or_instance = klass_or_instance(user=user) <NEW_LINE> <DEDENT> if isinstance(klass_or_instance, AgnocompleteBase): <NEW_LINE> <INDENT> klass_or_instance.set_agnocomplete_field(self) <NEW_LINE> <DEDENT> self.agnocomplete = klass_or_instance <NEW_LINE> self.agnocomplete.user = user <NEW_LINE> <DEDENT> def get_agnocomplete_context(self): <NEW_LINE> <INDENT> return getattr(self, AGNOCOMPLETE_USER_ATTRIBUTE, None) <NEW_LINE> <DEDENT> def transmit_agnocomplete_context(self): <NEW_LINE> <INDENT> if hasattr(self, AGNOCOMPLETE_USER_ATTRIBUTE): <NEW_LINE> <INDENT> user = self.get_agnocomplete_context() <NEW_LINE> if user: <NEW_LINE> <INDENT> self.agnocomplete.user = user <NEW_LINE> <DEDENT> return user <NEW_LINE> <DEDENT> <DEDENT> def clean(self, *args, **kwargs): <NEW_LINE> <INDENT> self.transmit_agnocomplete_context() <NEW_LINE> return super().clean(*args, **kwargs) | Handles the Agnocomplete generic handling for fields. | 62598fae57b8e32f52508111 |
class FeinCMSLoginRequiredMiddleware( LoginPermissionMiddlewareMixin, FeinCMSPermissionMiddleware ): <NEW_LINE> <INDENT> base_unauthorised_redirect_url = settings.LOGIN_URL | Middleware that requires a user to be authenticated to view any page with an
access_state of STATE_AUTH_ONLY.
Requires authentication middleware, template context processors, and FeinCMS's
add_page_if_missing middleware to be loaded. You'll get an error if they aren't. | 62598faee76e3b2f99fd8a22 |
class HostAgentNotifyAPI(object): <NEW_LINE> <INDENT> def __init__(self, topic=topics.AGENT): <NEW_LINE> <INDENT> target = oslo_messaging.Target(topic=topic, version='1.0') <NEW_LINE> self.topic = topic <NEW_LINE> self.client = n_rpc.get_client(target) <NEW_LINE> <DEDENT> def _notification_host(self, context, method, payload, host): <NEW_LINE> <INDENT> LOG.debug('Notify agents on %(host)s of the message ' '%(method)s', {'host': host, 'method': method}) <NEW_LINE> topic_host_updated = topics.get_topic_name(self.topic, topics.HOST, topics.UPDATE, host) <NEW_LINE> cctxt = self.client.prepare(topic=topic_host_updated, server=host) <NEW_LINE> cctxt.cast(context, method, payload=payload) <NEW_LINE> <DEDENT> def host_updated(self, context, host_state_up, host): <NEW_LINE> <INDENT> self._notification_host(context, 'host_updated', {'host_state_up': host_state_up}, host) | API for plugin to notify agents of host state change. | 62598fae8e7ae83300ee908d |
class Good(models.Model): <NEW_LINE> <INDENT> good_id = models.AutoField(primary_key=True, verbose_name='商品ID') <NEW_LINE> good_sender_id = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='卖家') <NEW_LINE> good_portrait = models.ImageField(upload_to='good_img', default='avatar/default.png', verbose_name='商品图片') <NEW_LINE> good_name = models.CharField(max_length=20, default="", verbose_name='商品名称') <NEW_LINE> good_prize = models.FloatField(max_length=128, verbose_name='价格') <NEW_LINE> good_description = models.CharField(max_length=256, blank=True, verbose_name='描述') <NEW_LINE> good_time = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='发出时间') <NEW_LINE> good_category = models.ForeignKey(GoodType, on_delete=models.CASCADE, verbose_name='商品分类') <NEW_LINE> fav = models.IntegerField(default=0, blank=True, verbose_name='收藏总次数') <NEW_LINE> car = models.IntegerField(default=0, blank=True, verbose_name='加入购物车总次数') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.good_name | 商品 | 62598fae30bbd7224646996e |
class VirtualMachineScaleSetUpdateNetworkConfiguration(SubResource): <NEW_LINE> <INDENT> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'primary': {'key': 'properties.primary', 'type': 'bool'}, 'enable_accelerated_networking': {'key': 'properties.enableAcceleratedNetworking', 'type': 'bool'}, 'network_security_group': {'key': 'properties.networkSecurityGroup', 'type': 'SubResource'}, 'dns_settings': {'key': 'properties.dnsSettings', 'type': 'VirtualMachineScaleSetNetworkConfigurationDnsSettings'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[VirtualMachineScaleSetUpdateIPConfiguration]'}, 'enable_ip_forwarding': {'key': 'properties.enableIPForwarding', 'type': 'bool'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, primary: Optional[bool] = None, enable_accelerated_networking: Optional[bool] = None, network_security_group: Optional["SubResource"] = None, dns_settings: Optional["VirtualMachineScaleSetNetworkConfigurationDnsSettings"] = None, ip_configurations: Optional[List["VirtualMachineScaleSetUpdateIPConfiguration"]] = None, enable_ip_forwarding: Optional[bool] = None, **kwargs ): <NEW_LINE> <INDENT> super(VirtualMachineScaleSetUpdateNetworkConfiguration, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.primary = primary <NEW_LINE> self.enable_accelerated_networking = enable_accelerated_networking <NEW_LINE> self.network_security_group = network_security_group <NEW_LINE> self.dns_settings = dns_settings <NEW_LINE> self.ip_configurations = ip_configurations <NEW_LINE> self.enable_ip_forwarding = enable_ip_forwarding | Describes a virtual machine scale set network profile's network configurations.
:ivar id: Resource Id.
:vartype id: str
:ivar name: The network configuration name.
:vartype name: str
:ivar primary: Whether this is a primary NIC on a virtual machine.
:vartype primary: bool
:ivar enable_accelerated_networking: Specifies whether the network interface is accelerated
networking-enabled.
:vartype enable_accelerated_networking: bool
:ivar network_security_group: The network security group.
:vartype network_security_group: ~azure.mgmt.compute.v2019_12_01.models.SubResource
:ivar dns_settings: The dns settings to be applied on the network interfaces.
:vartype dns_settings:
~azure.mgmt.compute.v2019_12_01.models.VirtualMachineScaleSetNetworkConfigurationDnsSettings
:ivar ip_configurations: The virtual machine scale set IP Configuration.
:vartype ip_configurations:
list[~azure.mgmt.compute.v2019_12_01.models.VirtualMachineScaleSetUpdateIPConfiguration]
:ivar enable_ip_forwarding: Whether IP forwarding enabled on this NIC.
:vartype enable_ip_forwarding: bool | 62598fae56ac1b37e63021d7 |
class updateAttributes(Handler): <NEW_LINE> <INDENT> def control(self): <NEW_LINE> <INDENT> self.is_valid(self.ras_ip, str) <NEW_LINE> self.is_valid_content(self.ras_ip, self.IP_PATTERN) <NEW_LINE> self.is_valid(self.attrs, dict) <NEW_LINE> <DEDENT> def setup(self, ras_ip, attrs): <NEW_LINE> <INDENT> self.ras_ip = ras_ip <NEW_LINE> self.attrs = attrs | Update attributes method class. | 62598faecb5e8a47e493c16f |
class Rig( MasterControlChainBendyRig, SegmentedChainBendyRig, ConnectingChainBendyRig, AlignedChainBendyRig, ComplexChainBendyRig ): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def parameters_ui(self, layout, params): <NEW_LINE> <INDENT> box = layout.box() <NEW_LINE> self.master_control_ui(self, box, params) <NEW_LINE> self.segmented_fk_ui(self, box, params) <NEW_LINE> self.attach_ui(self, box, params) <NEW_LINE> layout.row().prop(params, 'show_advanced') <NEW_LINE> if params.show_advanced: <NEW_LINE> <INDENT> box = layout.box() <NEW_LINE> self.align_ui(self, box, params) <NEW_LINE> self.complex_stretch_ui(self, box, params) <NEW_LINE> self.rotation_mode_tweak_ui(self, box, params) <NEW_LINE> self.org_transform_ui(self, box, params) <NEW_LINE> self.volume_ui(self, box, params) <NEW_LINE> <DEDENT> box = layout.box() <NEW_LINE> self.bbones_ui(self, box, params) <NEW_LINE> ControlLayersOption.TWEAK.parameters_ui(layout, params) | Bendy tentacle | 62598faebd1bec0571e150b9 |
class Wave: <NEW_LINE> <INDENT> def __init__(self, enemies): <NEW_LINE> <INDENT> self.enemies = enemies <NEW_LINE> <DEDENT> def tick(self, speedadjust=1.0): <NEW_LINE> <INDENT> for enemy in self.enemies: <NEW_LINE> <INDENT> if enemy.dead: <NEW_LINE> <INDENT> self.enemies.remove(enemy) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> enemy.tick(speedadjust) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def start(self, enemies_pos): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> for enemy in self.enemies: <NEW_LINE> <INDENT> enemy.start(enemies_pos[i]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> def draw(self, gfx): <NEW_LINE> <INDENT> [enemy.draw(gfx) for enemy in self.enemies] <NEW_LINE> <DEDENT> def erase(self, background): <NEW_LINE> <INDENT> [enemy.erase(background) for enemy in self.enemies] <NEW_LINE> <DEDENT> def dead(self): <NEW_LINE> <INDENT> for enemy in self.enemies: <NEW_LINE> <INDENT> if not enemy.dead: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> return 1 | Definicao do objeto wave | 62598fae4a966d76dd5eeec8 |
class DoctorContentView(AppTemplateView): <NEW_LINE> <INDENT> template_name = 'about/doctor.html' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(DoctorContentView, self).get_context_data(**kwargs) <NEW_LINE> doctor = get_object_or_404(Doctor, code=context['doctor_code']) <NEW_LINE> doctorcontent_list = doctor.doctorcontent_set.order_by('content_type') <NEW_LINE> context = { "doctor": doctor, "doctorcontent_list": doctorcontent_list } <NEW_LINE> return context | A view for displaying information about a doctor | 62598fae66656f66f7d5a3db |
class QMatrix4x2(): <NEW_LINE> <INDENT> def copyDataTo(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def data(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fill(self, p_float): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def isIdentity(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def setToIdentity(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def transposed(self): <NEW_LINE> <INDENT> return QMatrix2x4 <NEW_LINE> <DEDENT> def __delitem__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __eq__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __getitem__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ge__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __gt__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __iadd__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __idiv__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __imul__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __isub__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __itruediv__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __le__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __lt__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ne__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __setitem__(self, i, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) | QMatrix4x2()
QMatrix4x2(QMatrix4x2)
QMatrix4x2(sequence-of-float) | 62598fae44b2445a339b6966 |
class PrivateUserApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = create_user( email='test@c2c.com', password='testpassword', ) <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(user=self.user) <NEW_LINE> <DEDENT> def test_retrieve_user(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> res.data.pop('id') <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, {'email': self.user.email}) <NEW_LINE> <DEDENT> def test_update_user(self): <NEW_LINE> <INDENT> payload = {'password': 'newpassword'} <NEW_LINE> res = self.client.patch(ME_URL, payload) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertTrue(self.user.check_password(payload['password'])) <NEW_LINE> <DEDENT> def test_post_me_not_allowed(self): <NEW_LINE> <INDENT> res = self.client.post(ME_URL, {}) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) | Test user API requests that require authentication | 62598faea219f33f346c6802 |
class PoolTimeout(Exception): <NEW_LINE> <INDENT> pass | Exception raised when getting a connection from the pool takes too long.
| 62598faeb7558d5895463616 |
@python_2_unicode_compatible <NEW_LINE> class Image(TimeStampModel): <NEW_LINE> <INDENT> file = models.ImageField() <NEW_LINE> location = models.CharField(max_length=140) <NEW_LINE> caption = models.TextField() <NEW_LINE> creator = models.ForeignKey(user_models.User, on_delete=models.CASCADE, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '{} - {}'.format(self.location, self.caption) | Image Model | 62598faea8370b77170f03c8 |
class BdistAPK(Bdist): <NEW_LINE> <INDENT> description = 'Create an APK with python-for-android' <NEW_LINE> package_type = 'apk' | distutil command handler for 'apk'. | 62598fae4e4d562566372412 |
class RouteFilterRuleListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[RouteFilterRule]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["RouteFilterRule"]] = None, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(RouteFilterRuleListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link | Response for the ListRouteFilterRules API service call.
:param value: A list of RouteFilterRules in a resource group.
:type value: list[~azure.mgmt.network.v2020_05_01.models.RouteFilterRule]
:param next_link: The URL to get the next set of results.
:type next_link: str | 62598faed486a94d0ba2bfbb |
class LeftSiblings(NodeSet): <NEW_LINE> <INDENT> def __init__(self, ns, w=1): <NEW_LINE> <INDENT> self.__dict__.update(ns.__dict__) <NEW_LINE> self.label = 'LEFT-OF-%s' % ns.label <NEW_LINE> self.xpath = '%s[1]/preceding-sibling::*[position() <= %s]' % (ns.xpath, w) | Gets preceding siblings | 62598faebe8e80087fbbf050 |
class INamedDataPoint(INamedBase, IDataPoint): <NEW_LINE> <INDENT> pass | Data point with a series-unique categorical name | 62598fae26068e7796d4c941 |
class EpochDataConsumer(el.AbstractHook): <NEW_LINE> <INDENT> def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None: <NEW_LINE> <INDENT> assert 'train' in epoch_data <NEW_LINE> assert 'my_variable' in epoch_data['train'] <NEW_LINE> assert epoch_data['train']['my_variable'] == _EPOCH_DATA_VAR_VALUE | Simple hook that asserts presence of my_variable in the train entry of the epoch_data. | 62598faeaad79263cf42e7c0 |
class QuotientRing_generic(QuotientRing_nc, ring.CommutativeRing): <NEW_LINE> <INDENT> def __init__(self, R, I, names, category=None): <NEW_LINE> <INDENT> if not isinstance(R, ring.CommutativeRing): <NEW_LINE> <INDENT> raise TypeError("This class is for quotients of commutative rings only.\n For non-commutative rings, use <sage.rings.quotient_ring.QuotientRing_nc>") <NEW_LINE> <DEDENT> if not self._is_category_initialized(): <NEW_LINE> <INDENT> category = check_default_category(_CommutativeRingsQuotients,category) <NEW_LINE> <DEDENT> QuotientRing_nc.__init__(self, R, I, names, category=category) <NEW_LINE> <DEDENT> def _macaulay2_init_(self, macaulay2=None): <NEW_LINE> <INDENT> if macaulay2 is None: <NEW_LINE> <INDENT> from sage.interfaces.macaulay2 import macaulay2 as m2_default <NEW_LINE> macaulay2 = m2_default <NEW_LINE> <DEDENT> I = self.defining_ideal()._macaulay2_(macaulay2) <NEW_LINE> return I.ring()._operator('/', I) | Creates a quotient ring of a *commutative* ring `R` by the ideal `I`.
EXAMPLES::
sage: R.<x> = PolynomialRing(ZZ)
sage: I = R.ideal([4 + 3*x + x^2, 1 + x^2])
sage: S = R.quotient_ring(I); S
Quotient of Univariate Polynomial Ring in x over Integer Ring by the ideal (x^2 + 3*x + 4, x^2 + 1) | 62598fae627d3e7fe0e06e9a |
class _BucketizedColumn(_DenseColumn, _CategoricalColumn, collections.namedtuple('_BucketizedColumn', [ 'source_column', 'boundaries'])): <NEW_LINE> <INDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return '{}_bucketized'.format(self.source_column.name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _parse_example_spec(self): <NEW_LINE> <INDENT> return self.source_column._parse_example_spec <NEW_LINE> <DEDENT> def _transform_feature(self, inputs): <NEW_LINE> <INDENT> source_tensor = inputs.get(self.source_column) <NEW_LINE> return math_ops._bucketize( source_tensor, boundaries=self.boundaries) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _variable_shape(self): <NEW_LINE> <INDENT> return tensor_shape.TensorShape( tuple(self.source_column.shape) + (len(self.boundaries) + 1,)) <NEW_LINE> <DEDENT> def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): <NEW_LINE> <INDENT> del weight_collections <NEW_LINE> del trainable <NEW_LINE> input_tensor = inputs.get(self) <NEW_LINE> return array_ops.one_hot( indices=math_ops.to_int64(input_tensor), depth=len(self.boundaries) + 1, on_value=1., off_value=0.) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _num_buckets(self): <NEW_LINE> <INDENT> return (len(self.boundaries) + 1) * self.source_column.shape[0] <NEW_LINE> <DEDENT> def _get_sparse_tensors(self, inputs, weight_collections=None, trainable=None): <NEW_LINE> <INDENT> input_tensor = inputs.get(self) <NEW_LINE> batch_size = array_ops.shape(input_tensor)[0] <NEW_LINE> source_dimension = self.source_column.shape[0] <NEW_LINE> i1 = array_ops.reshape( array_ops.tile( array_ops.expand_dims(math_ops.range(0, batch_size), 1), [1, source_dimension]), (-1,)) <NEW_LINE> i2 = array_ops.tile(math_ops.range(0, source_dimension), [batch_size]) <NEW_LINE> bucket_indices = ( array_ops.reshape(input_tensor, (-1,)) + (len(self.boundaries) + 1) * i2) <NEW_LINE> indices = math_ops.to_int64(array_ops.transpose(array_ops.stack((i1, i2)))) <NEW_LINE> dense_shape = math_ops.to_int64(array_ops.stack( [batch_size, source_dimension])) <NEW_LINE> sparse_tensor = sparse_tensor_lib.SparseTensor( indices=indices, values=bucket_indices, dense_shape=dense_shape) <NEW_LINE> return _CategoricalColumn.IdWeightPair(sparse_tensor, None) | See `bucketized_column`. | 62598fae01c39578d7f12d6c |
class LastFmApi(object): <NEW_LINE> <INDENT> def __init__(self, key): <NEW_LINE> <INDENT> self.__api_key = key <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> if name.startswith('__'): <NEW_LINE> <INDENT> raise AttributeError() <NEW_LINE> <DEDENT> def generic_request(*args, **kwargs): <NEW_LINE> <INDENT> params = dict(kwargs) <NEW_LINE> params['method'] = name.replace('_', '.') <NEW_LINE> return self.__send(params) <NEW_LINE> <DEDENT> generic_request.__name__ = name <NEW_LINE> return generic_request <NEW_LINE> <DEDENT> def __send(self, params): <NEW_LINE> <INDENT> params['api_key'] = self.__api_key <NEW_LINE> params['format'] = 'json' <NEW_LINE> headers = {'User-Agent:': USER_AGENT} <NEW_LINE> request = requests.get(LASTFM_API_ENDPOINT,params=params) <NEW_LINE> request.headers = headers <NEW_LINE> response = request.text <NEW_LINE> s = json.loads(response) <NEW_LINE> if 'error' in s: <NEW_LINE> <INDENT> raise LastFmApiException(s['message']) <NEW_LINE> <DEDENT> return s | An interface to the Last.fm api.
This class dynamically resolves methods and their parameters. For instance,
if you would like to access the album.getInfo method, you simply call
album_getInfo on an instance of LastFmApi. | 62598faea8370b77170f03c9 |
class Base(object): <NEW_LINE> <INDENT> def __init__(self, cls): <NEW_LINE> <INDENT> self.cls = cls <NEW_LINE> <DEDENT> def read_attr(self, fieldname): <NEW_LINE> <INDENT> result = self._read_dict(fieldname) <NEW_LINE> if result is not MISSING: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> result = self.cls._read_from_class(fieldname) <NEW_LINE> if hasattr(result, "__get__"): <NEW_LINE> <INDENT> return _make_boundmethod(result, self, self) <NEW_LINE> <DEDENT> if result is not MISSING: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> meth = self.cls._read_from_class("__getattr__") <NEW_LINE> if meth is MISSING: <NEW_LINE> <INDENT> raise AttributeError(fieldname) <NEW_LINE> <DEDENT> return meth(self, fieldname) <NEW_LINE> <DEDENT> def write_attr(self, fieldname, value): <NEW_LINE> <INDENT> meth = self.cls._read_from_class("__setattr__") <NEW_LINE> return meth(self, fieldname, value) <NEW_LINE> <DEDENT> def isinstance(self, cls): <NEW_LINE> <INDENT> return self.cls.issubclass(cls) <NEW_LINE> <DEDENT> def send(self, methname, *args): <NEW_LINE> <INDENT> meth = self.read_attr(methname) <NEW_LINE> return meth(*args) <NEW_LINE> <DEDENT> def _read_dict(self, fieldname): <NEW_LINE> <INDENT> return MISSING <NEW_LINE> <DEDENT> def _write_dict(self, fieldname, value): <NEW_LINE> <INDENT> raise AttributeError | The base class that all of the object model classes inherit from. | 62598fae4e4d562566372413 |
class DataMessage(AsyncMessage): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> AsyncMessage.__init__(self) <NEW_LINE> self.identity = None <NEW_LINE> self.operation = None | I am used to transport an operation that occured on a managed object
or collection.
This class of message is transmitted between clients subscribed to a
remote destination as well as between server nodes within a cluster.
The payload of this message describes all of the relevant details of
the operation. This information is used to replicate updates and detect
conflicts.
@see: U{DataMessage on Livedocs<http://
help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/data/messages/DataMessage.html>} | 62598fae167d2b6e312b6f5f |
class ApiGrrMessageRenderer(ApiRDFProtoStructRenderer): <NEW_LINE> <INDENT> value_class = rdfvalue.GrrMessage <NEW_LINE> def RenderPayload(self, result, value): <NEW_LINE> <INDENT> if "args_rdf_name" in result: <NEW_LINE> <INDENT> result["payload_type"] = result["args_rdf_name"] <NEW_LINE> del result["args_rdf_name"] <NEW_LINE> <DEDENT> if "args" in result: <NEW_LINE> <INDENT> result["payload"] = self._PassThrough(value.payload) <NEW_LINE> del result["args"] <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> processors = [RenderPayload] | Renderer for GrrMessage objects. | 62598fae3317a56b869be541 |
class Solution(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def separate_liquids_01(self, glass): <NEW_LINE> <INDENT> if not glass: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> n_cols = len(glass[0]) <NEW_LINE> c = Counter(chain(*glass)) <NEW_LINE> liquids = list(c['O'] * 'O' + c['A'] * 'A' + c['W'] * 'W' + c['H'] * 'H') <NEW_LINE> return [liquids[i:i + n_cols] for i in range(0, len(liquids), n_cols)] <NEW_LINE> <DEDENT> def separate_liquids_02(self, glass): <NEW_LINE> <INDENT> if not glass: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> densitytab = { 'H': 1.36, 'W': 1.00, 'A': 0.87, 'O': 0.80, } <NEW_LINE> n_cols = len(glass[0]) <NEW_LINE> liquids = sum(glass, []) <NEW_LINE> liquids.sort(key=lambda x: densitytab[x]) <NEW_LINE> def chunks(it, n): <NEW_LINE> <INDENT> item = list(islice(it, n)) <NEW_LINE> while item: <NEW_LINE> <INDENT> yield item <NEW_LINE> item = list(islice(it, n)) <NEW_LINE> <DEDENT> <DEDENT> return list(chunks(iter(liquids), n_cols)) <NEW_LINE> <DEDENT> def separate_liquids_03(self, glass): <NEW_LINE> <INDENT> if not glass: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> n_rows = len(glass) <NEW_LINE> n_cols = len(glass[0]) <NEW_LINE> liquids = reduce(list.__add__, glass) <NEW_LINE> liquids.sort(key=lambda x: 'OAWH'.index(x)) <NEW_LINE> return [liquids[i * n_cols:(i + 1) * n_cols] for i in range(n_rows)] <NEW_LINE> <DEDENT> def separate_liquids_04(self, glass): <NEW_LINE> <INDENT> if not glass: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> n_cols = len(glass[0]) <NEW_LINE> liquids = ''.join([''.join(r) for r in glass]) <NEW_LINE> liquids = sorted(liquids.replace('H', '3').replace('W', '2').replace('A', '1').replace('O', '0')) <NEW_LINE> liquids = ''.join([''.join(r) for r in liquids]) <NEW_LINE> liquids = list(liquids.replace('3', 'H').replace('2', 'W').replace('1', 'A').replace('0', 'O')) <NEW_LINE> return [list(r) for r in zip_longest(*[iter(liquids)] * n_cols)] | https://www.codewars.com/kata/dont-drink-the-water
Don't Drink the Water
Given a two-dimensional array representation of a glass of mixed liquids,
sort the array such that the liquids appear in the glass based on their density.
(Lower density floats to the top) The width of the glass will not change from top to bottom.
======================
| Density Chart |
======================
| Honey | H | 1.36 |
| Water | W | 1.00 |
| Alcohol | A | 0.87 |
| Oil | O | 0.80 |
----------------------
[ [
['H', 'H', 'W', 'O'], ['O','O','O','O']
['W', 'W', 'O', 'W'], => ['W','W','W','W']
['H', 'H', 'O', 'O'] ['H','H','H','H']
] ]
The glass representation may be larger or smaller.
If a liquid doesn't fill a row, it floats to the top and to the left. | 62598fae56b00c62f0fb28a2 |
class _PageComponents(record('navigation searchAggregator staticShellContent settings themes')): <NEW_LINE> <INDENT> pass | I encapsulate various plugin objects that have some say
in determining the available functionality on a given page | 62598fae55399d3f05626511 |
class InlineResponseDefault4(object): <NEW_LINE> <INDENT> openapi_types = { 'pagination': 'OffsetInfo', 'results': 'list[InlineResponseDefault4Results]' } <NEW_LINE> attribute_map = { 'pagination': 'pagination', 'results': 'results' } <NEW_LINE> def __init__(self, pagination=None, results=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._pagination = None <NEW_LINE> self._results = None <NEW_LINE> self.discriminator = None <NEW_LINE> if pagination is not None: <NEW_LINE> <INDENT> self.pagination = pagination <NEW_LINE> <DEDENT> if results is not None: <NEW_LINE> <INDENT> self.results = results <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def pagination(self): <NEW_LINE> <INDENT> return self._pagination <NEW_LINE> <DEDENT> @pagination.setter <NEW_LINE> def pagination(self, pagination): <NEW_LINE> <INDENT> self._pagination = pagination <NEW_LINE> <DEDENT> @property <NEW_LINE> def results(self): <NEW_LINE> <INDENT> return self._results <NEW_LINE> <DEDENT> @results.setter <NEW_LINE> def results(self, results): <NEW_LINE> <INDENT> self._results = results <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_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> 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, InlineResponseDefault4): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineResponseDefault4): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 62598fae2ae34c7f260ab0cf |
class DeviceStatusViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = DeviceStatus.objects.all() <NEW_LINE> permission_classes = (permissions.IsAuthenticatedOrReadOnly,) <NEW_LINE> serializer_class = DeviceStatusSerializer | This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions. | 62598fae460517430c432054 |
class ShellItemFileEntryEventData(events.EventData): <NEW_LINE> <INDENT> DATA_TYPE = 'windows:shell_item:file_entry' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(ShellItemFileEntryEventData, self).__init__(data_type=self.DATA_TYPE) <NEW_LINE> self.file_reference = None <NEW_LINE> self.localized_name = None <NEW_LINE> self.long_name = None <NEW_LINE> self.name = None <NEW_LINE> self.origin = None <NEW_LINE> self.shell_item_path = None | Shell item file entry event data attribute container.
Attributes:
name (str): name of the file entry shell item.
long_name (str): long name of the file entry shell item.
localized_name (str): localized name of the file entry shell item.
file_reference (str): NTFS file reference, in the format:
"MTF entry - sequence number".
shell_item_path (str): shell item path.
origin (str): origin of the event. | 62598fae8e7ae83300ee9090 |
class BooksInstanceInline(admin.TabularInline): <NEW_LINE> <INDENT> model = BookInstance <NEW_LINE> extra = 0 | Дополнительная таблица, предоставляющая доступ к моделе (BookInstance) из другой модели (Book) | 62598fae66656f66f7d5a3dd |
class TestML(unittest.TestCase): <NEW_LINE> <INDENT> def test_ml(self): <NEW_LINE> <INDENT> self.assertEqual(0, 1) | General class for testing | 62598fae2c8b7c6e89bd37b3 |
class WM_OT_owner_enable(Operator): <NEW_LINE> <INDENT> bl_idname = "wm.owner_enable" <NEW_LINE> bl_label = "Enable Add-on" <NEW_LINE> owner_id: StringProperty( name="UI Tag", ) <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> workspace = context.workspace <NEW_LINE> workspace.owner_ids.new(self.owner_id) <NEW_LINE> return {'FINISHED'} | Enable workspace owner ID | 62598faefff4ab517ebcd7d3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.