code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class ResourceNavigationLink(SubResource): <NEW_LINE> <INDENT> _validation = { 'etag': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'linked_resource_type': {'key': 'properties.linkedResourceType', 'type': 'str'}, 'link': {'key': 'properties.link', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, linked_resource_type: Optional[str] = None, link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(ResourceNavigationLink, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = None <NEW_LINE> self.type = None <NEW_LINE> self.linked_resource_type = linked_resource_type <NEW_LINE> self.link = link <NEW_LINE> self.provisioning_state = None | ResourceNavigationLink resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Resource type.
:vartype type: str
:param linked_resource_type: Resource type of the linked resource.
:type linked_resource_type: str
:param link: Link to the external resource.
:type link: str
:ivar provisioning_state: The provisioning state of the resource navigation link resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_03_01.models.ProvisioningState | 62599040c432627299fa424b |
class DefaultQAConceptProvider(object): <NEW_LINE> <INDENT> def __init__(self, data_provider): <NEW_LINE> <INDENT> self.qa_concepts = self.__expand_qa_concepts(data_provider) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __expand_qa_concepts(data_provider): <NEW_LINE> <INDENT> concepts = [] <NEW_LINE> for entity_class in data_provider.get_all_entity_types(): <NEW_LINE> <INDENT> concepts.append(EntityClassLevelQA(entity_class)) <NEW_LINE> for entity_instance in data_provider.get_all_instances_of_type(entity_class): <NEW_LINE> <INDENT> concepts.append(EntityInstanceSelfQA(entity_instance)) <NEW_LINE> for property_name, property_def in entity_class.property_def_map.iteritems(): <NEW_LINE> <INDENT> concepts.append(EntityPropertyQA(entity_instance, property_def)) <NEW_LINE> <DEDENT> for relation_name, relation_def in entity_class.relation_def_map.iteritems(): <NEW_LINE> <INDENT> concepts.append(EntityRelationQA(entity_instance, relation_def)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return concepts <NEW_LINE> <DEDENT> def get_all_qa_concepts(self): <NEW_LINE> <INDENT> return list(self.qa_concepts) | QA concept provider backed by a knowledge data provider. | 625990401d351010ab8f4db1 |
class Env: <NEW_LINE> <INDENT> def __init__(self, outerenv=None): <NEW_LINE> <INDENT> self.env = dict() <NEW_LINE> self.outerenv = outerenv <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def empty(cls): <NEW_LINE> <INDENT> return cls() <NEW_LINE> <DEDENT> def extend(self, variable, value): <NEW_LINE> <INDENT> self.env[variable] = value <NEW_LINE> <DEDENT> def extend_many(self, envdict): <NEW_LINE> <INDENT> self.env.update(envdict) <NEW_LINE> <DEDENT> def lookup(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> found = self.env[key] <NEW_LINE> env = self <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> if self.outerenv is not None: <NEW_LINE> <INDENT> found, env =self.outerenv.lookup(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NameError("{} <<>> not found in Environment".format(key)) <NEW_LINE> <DEDENT> <DEDENT> return found, env | Absfun: the dicionary {k1:v1, k2:v2,...} represents the
environment binding k1 to v1 and k2 to v2. There are no duplicates.
The keys k must be strings, and the values v must be legitimate values
in our environment.
The empty dictionary represents the empty environment.
Repinv: Newer bindings replace older bindings in the dictionary.
This is guaranteed by using python dictionaries. | 62599040379a373c97d9a2bd |
class Problem(object): <NEW_LINE> <INDENT> def __init__(self, solver_instance=None): <NEW_LINE> <INDENT> if solver_instance is None: <NEW_LINE> <INDENT> solver_instance = DefaultSolver() <NEW_LINE> <DEDENT> self._solver_instance = solver_instance <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> @property <NEW_LINE> def solutions_seen(self): <NEW_LINE> <INDENT> return self._solver_instance.solutions_seen <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._variables = {} <NEW_LINE> self._constraints = [] <NEW_LINE> self._restore_point = None <NEW_LINE> <DEDENT> def add_variable(self, variable, domain): <NEW_LINE> <INDENT> self._variables[variable] = list(domain) <NEW_LINE> <DEDENT> def add_constraint(self, func, variables, default_values=None): <NEW_LINE> <INDENT> self._constraints.append((func, variables, default_values or ())) <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> self._solver_instance.set_conditions(dict(self._variables), list(self._constraints)) <NEW_LINE> self._solver_instance.restore_point(self._restore_point) <NEW_LINE> <DEDENT> def iter_solutions(self): <NEW_LINE> <INDENT> self.setup() <NEW_LINE> return iter(self._solver_instance) <NEW_LINE> <DEDENT> def get_solutions(self): <NEW_LINE> <INDENT> return tuple(self.iter_solutions()) <NEW_LINE> <DEDENT> def restore_point(self, start): <NEW_LINE> <INDENT> self._restore_point = start <NEW_LINE> return self <NEW_LINE> <DEDENT> def save_point(self): <NEW_LINE> <INDENT> return self._solver_instance.save_point() <NEW_LINE> <DEDENT> def known_solutions(self): <NEW_LINE> <INDENT> return self._solver_instance.solutions_at_points <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Problem(variables=%(v)r, constraints=%(c)r), solver=%(s)r>" % { 'v': self._variables, 'c': self._constraints, 's': self._solver_instance.__class__, } | Represents a problem space that needs solutions.
Optionally, solver_instance can be set to provide a more customized solver. | 625990403c8af77a43b68886 |
class FrontToBackPacket( collections.namedtuple( 'FrontToBackPacket', ['operation_id', 'sequence_number', 'kind', 'name', 'subscription', 'trace_id', 'payload', 'timeout'])): <NEW_LINE> <INDENT> pass | A sum type for all values sent from a front to a back.
Attributes:
operation_id: A unique-with-respect-to-equality hashable object identifying
a particular operation.
sequence_number: A zero-indexed integer sequence number identifying the
packet's place among all the packets sent from front to back for this
particular operation. Must be zero if kind is Kind.COMMENCEMENT or
Kind.ENTIRE. Must be positive for any other kind.
kind: One of Kind.COMMENCEMENT, Kind.CONTINUATION, Kind.COMPLETION,
Kind.ENTIRE, Kind.CANCELLATION, Kind.EXPIRATION, Kind.SERVICED_FAILURE,
Kind.RECEPTION_FAILURE, or Kind.TRANSMISSION_FAILURE.
name: The name of an operation. Must be present if kind is Kind.COMMENCEMENT
or Kind.ENTIRE. Must be None for any other kind.
subscription: An interfaces.ServicedSubscription.Kind value describing the
interest the front has in packets sent from the back. Must be present if
kind is Kind.COMMENCEMENT or Kind.ENTIRE. Must be None for any other kind.
trace_id: A uuid.UUID identifying a set of related operations to which this
operation belongs. May be None.
payload: A customer payload object. Must be present if kind is
Kind.CONTINUATION. Must be None if kind is Kind.CANCELLATION. May be None
for any other kind.
timeout: An optional length of time (measured from the beginning of the
operation) to allow for the entire operation. If None, a default value on
the back will be used. If present and excessively large, the back may
limit the operation to a smaller duration of its choice. May be present
for any ticket kind; setting a value on a later ticket allows fronts
to request time extensions (or even time reductions!) on in-progress
operations. | 6259904071ff763f4b5e8a33 |
class CableShieldMaterialKind(str): <NEW_LINE> <INDENT> pass | Values are: other, lead, steel, aluminum, copper
| 625990401d351010ab8f4db2 |
class Changelog: <NEW_LINE> <INDENT> RAW_CHANGELOG_URL = 'https://raw.githubusercontent.com/kyb3r/modmail/master/CHANGELOG.md' <NEW_LINE> CHANGELOG_URL = 'https://github.com/kyb3r/modmail/blob/master/CHANGELOG.md' <NEW_LINE> VERSION_REGEX = re.compile(r'# (v\d+\.\d+\.\d+)([\S\s]*?(?=# v|$))') <NEW_LINE> def __init__(self, bot: Bot, text: str): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> self.text = text <NEW_LINE> self.versions = [Version(bot, *m) for m in self.VERSION_REGEX.findall(text)] <NEW_LINE> <DEDENT> @property <NEW_LINE> def latest_version(self) -> Version: <NEW_LINE> <INDENT> return self.versions[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def embeds(self) -> List[Embed]: <NEW_LINE> <INDENT> return [v.embed for v in self.versions] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def from_url(cls, bot: Bot, url: str = '') -> 'Changelog': <NEW_LINE> <INDENT> url = url or cls.RAW_CHANGELOG_URL <NEW_LINE> resp = await bot.session.get(url) <NEW_LINE> return cls(bot, await resp.text()) | This class represents the complete changelog of Modmail.
Parameters
----------
bot : Bot
The Modmail bot.
text : str
The complete changelog text.
Attributes
----------
bot : Bot
The Modmail bot.
text : str
The complete changelog text.
versions : List[Version]
A list of `Version`'s within the changelog.
Class Attributes
----------------
RAW_CHANGELOG_URL : str
The URL to Modmail changelog.
VERSION_REGEX : re.Pattern
The regex used to parse the versions. | 6259904030c21e258be99aa1 |
@ROI_BOX_HEAD_REGISTRY.register() <NEW_LINE> class FastRCNNConvFCHead(nn.Sequential): <NEW_LINE> <INDENT> @configurable <NEW_LINE> def __init__( self, input_shape: ShapeSpec, *, conv_dims: List[int], fc_dims: List[int], conv_norm="" ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> assert len(conv_dims) + len(fc_dims) > 0 <NEW_LINE> self._output_size = (input_shape.channels, input_shape.height, input_shape.width) <NEW_LINE> self.conv_norm_relus = [] <NEW_LINE> for k, conv_dim in enumerate(conv_dims): <NEW_LINE> <INDENT> conv = Conv2d( self._output_size[0], conv_dim, kernel_size=3, padding=1, bias=not conv_norm, norm=get_norm(conv_norm, conv_dim), activation=nn.ReLU(), ) <NEW_LINE> self.add_module("conv{}".format(k + 1), conv) <NEW_LINE> self.conv_norm_relus.append(conv) <NEW_LINE> self._output_size = (conv_dim, self._output_size[1], self._output_size[2]) <NEW_LINE> <DEDENT> self.fcs = [] <NEW_LINE> for k, fc_dim in enumerate(fc_dims): <NEW_LINE> <INDENT> if k == 0: <NEW_LINE> <INDENT> self.add_module("flatten", nn.Flatten()) <NEW_LINE> <DEDENT> fc = Linear(int(np.prod(self._output_size)), fc_dim) <NEW_LINE> self.add_module("fc{}".format(k + 1), fc) <NEW_LINE> self.add_module("fc_relu{}".format(k + 1), nn.ReLU()) <NEW_LINE> self.fcs.append(fc) <NEW_LINE> self._output_size = fc_dim <NEW_LINE> <DEDENT> for layer in self.conv_norm_relus: <NEW_LINE> <INDENT> weight_init.c2_msra_fill(layer) <NEW_LINE> <DEDENT> for layer in self.fcs: <NEW_LINE> <INDENT> weight_init.c2_xavier_fill(layer) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def from_config(cls, cfg, input_shape): <NEW_LINE> <INDENT> num_conv = cfg.MODEL.ROI_BOX_HEAD.NUM_CONV <NEW_LINE> conv_dim = cfg.MODEL.ROI_BOX_HEAD.CONV_DIM <NEW_LINE> num_fc = cfg.MODEL.ROI_BOX_HEAD.NUM_FC <NEW_LINE> fc_dim = cfg.MODEL.ROI_BOX_HEAD.FC_DIM <NEW_LINE> return { "input_shape": input_shape, "conv_dims": [conv_dim] * num_conv, "fc_dims": [fc_dim] * num_fc, "conv_norm": cfg.MODEL.ROI_BOX_HEAD.NORM, } <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> for layer in self: <NEW_LINE> <INDENT> x = layer(x) <NEW_LINE> <DEDENT> return x <NEW_LINE> <DEDENT> @property <NEW_LINE> @torch.jit.unused <NEW_LINE> def output_shape(self): <NEW_LINE> <INDENT> o = self._output_size <NEW_LINE> if isinstance(o, int): <NEW_LINE> <INDENT> return ShapeSpec(channels=o) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ShapeSpec(channels=o[0], height=o[1], width=o[2]) | A head with several 3x3 conv layers (each followed by norm & relu) and then
several fc layers (each followed by relu). | 6259904024f1403a92686217 |
class SigV2Auth(BaseSigner): <NEW_LINE> <INDENT> def __init__(self, credentials): <NEW_LINE> <INDENT> self.credentials = credentials <NEW_LINE> <DEDENT> def calc_signature(self, request, params): <NEW_LINE> <INDENT> logger.debug("Calculating signature using v2 auth.") <NEW_LINE> split = urlsplit(request.url) <NEW_LINE> path = split.path <NEW_LINE> if len(path) == 0: <NEW_LINE> <INDENT> path = '/' <NEW_LINE> <DEDENT> string_to_sign = '%s\n%s\n%s\n' % (request.method, split.netloc, path) <NEW_LINE> lhmac = hmac.new(self.credentials.secret_key.encode('utf-8'), digestmod=sha256) <NEW_LINE> pairs = [] <NEW_LINE> for key in sorted(params): <NEW_LINE> <INDENT> if key == 'Signature': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> value = str(params[key]) <NEW_LINE> pairs.append(quote(key.encode('utf-8'), safe='') + '=' + quote(value.encode('utf-8'), safe='-_~')) <NEW_LINE> <DEDENT> qs = '&'.join(pairs) <NEW_LINE> string_to_sign += qs <NEW_LINE> logger.debug('String to sign: %s', string_to_sign) <NEW_LINE> lhmac.update(string_to_sign.encode('utf-8')) <NEW_LINE> b64 = base64.b64encode(lhmac.digest()).strip().decode('utf-8') <NEW_LINE> return (qs, b64) <NEW_LINE> <DEDENT> def add_auth(self, request): <NEW_LINE> <INDENT> if self.credentials is None: <NEW_LINE> <INDENT> raise NoCredentialsError <NEW_LINE> <DEDENT> if request.data: <NEW_LINE> <INDENT> params = request.data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> params = request.param <NEW_LINE> <DEDENT> params['AWSAccessKeyId'] = self.credentials.access_key <NEW_LINE> params['SignatureVersion'] = '2' <NEW_LINE> params['SignatureMethod'] = 'HmacSHA256' <NEW_LINE> params['Timestamp'] = time.strftime(ISO8601, time.gmtime()) <NEW_LINE> if self.credentials.token: <NEW_LINE> <INDENT> params['SecurityToken'] = self.credentials.token <NEW_LINE> <DEDENT> qs, signature = self.calc_signature(request, params) <NEW_LINE> params['Signature'] = signature <NEW_LINE> return request | Sign a request with Signature V2. | 62599040b830903b9686edc4 |
class LameAttrDict(dict): <NEW_LINE> <INDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> if name.startswith('__'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return dict.__getattribute__(self, name) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return dict.__getattribute__(self, name[2:]) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> return self[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError(name + ' not found') | A `dict` subclass that lets you access keys as using attribute notation.
To access built-in dict attributes and methods prefix the name with '__'.
WARNING: this probably won't work well with code expecting an dict because
calling normal `dict` methods won't work.
For example:
>>> d = LameAttrDict(foo=1, update=2, copy=3)
>>> d.foo
1
>>> d.copy
3
>>> d.__copy()
{'copy': 3, 'update': 2, 'foo': 1}
>>> d.__update({'update':4})
>>> d.update
4
>>> d['update']
4
>>> list(d.__iterkeys()) == d.__keys() == list(d)
True
>>> d[10] = '10'
>>> len(d)
4
>>> del d[10]
>>> len(d)
3
| 6259904066673b3332c3168e |
class Error(Exception): <NEW_LINE> <INDENT> pass | Base class for all exceptions in skime | 6259904007d97122c4217f35 |
class MockDatabaseTest(AppTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(MockDatabaseTest, self).setUp() <NEW_LINE> self.db = MockSession() <NEW_LINE> self.object_session_patcher = mock.patch( 'atmcraft.model.account.object_session') <NEW_LINE> self.object_session = self.object_session_patcher.start() <NEW_LINE> self.object_session.return_value = self.db <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(MockDatabaseTest, self).tearDown() <NEW_LINE> self.object_session_patcher.stop() | Run tests against a mock query system. | 6259904050485f2cf55dc21a |
class LedgerEntryType(IntEnum): <NEW_LINE> <INDENT> ACCOUNT = 0 <NEW_LINE> TRUSTLINE = 1 <NEW_LINE> OFFER = 2 <NEW_LINE> DATA = 3 <NEW_LINE> CLAIMABLE_BALANCE = 4 <NEW_LINE> def pack(self, packer: Packer) -> None: <NEW_LINE> <INDENT> packer.pack_int(self.value) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def unpack(cls, unpacker: Unpacker) -> "LedgerEntryType": <NEW_LINE> <INDENT> value = unpacker.unpack_int() <NEW_LINE> return cls(value) <NEW_LINE> <DEDENT> def to_xdr_bytes(self) -> bytes: <NEW_LINE> <INDENT> packer = Packer() <NEW_LINE> self.pack(packer) <NEW_LINE> return packer.get_buffer() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_xdr_bytes(cls, xdr: bytes) -> "LedgerEntryType": <NEW_LINE> <INDENT> unpacker = Unpacker(xdr) <NEW_LINE> return cls.unpack(unpacker) <NEW_LINE> <DEDENT> def to_xdr(self) -> str: <NEW_LINE> <INDENT> xdr_bytes = self.to_xdr_bytes() <NEW_LINE> return base64.b64encode(xdr_bytes).decode() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_xdr(cls, xdr: str) -> "LedgerEntryType": <NEW_LINE> <INDENT> xdr_bytes = base64.b64decode(xdr.encode()) <NEW_LINE> return cls.from_xdr_bytes(xdr_bytes) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _missing_(cls, value): <NEW_LINE> <INDENT> raise ValueError( f"{value} is not a valid {cls.__name__}, please upgrade the SDK or submit an issue here: {__issues__}." ) | XDR Source Code
----------------------------------------------------------------
enum LedgerEntryType
{
ACCOUNT = 0,
TRUSTLINE = 1,
OFFER = 2,
DATA = 3,
CLAIMABLE_BALANCE = 4
};
---------------------------------------------------------------- | 625990406fece00bbacccc46 |
class EmptySet(Set): <NEW_LINE> <INDENT> __metaclass__ = Singleton <NEW_LINE> is_EmptySet = True <NEW_LINE> def _intersect(self, other): <NEW_LINE> <INDENT> return S.EmptySet <NEW_LINE> <DEDENT> @property <NEW_LINE> def _complement(self): <NEW_LINE> <INDENT> return S.UniversalSet <NEW_LINE> <DEDENT> @property <NEW_LINE> def _measure(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def _contains(self, other): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def as_relational(self, symbol): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def union(self, other): <NEW_LINE> <INDENT> return other <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter([]) | Represents the empty set. The empty set is available as a singleton
as S.EmptySet.
Examples
========
>>> from sympy import S, Interval
>>> S.EmptySet
EmptySet()
>>> Interval(1, 2).intersect(S.EmptySet)
EmptySet()
See Also
========
UniversalSet
References
==========
.. [1] http://en.wikipedia.org/wiki/Empty_set | 62599040d10714528d69efd7 |
@myaml.register <NEW_LINE> @connection.register <NEW_LINE> class OutputParameter(Parameter): <NEW_LINE> <INDENT> pass | output parameter | 62599040d4950a0f3b11178b |
class Role(models.Model): <NEW_LINE> <INDENT> title = models.CharField(verbose_name='角色名称',max_length=32) <NEW_LINE> permissions = models.ManyToManyField(verbose_name='具有的所有权限',to='Permission',blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "角色表" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.title | 角色表 | 6259904029b78933be26aa0e |
class IdentityTool(cherrypy.Tool): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> log.debug("Identity Tool initialized") <NEW_LINE> return super(IdentityTool, self).__init__("before_handler", self.before_handler, priority=30) <NEW_LINE> <DEDENT> def start_extension(self): <NEW_LINE> <INDENT> if not config.get('tools.identity.on', False): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not config.get('tools.visit.on', False): <NEW_LINE> <INDENT> raise identity.IdentityConfigurationException( "Visit tracking must be enabled (tools.visit.on)") <NEW_LINE> <DEDENT> log.info("Identity starting") <NEW_LINE> visitor.create_extension_model() <NEW_LINE> visit.enable_visit_plugin(visitor.IdentityVisitPlugin()) <NEW_LINE> <DEDENT> def before_handler(self, *args, **kwargs): <NEW_LINE> <INDENT> predicates = [] <NEW_LINE> predicate = kwargs.get('require', None) <NEW_LINE> if predicate is not None: <NEW_LINE> <INDENT> predicates.append(predicate) <NEW_LINE> <DEDENT> if hasattr(request, "tg_predicates"): <NEW_LINE> <INDENT> predicates.extend(request.tg_predicates) <NEW_LINE> <DEDENT> for predicate in predicates: <NEW_LINE> <INDENT> errors = [] <NEW_LINE> if not predicate.eval_with_object(identity.current, errors): <NEW_LINE> <INDENT> raise identity.IdentityFailure(errors) <NEW_LINE> <DEDENT> <DEDENT> request.tg_predicates = [] <NEW_LINE> <DEDENT> def __call__(self, require, *args, **kwargs): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> raise TypeError("The %r Tool does not accept positional arguments" " exept for 'require'; you must use keyword " "arguments." % self._name) <NEW_LINE> <DEDENT> kwargs['require'] = require <NEW_LINE> def tool_decorator(func): <NEW_LINE> <INDENT> if not hasattr(func, "_cp_config"): <NEW_LINE> <INDENT> func._cp_config = {} <NEW_LINE> <DEDENT> subspace = self.namespace + "." + self._name + "." <NEW_LINE> func._cp_config[subspace + "on"] = True <NEW_LINE> for k, v in kwargs.iteritems(): <NEW_LINE> <INDENT> func._cp_config[subspace + k] = v <NEW_LINE> <DEDENT> return func <NEW_LINE> <DEDENT> return tool_decorator | A TurboGears identity tool | 62599040d53ae8145f9196f3 |
class UserAdd(PMCommand): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(UserAdd, self).get_parser(prog_name) <NEW_LINE> parser.add_argument('identity') <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> identity = parsed_args.identity <NEW_LINE> pm = self._get_password_manager(parsed_args) <NEW_LINE> identity_fp = pm.get_key_fingerprint(identity) <NEW_LINE> self.logger.info('Adding user: {0} ({1})' .format(identity, identity_fp)) <NEW_LINE> pm.add_identity(identity_fp) | Add a user | 625990400fa83653e46f6170 |
class TestCodingStandards(unittest.TestCase): <NEW_LINE> <INDENT> def test_PythonFiles_HaveLicenseText(self): <NEW_LINE> <INDENT> pyfiles = find_python_files() <NEW_LINE> files_missing_license = [] <NEW_LINE> for filename in pyfiles: <NEW_LINE> <INDENT> file_basename = os.path.basename(filename) <NEW_LINE> if license_missing(filename): <NEW_LINE> <INDENT> files_missing_license.append(filename) <NEW_LINE> <DEDENT> <DEDENT> self.assertEquals(len(files_missing_license), 0, str(files_missing_license)) | test coding standards: check for license | 6259904021a7993f00c67204 |
class InvalidParameters(ParameterError): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.reasons = dict(kwargs.pop("params", {})) <NEW_LINE> kwargs["params"] = self.reasons.keys() <NEW_LINE> kwargs["error_type"] = ErrorTypes.invalid_parameters <NEW_LINE> ParameterError.__init__(self, *args, **kwargs) | Raised when some parameters failed validation.
@ivar reasons: reasons of the validation failure indexed
by parameter name.
@type reasons: {str: str} | 6259904050485f2cf55dc21b |
class CommonDataForm(CommonProperties): <NEW_LINE> <INDENT> residence = MySelectField( label=_(u'Населённый пункт'), choices=[(str(R.id), R.name) for R in models.Residence.all()], blank_text=_(u'Выберите населённый пункт'), allow_blank=True ) <NEW_LINE> dateFrom = MFDateField(_(u'с'), [validators.InputRequired(_(u'Вы не указали дату "с".'))]) <NEW_LINE> dateTo = MFDateField(_(u'по'), [validators.InputRequired(_(u'Вы не указали дату "по".'))]) <NEW_LINE> submit = SubmitField(_(u'Показать')) <NEW_LINE> def validate_dateFrom(form, field): <NEW_LINE> <INDENT> if field.data and form.dateTo.data: <NEW_LINE> <INDENT> if field.data > form.dateTo.data: <NEW_LINE> <INDENT> raise ValidationError(_(u'Дата "с" не может быть позднее даты "по".')) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def validate_residence(form, field): <NEW_LINE> <INDENT> if form.weatherProps.data and not field.data: <NEW_LINE> <INDENT> raise ValidationError(_(u'Если вы выбрали данные погоды, то следует выбрать и населённый пункт.')) <NEW_LINE> <DEDENT> <DEDENT> def validate_indiceProps(form, field): <NEW_LINE> <INDENT> if not any((form.indiceProps.data, form.commodityProps.data, form.currencyProps.data, form.astroProps.data, form.geomagneticProps.data, form.weatherProps.data)): <NEW_LINE> <INDENT> raise ValidationError(_(u'Нужно выбрать хотя бы один показатель.')) | Главная форма на странице /show_common_data | 6259904021bff66bcd723f01 |
class AdbLogcat(object): <NEW_LINE> <INDENT> def __init__(self, process, filename, logger): <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self.p = process <NEW_LINE> self.name = filename <NEW_LINE> if self.p.stderr: <NEW_LINE> <INDENT> self.p.stderr.close() <NEW_LINE> <DEDENT> self.logger.info("Adblogcat({}): start".format(self.name)) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.p.poll() <NEW_LINE> if self.p.returncode is None: <NEW_LINE> <INDENT> with ignored(OSError): <NEW_LINE> <INDENT> self.p.kill() <NEW_LINE> <DEDENT> self.p.wait() <NEW_LINE> <DEDENT> if self.p.stdout: <NEW_LINE> <INDENT> self.p.stdout.close() <NEW_LINE> <DEDENT> <DEDENT> def isalive(self): <NEW_LINE> <INDENT> self.logger.info("Adblogcat({}): isalive".format(self.name)) <NEW_LINE> self.p.poll() <NEW_LINE> if self.p.returncode is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.close() <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def join(self, timeout=None): <NEW_LINE> <INDENT> self.logger.info("Adblogcat({}): join".format(self.name)) <NEW_LINE> self.p.poll() <NEW_LINE> start_time = time.time() <NEW_LINE> if timeout is None: <NEW_LINE> <INDENT> _timeout = 99999999 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _timeout = timeout <NEW_LINE> <DEDENT> while self.p.returncode is None and time.time() - start_time < _timeout: <NEW_LINE> <INDENT> self.p.poll() <NEW_LINE> time.sleep(ADBGAP) <NEW_LINE> <DEDENT> return not self.isalive() <NEW_LINE> <DEDENT> def filename(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.logger.info("Adblogcat({}): close".format(self.name)) <NEW_LINE> self.p.poll() <NEW_LINE> if self.p.returncode is None: <NEW_LINE> <INDENT> with ignored(OSError): <NEW_LINE> <INDENT> self.logger.info("Adblogcat({}): kill adb process".format(self.name)) <NEW_LINE> self.p.kill() <NEW_LINE> <DEDENT> self.p.wait() <NEW_LINE> self.logger.debug("Adblogcat({}): adb logcat close".format(self.name)) <NEW_LINE> <DEDENT> if self.p.stdout: <NEW_LINE> <INDENT> self.p.stdout.close() | AdbLogcat, offer easy handle for adb logcat process
It should be created by AdbWrapper.logcat
Offer below function:
isalive()
join()
close()
filename() | 6259904023e79379d538d796 |
class OrganizationListView(generics.ListCreateAPIView): <NEW_LINE> <INDENT> authentication_classes = (TokenAuthentication,) <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> queryset = Organization.objects.all() <NEW_LINE> serializer_class = OrganizationSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return get_objects_for_user(self.request.user, "view_organization", Organization.objects.all()) | Returns a list of all organizations. | 62599040ec188e330fdf9b31 |
class ShowInterface(QuantumInterfaceCommand, show.ShowOne): <NEW_LINE> <INDENT> api = 'network' <NEW_LINE> log = logging.getLogger(__name__ + '.ShowInterface') <NEW_LINE> def get_data(self, parsed_args): <NEW_LINE> <INDENT> self.log.debug('get_data(%s)' % parsed_args) <NEW_LINE> quantum_client = self.app.client_manager.quantum <NEW_LINE> quantum_client.tenant = parsed_args.tenant_id <NEW_LINE> quantum_client.format = parsed_args.request_format <NEW_LINE> iface = quantum_client.show_port_attachment( parsed_args.net_id, parsed_args.port_id)['attachment'] <NEW_LINE> if iface: <NEW_LINE> <INDENT> if 'id' not in iface: <NEW_LINE> <INDENT> iface['id'] = '<none>' <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iface = {'': ''} <NEW_LINE> <DEDENT> return zip(*sorted(iface.iteritems())) | Show interface on a given port | 6259904015baa72349463229 |
class MissingResolutionError(OpencastError): <NEW_LINE> <INDENT> def __init__(self, resolution): <NEW_LINE> <INDENT> self.resolution = resolution <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Resolution not support {0}.".format(self.resolution) | Error for invalid resolutions. | 62599040097d151d1a2c22ff |
class PixelShuffle(HybridBlock): <NEW_LINE> <INDENT> def __init__(self, channels, scale_factor, in_size, fixed_size, **kwargs): <NEW_LINE> <INDENT> super(PixelShuffle, self).__init__(**kwargs) <NEW_LINE> assert (channels % scale_factor % scale_factor == 0) <NEW_LINE> self.channels = channels <NEW_LINE> self.scale_factor = scale_factor <NEW_LINE> self.in_size = in_size <NEW_LINE> self.fixed_size = fixed_size <NEW_LINE> <DEDENT> def hybrid_forward(self, F, x): <NEW_LINE> <INDENT> f1 = self.scale_factor <NEW_LINE> f2 = self.scale_factor <NEW_LINE> if not self.fixed_size: <NEW_LINE> <INDENT> x = x.reshape((0, -4, -1, f1 * f2, 0, 0)) <NEW_LINE> x = x.reshape((0, 0, -4, f1, f2, 0, 0)) <NEW_LINE> x = x.transpose((0, 1, 4, 2, 5, 3)) <NEW_LINE> x = x.reshape((0, 0, -3, -3)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_channels = self.channels // f1 // f2 <NEW_LINE> h, w = self.in_size <NEW_LINE> x = x.reshape((0, new_channels, f1 * f2, h, w)) <NEW_LINE> x = x.reshape((0, new_channels, f1, f2, h, w)) <NEW_LINE> x = x.transpose((0, 1, 4, 2, 5, 3)) <NEW_LINE> x = x.reshape((0, new_channels, h * f1, w * f2)) <NEW_LINE> <DEDENT> return x | Pixel-shuffle operation from 'Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel
Convolutional Neural Network,' https://arxiv.org/abs/1609.05158.
Parameters:
----------
scale_factor : int
Multiplier for spatial size.
in_size : tuple of 2 int
Spatial size of the input heatmap tensor.
fixed_size : bool
Whether to expect fixed spatial size of input image. | 625990401d351010ab8f4db6 |
class LaboratoryForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = LaboratoryProfile | Form class 'Laboratory' | 62599040e64d504609df9d1d |
class Conf(_config.ConfigNamespace): <NEW_LINE> <INDENT> timeout = _config.ConfigItem(60, "Timeout in seconds.") <NEW_LINE> archive_url = _config.ConfigItem( _url_list, 'The ALMA Archive mirror to use.') <NEW_LINE> auth_url = _config.ConfigItem( auth_urls, 'ALMA Central Authentication Service URLs' ) <NEW_LINE> username = _config.ConfigItem( "", 'Optional default username for ALMA archive.') | Configuration parameters for `astroquery.alma`. | 62599040dc8b845886d5484f |
class QcInput(MSONable): <NEW_LINE> <INDENT> def __init__(self, jobs): <NEW_LINE> <INDENT> jobs = jobs if isinstance(jobs, list) else [jobs] <NEW_LINE> for j in jobs: <NEW_LINE> <INDENT> if not isinstance(j, QcTask): <NEW_LINE> <INDENT> raise ValueError("jobs must be a list QcInput object") <NEW_LINE> <DEDENT> self.jobs = jobs <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "\n@@@\n\n\n".join([str(j) for j in self.jobs]) <NEW_LINE> <DEDENT> def write_file(self, filename): <NEW_LINE> <INDENT> with zopen(filename, "w") as f: <NEW_LINE> <INDENT> f.write(self.__str__()) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def to_dict(self): <NEW_LINE> <INDENT> return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "jobs": [j.to_dict for j in self.jobs]} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, d): <NEW_LINE> <INDENT> jobs = [QcTask.from_dict(j) for j in d["jobs"]] <NEW_LINE> return QcInput(jobs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, contents): <NEW_LINE> <INDENT> qc_contents = contents.split("@@@") <NEW_LINE> jobs = [QcTask.from_string(cont) for cont in qc_contents] <NEW_LINE> return QcInput(jobs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_file(cls, filename): <NEW_LINE> <INDENT> with zopen(filename) as f: <NEW_LINE> <INDENT> return cls.from_string(f.read()) | An object representing a multiple step QChem input file. | 6259904015baa7234946322a |
class TestTwoingTwoClasses(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.criterion = criteria.Twoing <NEW_LINE> self.config = dataset.load_config(os.path.join( '.', 'data', 'train_dataset1')) <NEW_LINE> self.data = dataset.Dataset(self.config["filepath"], self.config["key attrib index"], self.config["class attrib index"], self.config["split char"], self.config["missing value string"], load_numeric=True) <NEW_LINE> self.decision_tree = decision_tree.DecisionTree(self.criterion) <NEW_LINE> <DEDENT> def test_twoing(self): <NEW_LINE> <INDENT> self.decision_tree.train(self.data, list(range(self.data.num_samples)), max_depth=1, min_samples_per_node=1, use_stop_conditions=False, max_p_value_chi_sq=None) <NEW_LINE> self.assertEqual(self.decision_tree.get_root_node().node_split.separation_attrib_index, 0) <NEW_LINE> self.assertEqual(self.decision_tree.get_root_node().node_split.splits_values, [set([0]), set([1])]) <NEW_LINE> self.assertEqual(self.decision_tree.get_root_node().node_split.values_to_split, {0:0, 1:1}) <NEW_LINE> self.assertEqual(self.decision_tree.get_root_node().node_split.criterion_value, 0.5) | Tests Twoing criterion using dataset with two classes. | 6259904021bff66bcd723f03 |
class TokenSession(requests.Session): <NEW_LINE> <INDENT> def __init__(self, capacity, fill_rate): <NEW_LINE> <INDENT> requests.Session.__init__(self) <NEW_LINE> self.capacity = float(capacity) <NEW_LINE> self._tokens = float(capacity) <NEW_LINE> self.consumed_tokens = 0 <NEW_LINE> self.fill_rate = float(fill_rate) <NEW_LINE> self.timestamp = time() <NEW_LINE> <DEDENT> def consume(self, tokens): <NEW_LINE> <INDENT> self.update_tokens() <NEW_LINE> if tokens < self._tokens: <NEW_LINE> <INDENT> self._tokens -= tokens <NEW_LINE> self.consumed_tokens += tokens <NEW_LINE> LOGGER.debug("Consuming {0} token(s), total tokens consumed so far: {1}".format(tokens, self.consumed_tokens)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def request(self, *args, **kwargs): <NEW_LINE> <INDENT> while not self.consume(1): <NEW_LINE> <INDENT> LOGGER.debug("Waiting for token bucket to refull...") <NEW_LINE> sleep(1) <NEW_LINE> <DEDENT> return requests.Session.request(self, *args, **kwargs) <NEW_LINE> <DEDENT> def update_tokens(self): <NEW_LINE> <INDENT> if self._tokens < self.capacity: <NEW_LINE> <INDENT> now = time() <NEW_LINE> delta = self.fill_rate * (now - self.timestamp) <NEW_LINE> self._tokens = min(self.capacity, self._tokens + delta) <NEW_LINE> self.timestamp = now <NEW_LINE> <DEDENT> return self._tokens <NEW_LINE> <DEDENT> tokens = (update_tokens) <NEW_LINE> def base_get(self, url_path, *args, **kwargs): <NEW_LINE> <INDENT> return self.get(config.get('Main', 'baseURL') + url_path, *args, **kwargs) <NEW_LINE> <DEDENT> def base_post(self, url_path, *args, **kwargs): <NEW_LINE> <INDENT> return self.post(config.get('Main', 'baseURL') + url_path, *args, **kwargs) | Allow rate-limiting requests to a site | 62599040b830903b9686edc6 |
class PowNode(BinaryNode): <NEW_LINE> <INDENT> def __init__(self, lhs, rhs): <NEW_LINE> <INDENT> super(PowNode, self).__init__(lhs, rhs, '**', 4, 'right', Constant(1)) <NEW_LINE> <DEDENT> def simplify_specific(self): <NEW_LINE> <INDENT> left=self.lhs <NEW_LINE> right=self.rhs <NEW_LINE> if right==Constant(0): <NEW_LINE> <INDENT> return Constant(1) <NEW_LINE> <DEDENT> elif type(left)==PowNode: <NEW_LINE> <INDENT> return (left.lhs**(left.rhs*right)).simplify() <NEW_LINE> <DEDENT> elif type(left)==MulNode: <NEW_LINE> <INDENT> return (left.lhs**right*left.rhs**right).simplify() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return left**right <NEW_LINE> <DEDENT> <DEDENT> def derivative_specific(self,variable): <NEW_LINE> <INDENT> L=self.lhs.simplify() <NEW_LINE> R=self.rhs.simplify() <NEW_LINE> left=L.derivative(variable) <NEW_LINE> right=R.derivative(variable) <NEW_LINE> if str(variable) in str(L): <NEW_LINE> <INDENT> if str(variable) in str(R): <NEW_LINE> <INDENT> return (Constant(math.e)**(R*LogNode(L))*(right*LogNode(L)+left*R/L)).simplify() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ((R*L**(R-Constant(1)))*left).simplify() <NEW_LINE> <DEDENT> <DEDENT> elif str(variable) in str(R): <NEW_LINE> <INDENT> return (L**R*LogNode(L)*right).simplify() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Constant(0) | Represents the power operator | 625990403eb6a72ae038b904 |
class MyList(list): <NEW_LINE> <INDENT> def print_sorted(self): <NEW_LINE> <INDENT> print(sorted(self)) | myList - This class inherits from list
Args:
list: the list superclass | 62599040711fe17d825e15e9 |
class DeleteWorkResponse(BaseOrcidClientResponse): <NEW_LINE> <INDENT> specific_exceptions = (exceptions.OrcidNotFoundException, exceptions.PutcodeNotFoundDeleteException, exceptions.TokenWithWrongPermissionException,) | An empty dict-like object. | 6259904045492302aabfd775 |
class HTTPLoopDetected(HTTPServerError): <NEW_LINE> <INDENT> status_code = 508 | HTTP/508 - Loop Detected | 62599040d53ae8145f9196f7 |
class Base: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.id_ = create_id() <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> file_path = r'%s/%s' % (self.save_path, self.id_) <NEW_LINE> with open(file_path, 'wb') as f: <NEW_LINE> <INDENT> pickle.dump(self, f) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_all_objects(cls): <NEW_LINE> <INDENT> obj_lst = [] <NEW_LINE> obj_id_l = os.listdir(cls.save_path) <NEW_LINE> for obj_id in obj_id_l: <NEW_LINE> <INDENT> obj = pickle.load(open('%s/%s' % (cls.save_path, obj_id), 'rb')) <NEW_LINE> obj_lst.append(obj) <NEW_LINE> <DEDENT> return obj_lst <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> res = '' <NEW_LINE> for i in self.__dict__.items(): <NEW_LINE> <INDENT> res += i[0].ljust(20) + i[1] + '\n' <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_obj_by_name(cls, name): <NEW_LINE> <INDENT> id_l = os.listdir(cls.save_path) <NEW_LINE> obj_lst = [pickle.load(open('%s/%s' % (cls.save_path, id), 'rb')) for id in id_l] <NEW_LINE> target_obj = None <NEW_LINE> for obj in obj_lst: <NEW_LINE> <INDENT> if obj.name == name: <NEW_LINE> <INDENT> target_obj = obj <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return target_obj <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_obj_by_id(cls, id_str): <NEW_LINE> <INDENT> id_l = os.listdir(cls.save_path) <NEW_LINE> obj_lst = [pickle.load(open('%s/%s' % (cls.save_path, _id), 'rb')) for _id in id_l] <NEW_LINE> target_obj = None <NEW_LINE> for obj in obj_lst: <NEW_LINE> <INDENT> if obj.id_ == id_str: <NEW_LINE> <INDENT> target_obj = obj <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return target_obj | 基类,用户继承属性 | 6259904030c21e258be99aa8 |
class Params(object): <NEW_LINE> <INDENT> def __init__(self, param_file=None): <NEW_LINE> <INDENT> self.param_file = param_file <NEW_LINE> if param_file == None: return <NEW_LINE> self.yaml = YAML() <NEW_LINE> self.params = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.params = self.yaml.load(pathlib.Path(self.param_file)) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise ParameterLoadError("parameter loading of '%s' failed: %s" % (self.param_file, str(e))) <NEW_LINE> <DEDENT> <DEDENT> def is_host(self,host): <NEW_LINE> <INDENT> return host in self.params if self.params else None <NEW_LINE> <DEDENT> def get_host_params(self,host): <NEW_LINE> <INDENT> return (self.params.get(host,None) or self.params.get('host',None)) if self.params else None <NEW_LINE> <DEDENT> def get_actor_params(self,host,actor): <NEW_LINE> <INDENT> host_params = self.get_host_params(host) <NEW_LINE> return host_params.get(actor,None) if host_params else None <NEW_LINE> <DEDENT> def get_comp_params(self,host,actor,component): <NEW_LINE> <INDENT> actor_params = self.get_actor_params(host, actor) <NEW_LINE> return actor_params.get(component,None) if actor_params else None | Parameters are stored as YAML files, of the following format:
hostname_or_host:
actor_name:
component_name:
param_name: param_value | 62599040b57a9660fecd2d16 |
class WeekDay(VbaLibraryFunc): <NEW_LINE> <INDENT> def eval(self, context, params=None): <NEW_LINE> <INDENT> context = context <NEW_LINE> if ((params is None) or (len(params) == 0)): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> date_str = utils.safe_str_convert(params[0]).replace("#", "") <NEW_LINE> date_obj = None <NEW_LINE> if (date_str.count("/") == 2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> date_obj = datetime.strptime(date_str, '%m/%d/%Y') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if (log.getEffectiveLevel() == logging.DEBUG): <NEW_LINE> <INDENT> log.debug("WeekDay() exception: " + utils.safe_str_convert(e)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if (date_obj is not None): <NEW_LINE> <INDENT> r = date_obj.weekday() <NEW_LINE> r += 2 <NEW_LINE> if (log.getEffectiveLevel() == logging.DEBUG): <NEW_LINE> <INDENT> log.debug("WeekDay(%r): return %r" % (date_str, r)) <NEW_LINE> <DEDENT> return r <NEW_LINE> <DEDENT> return 1 <NEW_LINE> <DEDENT> def num_args(self): <NEW_LINE> <INDENT> return 1 | Emulate VBA WeekDay function.
| 625990408da39b475be0448a |
class Update(BaseQuery): <NEW_LINE> <INDENT> def __init__(self, table, mapping): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._table = table <NEW_LINE> self._mapping = mapping <NEW_LINE> <DEDENT> def set_mapping(self, mapping): <NEW_LINE> <INDENT> self._mapping = mapping <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if len(self._conditions) > 0: <NEW_LINE> <INDENT> where = " AND ".join(self._conditions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> where = None <NEW_LINE> <DEDENT> return create_update_sql(self._table, self._mapping, where) | Update Query | 625990401f5feb6acb163e8f |
class Element: <NEW_LINE> <INDENT> tag = 'html' <NEW_LINE> indent = '\t' <NEW_LINE> def __init__(self, content=None, **kwargs): <NEW_LINE> <INDENT> if content is None: <NEW_LINE> <INDENT> self.content = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.content = [content] <NEW_LINE> <DEDENT> if kwargs is not None: <NEW_LINE> <INDENT> self.attribs = kwargs <NEW_LINE> <DEDENT> else: self.attribs = {} <NEW_LINE> <DEDENT> def append(self, new_text): <NEW_LINE> <INDENT> self.content.append(new_text) <NEW_LINE> <DEDENT> def add_attributes(self): <NEW_LINE> <INDENT> attributes = '' <NEW_LINE> for key, value in self.attribs.items(): <NEW_LINE> <INDENT> attributes += key <NEW_LINE> attributes += '="' <NEW_LINE> attributes += value +'"' <NEW_LINE> <DEDENT> return attributes <NEW_LINE> <DEDENT> def render(self, out_file, cur_ind = ''): <NEW_LINE> <INDENT> if self.attribs != {}: <NEW_LINE> <INDENT> out_file.write(f'{cur_ind}<{self.tag} {self.add_attributes()}>\n') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out_file.write(f'{cur_ind}<{self.tag}>\n') <NEW_LINE> <DEDENT> for item in self.content: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> item.render(out_file, cur_ind+self.indent) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> out_file.write(cur_ind+self.indent+item) <NEW_LINE> <DEDENT> out_file.write('\n') <NEW_LINE> <DEDENT> out_file.write(f'{cur_ind}</{self.tag}>') | class attribute to store html tags | 6259904094891a1f408ba044 |
class GradeEntry: <NEW_LINE> <INDENT> course_identifier: str <NEW_LINE> course_weight: float <NEW_LINE> course_grade: str <NEW_LINE> def __init__(self, course_identifier: str, course_weight: float, course_grade: str) -> None: <NEW_LINE> <INDENT> self.course_identifier = course_identifier <NEW_LINE> self.course_grade = course_grade <NEW_LINE> self.course_weight = course_weight <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return "{} {} {}".format(self.course_identifier, self.course_grade, self.course_weight) <NEW_LINE> <DEDENT> def __eq__(self, other: Any) -> bool: <NEW_LINE> <INDENT> return (type(self) == type(other) and self.course_weight == other.course_weight and self.course_grade == other.course_grade and self.course_identifier == other.course_identifier) <NEW_LINE> <DEDENT> def get_points(self) -> float: <NEW_LINE> <INDENT> raise NotImplementedError('subclass needed') | a grade system for students
course_identifier - which course
course_weight - credit
course_grade - grade for this course | 6259904023e79379d538d79a |
class SetupApplication(npyscreen.NPSAppManaged): <NEW_LINE> <INDENT> def onStart(self): <NEW_LINE> <INDENT> self.addForm('MAIN', MainMenuForm, name='dtk-tools v0.3.5') <NEW_LINE> self.addForm('EDIT', ConfigEditionForm, name='Block creation/edition form') <NEW_LINE> <DEDENT> def change_form(self, name): <NEW_LINE> <INDENT> self.switchForm(name) | Main application for the dtk setup command.
Forms available:
- MAIN: Display the menu
- DEFAULT_SELECTION: Form to select the default blocks
- EDIT: Form to edit/create a block | 62599040b830903b9686edc7 |
class Meta: <NEW_LINE> <INDENT> verbose_name = 'Rating' <NEW_LINE> verbose_name_plural = 'Ratings' | Meta definition for Rating. | 6259904073bcbd0ca4bcb526 |
class OSBreakDown(AbstractClientStatsCronFlow): <NEW_LINE> <INDENT> def BeginProcessing(self): <NEW_LINE> <INDENT> self.counters = [ _ActiveCounter(self.stats.Schema.OS_HISTOGRAM), _ActiveCounter(self.stats.Schema.VERSION_HISTOGRAM), _ActiveCounter(self.stats.Schema.RELEASE_HISTOGRAM), ] <NEW_LINE> <DEDENT> def FinishProcessing(self): <NEW_LINE> <INDENT> for counter in self.counters: <NEW_LINE> <INDENT> counter.Save(self.stats) <NEW_LINE> <DEDENT> <DEDENT> def ProcessClient(self, client): <NEW_LINE> <INDENT> ping = client.Get(client.Schema.PING) <NEW_LINE> if not ping: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> system = client.Get(client.Schema.SYSTEM, "Unknown") <NEW_LINE> self.counters[0].Add(system, ping) <NEW_LINE> version = client.Get(client.Schema.VERSION, "Unknown") <NEW_LINE> self.counters[1].Add("%s %s" % (system, version), ping) <NEW_LINE> release = client.Get(client.Schema.OS_RELEASE, "Unknown") <NEW_LINE> self.counters[2].Add("%s %s %s" % (system, version, release), ping) | Records relative ratios of OS versions in 7 day actives. | 6259904015baa7234946322d |
class notify_remove4(BaseObj): <NEW_LINE> <INDENT> _attrlist = ("entry", "cookie") <NEW_LINE> def __init__(self, unpack): <NEW_LINE> <INDENT> self.entry = notify_entry4(unpack) <NEW_LINE> self.cookie = nfs_cookie4(unpack) | struct notify_remove4 {
notify_entry4 entry;
nfs_cookie4 cookie;
}; | 62599040b5575c28eb713617 |
class DPShowConfig(DP.get_sub(), QuickAppBase): <NEW_LINE> <INDENT> cmd = 'config' <NEW_LINE> def define_program_options(self, params): <NEW_LINE> <INDENT> params.add_flag('verbose') <NEW_LINE> params.add_string('type', help="Show only type t objects.", default='*') <NEW_LINE> <DEDENT> def go(self): <NEW_LINE> <INDENT> options = self.get_options() <NEW_LINE> allofthem = options.type == '*' <NEW_LINE> config = get_dp_config() <NEW_LINE> if options.type == 'distances' or options.type == True: <NEW_LINE> <INDENT> print('Distances:') <NEW_LINE> print(config.distances.summary_string_id_desc_patterns()) <NEW_LINE> <DEDENT> if options.type == 'algos' or allofthem: <NEW_LINE> <INDENT> print('Algorithms:') <NEW_LINE> print(config.algos.summary_string_id_desc_patterns()) <NEW_LINE> <DEDENT> if options.type == 'batches' or allofthem: <NEW_LINE> <INDENT> print('Batch experiments:') <NEW_LINE> print(config.batches.summary_string_id_desc_patterns()) <NEW_LINE> <DEDENT> if options.type == 'testcases' or allofthem: <NEW_LINE> <INDENT> if options.verbose: <NEW_LINE> <INDENT> print('Test cases:') <NEW_LINE> print(config.testcases.summary_string_id_desc_patterns()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n = len(config.testcases) <NEW_LINE> print('There are %d testcases; use -v to show them' % n) | Shows the configuration | 62599040d53ae8145f9196f9 |
class QuestionNotificationTestCase(TestCaseWithFactory): <NEW_LINE> <INDENT> layer = DatabaseFunctionalLayer <NEW_LINE> def makeQuestion(self): <NEW_LINE> <INDENT> asker = self.factory.makePerson() <NEW_LINE> product = self.factory.makeProduct() <NEW_LINE> naked_question_set = removeSecurityProxy(getUtility(IQuestionSet)) <NEW_LINE> question = naked_question_set.new( title='title', description='description', owner=asker, language=getUtility(ILanguageSet)['en'], product=product, distribution=None, sourcepackagename=None) <NEW_LINE> return question <NEW_LINE> <DEDENT> def test_init_enqueue(self): <NEW_LINE> <INDENT> question = self.makeQuestion() <NEW_LINE> event = FakeEvent() <NEW_LINE> event.user = self.factory.makePerson() <NEW_LINE> notification = FakeQuestionNotification(question, event) <NEW_LINE> self.assertEqual( notification.recipient_set.name, notification.job.metadata['recipient_set']) <NEW_LINE> self.assertEqual(notification.question, notification.job.question) <NEW_LINE> self.assertEqual(notification.user, notification.job.user) <NEW_LINE> self.assertEqual(notification.getSubject(), notification.job.subject) <NEW_LINE> self.assertEqual(notification.getBody(), notification.job.body) <NEW_LINE> self.assertEqual(notification.getHeaders(), notification.job.headers) | Test common question notification behavior. | 62599040dc8b845886d54853 |
class ptMarkerMarkerNameChangedMsg(ptMarkerMsg): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getGameCli(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getMarkerMsgType(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getType(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def markerId(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def upcastToFinalGameCliMsg(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def upcastToFinalMarkerMsg(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def upcastToGameMsg(self): <NEW_LINE> <INDENT> pass | Marker message received when the name of a marker is changed | 625990403eb6a72ae038b908 |
@pydantic.dataclasses.dataclass(config=Config) <NEW_LINE> class Canvas: <NEW_LINE> <INDENT> objs: typing.Dict[str, Dashboard] <NEW_LINE> def __post_init_post_parse__(self): <NEW_LINE> <INDENT> tabs = [(item, dash.view) for item, dash in self.objs.items()] <NEW_LINE> self._canvas = pn.Tabs(*tabs, tabs_location='above') <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> return pn.Row(self._canvas) | A Canvas is a collection of Dashboards. | 6259904010dbd63aa1c71e75 |
class disable(ChromeCommand): <NEW_LINE> <INDENT> def __init__(self): pass | Disables log domain, prevents further log entries from being reported to the client. | 6259904073bcbd0ca4bcb528 |
class Number(Expression): <NEW_LINE> <INDENT> def __init__(self, head, attributes=None): <NEW_LINE> <INDENT> if attributes is None: <NEW_LINE> <INDENT> attributes = [Attribute.Numeric, Attribute.Constant] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attributes += [Attribute.Numeric] <NEW_LINE> <DEDENT> super().__init__(head, attributes) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return self.__add__(other * Integer(-1)) <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __truediv__(self, other): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, Number) and other.head == self.head | Base class for every number expression. | 62599040baa26c4b54d50546 |
class AakashCenter(models.Model): <NEW_LINE> <INDENT> ac_id = models.IntegerField(max_length=6, unique=True) <NEW_LINE> quantity = models.IntegerField(max_length=7, default=0) <NEW_LINE> name = models.CharField(max_length=200, blank=True) <NEW_LINE> city = models.CharField(max_length=200, blank=True) <NEW_LINE> state = models.CharField(max_length=200, blank=True) <NEW_LINE> coordinator = models.OneToOneField(Coordinator) <NEW_LINE> active = models.BooleanField(default=False) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | Aakash centers.
| 6259904073bcbd0ca4bcb529 |
@python_2_unicode_compatible <NEW_LINE> class Room(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=255) <NEW_LINE> staff_only = models.BooleanField(default=False) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> @property <NEW_LINE> def websocket_group(self): <NEW_LINE> <INDENT> return Group("room-%s" % self.id) <NEW_LINE> <DEDENT> def send_message(self, message, user, msg_type=MSG_TYPE_MESSAGE): <NEW_LINE> <INDENT> final_msg = {'room': str(self.id), 'message': message, 'username': user.username, 'type': msg_type} <NEW_LINE> self.websocket_group.send({ "text": json.dumps(final_msg) }) | A room for people to chat | 6259904023849d37ff852358 |
class ServerInfo(DStruct): <NEW_LINE> <INDENT> pass | Information object returned by :func:`~dogecoinrpc.connection.DogecoinConnection.getinfo`.
- *errors* -- Number of errors.
- *blocks* -- Number of blocks.
- *paytxfee* -- Amount of transaction fee to pay.
- *keypoololdest* -- Oldest key in keypool.
- *genproclimit* -- Processor limit for generation.
- *connections* -- Number of connections to other clients.
- *difficulty* -- Current generating difficulty.
- *testnet* -- True if connected to testnet, False if on real network.
- *version* -- Dogecoin client version.
- *proxy* -- Proxy configured in client.
- *hashespersec* -- Number of hashes per second (if generation enabled).
- *balance* -- Total current server balance.
- *generate* -- True if generation enabled, False if not.
- *unlocked_until* -- Timestamp (seconds since epoch) after which the wallet
will be/was locked (if wallet encryption is enabled). | 625990403c8af77a43b6888b |
class DosFsLabel(FSLabelApp): <NEW_LINE> <INDENT> name = "dosfslabel" <NEW_LINE> reads = True <NEW_LINE> _label_regex = r'(?P<label>.*)' <NEW_LINE> def _writeLabelArgs(self, fs): <NEW_LINE> <INDENT> return [fs.device, fs.label] <NEW_LINE> <DEDENT> def _readLabelArgs(self, fs): <NEW_LINE> <INDENT> return [fs.device] | Application used by FATFS. | 6259904030c21e258be99aab |
class DexUnit(LogUnit): <NEW_LINE> <INDENT> @property <NEW_LINE> def _default_function_unit(self): <NEW_LINE> <INDENT> return dex <NEW_LINE> <DEDENT> @property <NEW_LINE> def _quantity_class(self): <NEW_LINE> <INDENT> return Dex | Logarithmic physical units expressed in magnitudes
Parameters
----------
physical_unit : `~astropy.units.Unit` or `string`
Unit that is encapsulated within the magnitude function unit.
If not given, dimensionless.
function_unit : `~astropy.units.Unit` or `string`
By default, this is ``dex`, but this allows one to use an equivalent
unit such as ``0.5 dex``. | 62599040dc8b845886d54855 |
class TestSyncServiceApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = isi_sdk_9_0_0.api.sync_service_api.SyncServiceApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_create_policies_policy_reset_item(self): <NEW_LINE> <INDENT> pass | SyncServiceApi unit test stubs | 6259904030c21e258be99aac |
class ImgTextCompositionBase(torch.nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ImgTextCompositionBase, self).__init__() <NEW_LINE> self.normalization_layer = torch_functions.NormalizationLayer( normalize_scale=4.0, learn_scale=True) <NEW_LINE> self.soft_triplet_loss = torch_functions.TripletLoss() <NEW_LINE> <DEDENT> def extract_img_feature(self, imgs): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def extract_text_feature(self, texts): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def compose_img_text(self, imgs, texts): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def compute_loss(self, imgs_query, modification_texts, imgs_target, soft_triplet_loss=True): <NEW_LINE> <INDENT> mod_img1 = self.compose_img_text(imgs_query, modification_texts) <NEW_LINE> mod_img1 = self.normalization_layer(mod_img1) <NEW_LINE> img2 = self.extract_img_feature(imgs_target) <NEW_LINE> img2 = self.normalization_layer(img2) <NEW_LINE> assert (mod_img1.shape[0] == img2.shape[0] and mod_img1.shape[1] == img2.shape[1]) <NEW_LINE> if soft_triplet_loss: <NEW_LINE> <INDENT> return self.compute_soft_triplet_loss_(mod_img1, img2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.compute_batch_based_classification_loss_(mod_img1, img2) <NEW_LINE> <DEDENT> <DEDENT> def compute_soft_triplet_loss_(self, mod_img1, img2): <NEW_LINE> <INDENT> triplets = [] <NEW_LINE> labels = list(range(mod_img1.shape[0])) + list(range(img2.shape[0])) <NEW_LINE> for i in range(len(labels)): <NEW_LINE> <INDENT> triplets_i = [] <NEW_LINE> for j in range(len(labels)): <NEW_LINE> <INDENT> if labels[i] == labels[j] and i != j: <NEW_LINE> <INDENT> for k in range(len(labels)): <NEW_LINE> <INDENT> if labels[i] != labels[k]: <NEW_LINE> <INDENT> triplets_i.append([i, j, k]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> np.random.shuffle(triplets_i) <NEW_LINE> triplets += triplets_i[:3] <NEW_LINE> <DEDENT> assert (triplets and len(triplets) < 2000) <NEW_LINE> return self.soft_triplet_loss(torch.cat([mod_img1, img2]), triplets) <NEW_LINE> <DEDENT> def compute_batch_based_classification_loss_(self, mod_img1, img2): <NEW_LINE> <INDENT> x = torch.mm(mod_img1, img2.transpose(0, 1)) <NEW_LINE> labels = torch.tensor(list(range(x.shape[0]))).long() <NEW_LINE> labels = torch.autograd.Variable(labels).cuda() <NEW_LINE> return F.cross_entropy(x, labels) | Base class for image + text composition. | 6259904007f4c71912bb06d0 |
class Parser(ConfigParser): <NEW_LINE> <INDENT> def get(self, section, option, default=None, cls=uni_cls, delimiter=','): <NEW_LINE> <INDENT> default = None if default is None else str(default) <NEW_LINE> try: <NEW_LINE> <INDENT> value = ConfigParser.get(self, section, option).strip() <NEW_LINE> <DEDENT> except NoSectionError: <NEW_LINE> <INDENT> if default is None: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> value = default <NEW_LINE> <DEDENT> except NoOptionError: <NEW_LINE> <INDENT> if default is None: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> value = default <NEW_LINE> <DEDENT> return smart_get(value, cls, delimiter) | Wrapper to ConfigParser class, with better get method. | 62599040be383301e0254ab7 |
class AuthorizationListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteCircuitAuthorization]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AuthorizationListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None) | Response for ListAuthorizations API service call retrieves all authorizations that belongs to an ExpressRouteCircuit.
:param value: The authorizations in an ExpressRoute Circuit.
:type value: list[~azure.mgmt.network.v2018_04_01.models.ExpressRouteCircuitAuthorization]
:param next_link: The URL to get the next set of results.
:type next_link: str | 62599040d6c5a102081e33c5 |
class botflags(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.GREEN = (0,175,0) <NEW_LINE> self.RED = (175,0,0) <NEW_LINE> self.BLACK = (255,255,255) | classdocs | 6259904007d97122c4217f3e |
class EntityCategory(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> LOCATION = "location" <NEW_LINE> ORGANIZATION = "organization" <NEW_LINE> PERSON = "person" <NEW_LINE> QUANTITY = "quantity" <NEW_LINE> DATETIME = "datetime" <NEW_LINE> URL = "url" <NEW_LINE> EMAIL = "email" | A string indicating what entity categories to return.
| 62599040d99f1b3c44d0693c |
class Comment(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'comments' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> body = db.Column(db.Text) <NEW_LINE> body_html = db.Column(db.Text) <NEW_LINE> timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) <NEW_LINE> disabled = db.Column(db.Boolean) <NEW_LINE> author_id = db.Column(db.Integer, db.ForeignKey('users.id')) <NEW_LINE> post_id = db.Column(db.Integer, db.ForeignKey('posts.id')) <NEW_LINE> @staticmethod <NEW_LINE> def on_changed_body(target, value, oldvalue, initiator): <NEW_LINE> <INDENT> allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'em', 'i', 'strong'] <NEW_LINE> target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> json_comment = { 'url': url_for('api.get_comment', id=self.id, _external=True), 'post': url_for('api.get_post', id=self.post_id, _external=True), 'body': self.body, 'body_html': self.body_html, 'timestamp': self.timestamp, 'author': url_for('api.get_user', id=self.author_id, _external=True) } <NEW_LINE> return json_comment <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json(json_comment): <NEW_LINE> <INDENT> body = json_comment.get('body') <NEW_LINE> if body is None or body == '': <NEW_LINE> <INDENT> raise ValidationError('comment does not have a body') <NEW_LINE> <DEDENT> return Comment(body=body) | 评论类 | 6259904050485f2cf55dc224 |
class XmlNs0SymbolData(object): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> 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, XmlNs0SymbolData): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62599040d99f1b3c44d0693d |
class YDirectionType(Serializable): <NEW_LINE> <INDENT> _fields = ('UVectECF', 'SampleSpacing', 'NumSamples', 'FirstSample') <NEW_LINE> _required = _fields <NEW_LINE> _numeric_format = {'SampleSpacing': FLOAT_FORMAT, } <NEW_LINE> UVectECF = UnitVectorDescriptor( 'UVectECF', XYZType, _required, strict=DEFAULT_STRICT, docstring='The unit vector in the Y direction.') <NEW_LINE> SampleSpacing = FloatDescriptor( 'SampleSpacing', _required, strict=DEFAULT_STRICT, docstring='The collection sample spacing in the Y direction in meters.') <NEW_LINE> NumSamples = IntegerDescriptor( 'NumSamples', _required, strict=DEFAULT_STRICT, docstring='The number of samples in the Y direction.') <NEW_LINE> FirstSample = IntegerDescriptor( 'FirstSample', _required, strict=DEFAULT_STRICT, docstring='The first sample index.') <NEW_LINE> def __init__(self, UVectECF=None, SampleSpacing=None, NumSamples=None, FirstSample=None, **kwargs): <NEW_LINE> <INDENT> if '_xml_ns' in kwargs: <NEW_LINE> <INDENT> self._xml_ns = kwargs['_xml_ns'] <NEW_LINE> <DEDENT> if '_xml_ns_key' in kwargs: <NEW_LINE> <INDENT> self._xml_ns_key = kwargs['_xml_ns_key'] <NEW_LINE> <DEDENT> self.UVectECF = UVectECF <NEW_LINE> self.SampleSpacing = SampleSpacing <NEW_LINE> self.NumSamples = NumSamples <NEW_LINE> self.FirstSample = FirstSample <NEW_LINE> super(YDirectionType, self).__init__(**kwargs) | The Y direction of the collect | 62599040b5575c28eb713619 |
class PasswordResetTests(ManifestTestCase): <NEW_LINE> <INDENT> def test_password_reset_view(self): <NEW_LINE> <INDENT> response = self.client.get(reverse("password_reset")) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertTemplateUsed(response, "manifest/password_reset_form.html") <NEW_LINE> self.assertTrue( isinstance(response.context["form"], PasswordResetForm) ) <NEW_LINE> <DEDENT> def test_password_reset_success(self): <NEW_LINE> <INDENT> response = self.client.post( reverse("password_reset"), data={"email": "[email protected]"} ) <NEW_LINE> self.assertRedirects(response, reverse("password_reset_done")) <NEW_LINE> self.assertEqual(len(mail.outbox), 1) <NEW_LINE> <DEDENT> def test_password_reset_invalid(self): <NEW_LINE> <INDENT> response = self.client.post( reverse("password_reset"), data={"email": "dummy"} ) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertTemplateUsed(response, "manifest/password_reset_form.html") <NEW_LINE> self.assertEqual( response.context["form"].errors["email"][0], _("Enter a valid email address."), ) <NEW_LINE> <DEDENT> def test_password_reset_fail(self): <NEW_LINE> <INDENT> response = self.client.post( reverse("password_reset"), data={"email": "[email protected]"} ) <NEW_LINE> self.assertRedirects(response, reverse("password_reset_done")) <NEW_LINE> self.assertEqual(len(mail.outbox), 0) | Tests for :class:`PasswordResetView
<manifest.views.PasswordResetView>`. | 6259904063b5f9789fe8640b |
class RPCInvalidRPC(RPCFault): <NEW_LINE> <INDENT> def __init__(self, error_data=None): <NEW_LINE> <INDENT> RPCFault.__init__(self, INVALID_REQUEST, ERROR_MESSAGE[INVALID_REQUEST], error_data) | Invalid rpc-package. (INVALID_REQUEST) | 6259904023849d37ff85235a |
class Failure(Try): <NEW_LINE> <INDENT> def __init__(self, exc): <NEW_LINE> <INDENT> self.failure = exc <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def map(self, func): <NEW_LINE> <INDENT> return Failure(self.failure) <NEW_LINE> <DEDENT> def get_or_raise(self): <NEW_LINE> <INDENT> raise self.failure <NEW_LINE> <DEDENT> def handle_error(self, func): <NEW_LINE> <INDENT> return Try.attempt(func, self.failure) | Represents the failed case of a computation that could fail with
an Exception. In this case, the instances value hold the exception
was raised during failure | 6259904007d97122c4217f3f |
class SRPClient(object): <NEW_LINE> <INDENT> def __init__(self, email, password, g=ck.DH_G, N=ck.DH_P, k=3): <NEW_LINE> <INDENT> self.email = email <NEW_LINE> self.password = password <NEW_LINE> self.g, self.N, self.k = g, N, k <NEW_LINE> self.server = None <NEW_LINE> self.session_key = None <NEW_LINE> self.salt = None <NEW_LINE> <DEDENT> def login(self, server, DH_keys=None): <NEW_LINE> <INDENT> if DH_keys is None: <NEW_LINE> <INDENT> public, private = ck.gen_DH_keys(p=self.N, g=self.g) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> public, private = DH_keys <NEW_LINE> <DEDENT> simple = server.simple <NEW_LINE> response = server.login(self.email, public) <NEW_LINE> self.server = server <NEW_LINE> if simple: <NEW_LINE> <INDENT> self.salt, server_public, scramble = response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.salt, server_public = response <NEW_LINE> scramble = srp_scrambler(public, server_public) <NEW_LINE> <DEDENT> m = sha256() <NEW_LINE> m.update(self.salt+bytes(self.password, 'utf-8')) <NEW_LINE> xH = m.digest() <NEW_LINE> x = int.from_bytes(xH, byteorder='big') <NEW_LINE> if simple: <NEW_LINE> <INDENT> S = pow(server_public, private+scramble*x, self.N) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> S = pow(self.g, x, self.N) <NEW_LINE> S = pow(server_public-self.k*S, private+scramble*x, self.N) <NEW_LINE> <DEDENT> m = sha256() <NEW_LINE> m.update(cu.int_to_bytes(S)) <NEW_LINE> self.session_key = m.digest() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> validation = hmac.new(self.session_key, self.salt, sha256).digest() <NEW_LINE> return self.server.validate(self.email, validation) | Mock up a client for Secure Remote Password authentication. | 62599040507cdc57c63a603c |
class ChangePasswordSuccessView(LoginRequiredViewMixin, TemplateView): <NEW_LINE> <INDENT> template_name = 'umanage/change_password/change_password_success.html' | View for when a password has successfully been changed. | 62599040d53ae8145f9196fd |
class NoParent(exception.DNSException): <NEW_LINE> <INDENT> pass | An attempt was made to get the parent of the root name
or the empty name. | 6259904026068e7796d4dbe7 |
class MoonPhase: <NEW_LINE> <INDENT> def __init__(self, date=datetime.now()): <NEW_LINE> <INDENT> if not isinstance(date, datetime): <NEW_LINE> <INDENT> self.date = datetime.strptime(date, '%Y-%m-%d') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.date = date <NEW_LINE> <DEDENT> self.__dict__.update(phase(self.date)) <NEW_LINE> self.phase_text = phase_string(self.phase) <NEW_LINE> <DEDENT> def __getattr__(self, a): <NEW_LINE> <INDENT> if a in ['new_date', 'q1_date', 'full_date', 'q3_date', 'nextnew_date']: <NEW_LINE> <INDENT> (self.new_date, self.q1_date, self.full_date, self.q3_date, self.nextnew_date) = phase_hunt(self.date) <NEW_LINE> return getattr(self, a) <NEW_LINE> <DEDENT> raise AttributeError(a) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> jdn = dt2jdn(self.date) <NEW_LINE> return "<%s(%d)>" % (self.__class__, jdn) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = "%s for %s, %s (%%%.2f illuminated)" % (self.__class__, self.date.strftime(), self.phase_text, self.illuminated * 100) <NEW_LINE> return s | I describe the phase of the moon.
I have the following properties:
date - a datetime instance
phase - my phase, in the range 0.0 .. 1.0
phase_text - a string describing my phase
illuminated - the percentage of the face of the moon illuminated
angular_diameter - as seen from Earth, in degrees.
sun_angular_diameter - as seen from Earth, in degrees.
new_date - the date of the most recent new moon
q1_date - the date the moon reaches 1st quarter in this cycle
full_date - the date of the full moon in this cycle
q3_date - the date the moon reaches 3rd quarter in this cycle
nextnew_date - the date of the next new moon | 6259904076d4e153a661dbc4 |
class Stack(DataStruct): <NEW_LINE> <INDENT> def push(self, item, priority=None): <NEW_LINE> <INDENT> self.list.append(item) | Implements a simple Stack data structure.
A stack uses the First-in-Last-out paradigm | 6259904007f4c71912bb06d2 |
class Handler(BaseHTTPRequestHandler): <NEW_LINE> <INDENT> def do_GET(self): <NEW_LINE> <INDENT> self.server.obst_counter += 1 <NEW_LINE> if self.path[:13] == '/status_code=': <NEW_LINE> <INDENT> status = int(self.path[13:]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> status = 404 <NEW_LINE> <DEDENT> self.send_response(status) <NEW_LINE> self.send_header('Content-type', 'text/plain') <NEW_LINE> self.end_headers() <NEW_LINE> <DEDENT> def log_message(self, *args, **kwargs): <NEW_LINE> <INDENT> pass | Router for the HTTP server | 62599040a79ad1619776b320 |
class BitEnum(Enum): <NEW_LINE> <INDENT> def __and__(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val = other.value <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> val = int(other) <NEW_LINE> <DEDENT> res = self.value & val <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return type(self)(res) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val = other.value <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> val = int(other) <NEW_LINE> <DEDENT> res = self.value | val <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return type(self)(res) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return self.value != 0 | A type of enum that supports certain binary operations between its
instances, namely & (bitwise-and) and | (bitwise-or). It also
defines a bool-conversion where the member with value 0 will
evaluate False, while all other values evaluate True.
For this to work properly, the underlying type of the members
should be int, and the subclass MUST define a "None"-like member
with value 0.
If a bitwise operation returns a result that is a valid member
of the Enum (perhaps a combination you wanted to use often and
thus defined within the enum itself), that enum member will be
returned. If the result is not a valid member of this enum, then
the int result of the operation will be returned instead. This
allows saving arbitrary combinations for use as flags.
These aspects allow for simple, useful statements like:
>>> if some_combined_MyBitEnum_value & MyBitEnum.memberA:
>>> ...
to see if 'MyBitEnum.memberA' is present in the bitwise combination
'some_combined_MyBitEnum_value' | 6259904021bff66bcd723f0b |
class AdderServicer(object): <NEW_LINE> <INDENT> def AddNumbers(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | The greeting service definition.
| 625990408da39b475be0448f |
class TestDataLoaderBase(unittest.TestCase): <NEW_LINE> <INDENT> def __init__(self, methodName='test_preprocessor', config=None, groundtruth=None, log=None): <NEW_LINE> <INDENT> super(TestDataLoaderBase, self).__init__(methodName) <NEW_LINE> self.config = config <NEW_LINE> self.groundtruth = groundtruth <NEW_LINE> self.log = log <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parametrize(test_data_loader, config=None, groundtruth=None, log=None): <NEW_LINE> <INDENT> testloader = unittest.TestLoader() <NEW_LINE> testnames = testloader.getTestCaseNames(test_data_loader) <NEW_LINE> suite = unittest.TestSuite() <NEW_LINE> for name in testnames: <NEW_LINE> <INDENT> suite.addTest(test_data_loader( name, config=config, groundtruth=groundtruth, log=log)) <NEW_LINE> <DEDENT> return suite | Base class for Test Data Loader to supply parameters to Unit Test Class
| 6259904023e79379d538d7a0 |
class CannotSaveException(IoException): <NEW_LINE> <INDENT> formatstring = "You tried to save a file with fileformat '{0}', but this format is not supported for writing files" | Raised when the given format cannot save data (only reading of data is supported for the format)
| 6259904066673b3332c3169a |
class Application(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255, unique=True) <NEW_LINE> verbose_name = models.CharField(max_length=255, blank=True, default='') <NEW_LINE> description = models.TextField(blank=True, default='') <NEW_LINE> repository = models.CharField(max_length=255, blank=True, default='') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s" % (self.verbose_name or self.name,) | The Software/Application | 625990404e696a045264e772 |
class UserDetails(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> user = MyUser.objects.get(pk=request.user.id) <NEW_LINE> user_photos = user.photos.all().order_by('-creation_date') <NEW_LINE> result = make_photo_pages(request, user_photos) <NEW_LINE> ctx = { 'user_photos': result, } <NEW_LINE> return render(request, 'photoalbum/user_photos.html', ctx) | User page displaying all his photos | 6259904073bcbd0ca4bcb52c |
class RouterHandler(BaseHandler): <NEW_LINE> <INDENT> def put(self, uaid): <NEW_LINE> <INDENT> client = self.application.clients.get(uaid) <NEW_LINE> if not client: <NEW_LINE> <INDENT> self.set_status(404, reason=None) <NEW_LINE> self.write("Client not connected.") <NEW_LINE> return <NEW_LINE> <DEDENT> if client.paused: <NEW_LINE> <INDENT> self.set_status(503, reason=None) <NEW_LINE> self.write("Client busy.") <NEW_LINE> return <NEW_LINE> <DEDENT> update = json.loads(self.request.body) <NEW_LINE> client.send_notification(update) <NEW_LINE> self.write("Client accepted for delivery") | Router Handler
Handles routing a notification to a connected client from an endpoint. | 62599040baa26c4b54d5054a |
class SpriteCollectionMixin(object): <NEW_LINE> <INDENT> def load_atlas(self, atlas_file): <NEW_LINE> <INDENT> raise NotImplemented <NEW_LINE> <DEDENT> def paint_regions(self, surface, regions): <NEW_LINE> <INDENT> for region in regions: <NEW_LINE> <INDENT> self.tile_group.repaint_rect(self.surface, region) <NEW_LINE> subsurface = self.surface.subsurface(region) <NEW_LINE> surface.blit(subsurface, region) <NEW_LINE> <DEDENT> <DEDENT> def get_old_rects(self): <NEW_LINE> <INDENT> dirty_rects = [] <NEW_LINE> for sprite in self.sprites: <NEW_LINE> <INDENT> if sprite.dirty: <NEW_LINE> <INDENT> dirty_rects.append([sprite.rect]) <NEW_LINE> <DEDENT> <DEDENT> return dirty_rects | Mixin to hold logic for a collection of sprites (tiles, units, etc) | 62599040c432627299fa4252 |
class TemplateDirSwitcher(object): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> device_families = importlib.import_module(getattr(settings, 'DEVICE_FAMILIES', 'templateswitcher.device_families')) <NEW_LINE> device_obj = getattr(request, 'device', None) <NEW_LINE> device_cache_key = hash(request.META['HTTP_USER_AGENT']) <NEW_LINE> template_set = cache.get(device_cache_key) <NEW_LINE> full_path = request.get_full_path() <NEW_LINE> media_request = (full_path.startswith(settings.MEDIA_URL) or full_path.startswith(settings.ADMIN_MEDIA_PREFIX) or full_path.startswith('/favicon')) <NEW_LINE> if not template_set: <NEW_LINE> <INDENT> device_switch_libs = getattr(settings, 'DEVICE_SWITCH_LIB', ['WurlfSniffer']) <NEW_LINE> da_api = getattr(settings, 'DEVICE_ATLAS_API_FILE', None) <NEW_LINE> device_cache_timeout = getattr(settings, 'DEVICE_CACHE_TIMEOUT', 72000) <NEW_LINE> if 'ApexVertexSniffer' in device_switch_libs: <NEW_LINE> <INDENT> from mobile.sniffer.apexvertex.sniffer import ApexVertexSniffer <NEW_LINE> <DEDENT> if 'WAPProfileSniffer' in device_switch_libs: <NEW_LINE> <INDENT> from mobile.sniffer.wapprofile.sniffer import WAPProfileSniffer <NEW_LINE> <DEDENT> if 'DeviceAtlasSniffer' in device_switch_libs: <NEW_LINE> <INDENT> if not os.path.exists(da_api): <NEW_LINE> <INDENT> raise Exception('DEVICE_ATLAS_API_FILE must be in your setting and contain a valid path to use Device Atlas.') <NEW_LINE> <DEDENT> from mobile.sniffer.deviceatlas.sniffer import DeviceAtlasSniffer <NEW_LINE> <DEDENT> if 'WurlfSniffer' in device_switch_libs: <NEW_LINE> <INDENT> from mobile.sniffer.wurlf.sniffer import WurlfSniffer <NEW_LINE> <DEDENT> chained_libs = [] <NEW_LINE> for device_lib in device_switch_libs: <NEW_LINE> <INDENT> chained_libs.append(eval(device_lib)()) <NEW_LINE> <DEDENT> sniffer = ChainedSniffer(chained_libs) <NEW_LINE> device_object = sniffer.sniff(request) <NEW_LINE> template_set = device_families.get_device_family(device_object) <NEW_LINE> request.device = device_object <NEW_LINE> cache.set(device_cache_key, template_set, device_cache_timeout) <NEW_LINE> <DEDENT> if not media_request: <NEW_LINE> <INDENT> settings.TEMPLATE_DIRS = ( settings.DEVICE_TEMPLATE_DIRS[template_set], ) | Template Switching Middleware. Switches template dirs by using preset conditions
and device families according to the devices capabilities. Returns the device
object in the request object and resets the TEMPLATE_DIRS attr in the project
settings. | 625990406fece00bbacccc52 |
class dbEngine(object): <NEW_LINE> <INDENT> dbengine = None <NEW_LINE> @staticmethod <NEW_LINE> def get(): <NEW_LINE> <INDENT> if not dbEngine.dbengine: <NEW_LINE> <INDENT> dbEngine.dbengine = create_engine('postgresql://basudebpuragrodb:password@localhost:5432/basudebpuragrodb', echo=True) <NEW_LINE> <DEDENT> return dbEngine.dbengine | singletone class to access db engine | 625990401d351010ab8f4dbf |
class Sinus(Node): <NEW_LINE> <INDENT> def __init__(self, amplitude=1, rate=1, name="sinus"): <NEW_LINE> <INDENT> self._amplitude = amplitude <NEW_LINE> self._rate = rate <NEW_LINE> self._name = name <NEW_LINE> self._start = None <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> timestamp = now() <NEW_LINE> float = time_to_float(timestamp) <NEW_LINE> if self._start is None: <NEW_LINE> <INDENT> self._start = float <NEW_LINE> <DEDENT> values = [ self._amplitude * np.sin(2 * np.pi * self._rate * (float - self._start)) ] <NEW_LINE> self.o.set(values, names=[self._name]) <NEW_LINE> self.o.meta = {"rate": Registry.rate} | Return a sinusoidal signal sampled to registry rate.
This node generates a sinusoidal signal of chosen frequency and amplitude.
Note that at each update, the node generate one row, so its sampling rate
equals the graph parsing rate (given by the Registry).
Attributes:
o (Port): Default output, provides DataFrame.
Example:s
.. literalinclude:: /../examples/sinus.yaml
:language: yaml | 625990403c8af77a43b6888d |
class EdgeNotFound(Exception): <NEW_LINE> <INDENT> pass | Raised in case Edge not found | 625990401d351010ab8f4dc0 |
class TimelineView(BrowserView): <NEW_LINE> <INDENT> implements(ITimelineView) <NEW_LINE> def __init__(self, context, request): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.request = request <NEW_LINE> <DEDENT> @property <NEW_LINE> def portal_catalog(self): <NEW_LINE> <INDENT> return getToolByName(self.context, 'portal_catalog') <NEW_LINE> <DEDENT> @property <NEW_LINE> def portal(self): <NEW_LINE> <INDENT> return getToolByName(self.context, 'portal_url').getPortalObject() <NEW_LINE> <DEDENT> def attrvals(self,items,attr): <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> val = getattr(item,attr, getattr(item.getObject(),attr,None)) <NEW_LINE> if callable(val): <NEW_LINE> <INDENT> val = val() <NEW_LINE> <DEDENT> if val: <NEW_LINE> <INDENT> if type(val) == str: <NEW_LINE> <INDENT> yield val <NEW_LINE> <DEDENT> elif iter(val): <NEW_LINE> <INDENT> for i in val: <NEW_LINE> <INDENT> yield i <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def filterResults(self,**filters): <NEW_LINE> <INDENT> query = self.context.buildQuery() <NEW_LINE> query.update(filters) <NEW_LINE> catalog = getToolByName(self.context,'portal_catalog') <NEW_LINE> return catalog(query) | Timeline browser view | 6259904030c21e258be99aaf |
class Figure(Element): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._filename = "" <NEW_LINE> self._caption = "" <NEW_LINE> <DEDENT> @property <NEW_LINE> def caption(self): <NEW_LINE> <INDENT> return self._caption <NEW_LINE> <DEDENT> @caption.setter <NEW_LINE> def caption(self,val): <NEW_LINE> <INDENT> self._caption = self._lint(val) <NEW_LINE> <DEDENT> @property <NEW_LINE> def formatted_caption(self): <NEW_LINE> <INDENT> return self._formatter.fmt( self._caption, **self.NS.__dict__ ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def filename(self): <NEW_LINE> <INDENT> return self._filename <NEW_LINE> <DEDENT> @filename.setter <NEW_LINE> def filename(self,val): <NEW_LINE> <INDENT> val = os.path.abspath(val) <NEW_LINE> self._filename = self._lint(val) | Represents a figure. | 62599040dc8b845886d54859 |
class LineWatcher(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.start_time = 0.0 <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.start_time = time.time() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self.start_time: <NEW_LINE> <INDENT> diff = time.time() - self.start_time <NEW_LINE> assert diff > 0 <NEW_LINE> print('time: %s' % format_delta(diff)) | Class that implements a basic timer.
Notes
-----
* Register the `start` and `stop` methods with the IPython events API. | 62599040e76e3b2f99fd9cad |
class IncorrectPreviousVersionException(BaseException): <NEW_LINE> <INDENT> pass | The specified previous version did not match the actual previous version. | 625990408e71fb1e983bcd70 |
class EntityResourceGeneratorPagination(EntityResource): <NEW_LINE> <INDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'Page %s of %s with %s items per page. Total: %s' % (self.page, self.pages, self.per_page, self.items) | Base class for a paginator of a EntityResourceGenerator.
A list of EntityResources may have pages, and this class has the correspond
properties of a paginator such as:
page: the page number,
pages: total number of pages,
items: total items,
per_page: number of items per page (default is 50)
urls: a dict containing the following keys and values:
first: api url for the first page
prev: api url for the previous page
next: api url for the next page
last: api url for the last page
>>> from discogsapi import Discogs
>>> from category.categories import Database
>>> from resource.database.artist import Resource
>>> discogs = Discogs("HeyBaldock/1.0 +http://heybaldock.com.br")
>>> resource = Resource(discogs)
>>> resource.name = 'artists'
>>> resource.category = Database
>>> releases = EntityResource(resource, '45/releases')
>>> isinstance(releases.pagination, dict)
True
>>> releases.pagination.has_key('per_page')
True
>>> releases.pagination['per_page']
50
>>> p = EntityResourceGeneratorPagination(resource, data=releases.pagination)
>>> p.page
1
>>> p.pages > 1
True
>>> p.per_page
50
>>> p.items >= (p.pages - 1) * p.per_page
True
>>> isinstance(p.urls, dict)
True
>>> p.urls.has_key('next')
True
>>> p.urls.has_key('last')
True
>>> p.urls['next'].startswith('http')
True
>>> p.urls['last'].startswith('http')
True | 6259904023e79379d538d7a2 |
class MGMSG_MOT_REQ_MFF_OPERPARAMS(Message): <NEW_LINE> <INDENT> id = 0x511 <NEW_LINE> parameters = [('chan_ident', 'B'), (None, 'B')] | See :class:`MGMSG_MOT_SET_MFF_OPERPARAMS`.
:param chan_ident: channel number (0x01, 0x02)
:type chan_ident: int | 625990403eb6a72ae038b90e |
class City(models.Model): <NEW_LINE> <INDENT> city = models.CharField('城市名称', max_length=40, db_index=True) <NEW_LINE> district = models.CharField('市区信息', max_length=40) <NEW_LINE> user_id = models.IntegerField('创建者') <NEW_LINE> status = models.IntegerField('数据状态', default=1) <NEW_LINE> created = models.DateTimeField(default=now) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> objects = BaseManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'ys_city' <NEW_LINE> unique_together = ('city', 'district', 'status') <NEW_LINE> ordering = ['city', 'district'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.city <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_object(cls, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return cls.objects.get(**kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return e | 城市信息 | 62599040d164cc617582221a |
class SessionManager: <NEW_LINE> <INDENT> _SESSION_COOKIE_KEY_FOR_CODENAME = "codename" <NEW_LINE> _SESSION_COOKIE_KEY_FOR_EXPIRATION_DATE = "expires" <NEW_LINE> @classmethod <NEW_LINE> def log_user_in( cls, db_session: sqlalchemy.orm.Session, supplied_passphrase: "DicewarePassphrase" ) -> SourceUser: <NEW_LINE> <INDENT> source_user = authenticate_source_user( db_session=db_session, supplied_passphrase=supplied_passphrase ) <NEW_LINE> session[cls._SESSION_COOKIE_KEY_FOR_CODENAME] = supplied_passphrase <NEW_LINE> session_duration = timedelta(minutes=config.SESSION_EXPIRATION_MINUTES) <NEW_LINE> session[cls._SESSION_COOKIE_KEY_FOR_EXPIRATION_DATE] = datetime.now( timezone.utc) + session_duration <NEW_LINE> return source_user <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def log_user_out(cls) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del session[cls._SESSION_COOKIE_KEY_FOR_CODENAME] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> del session[cls._SESSION_COOKIE_KEY_FOR_EXPIRATION_DATE] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_logged_in_user(cls, db_session: sqlalchemy.orm.Session) -> SourceUser: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_passphrase = session[cls._SESSION_COOKIE_KEY_FOR_CODENAME] <NEW_LINE> date_session_expires = session[cls._SESSION_COOKIE_KEY_FOR_EXPIRATION_DATE] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> cls.log_user_out() <NEW_LINE> raise UserNotLoggedIn() <NEW_LINE> <DEDENT> if datetime.now(timezone.utc) >= date_session_expires: <NEW_LINE> <INDENT> cls.log_user_out() <NEW_LINE> raise UserSessionExpired() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> source_user = authenticate_source_user( db_session=db_session, supplied_passphrase=user_passphrase ) <NEW_LINE> <DEDENT> except InvalidPassphraseError: <NEW_LINE> <INDENT> cls.log_user_out() <NEW_LINE> raise UserHasBeenDeleted() <NEW_LINE> <DEDENT> return source_user <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def is_user_logged_in(cls, db_session: sqlalchemy.orm.Session) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cls.get_logged_in_user(db_session) <NEW_LINE> <DEDENT> except _InvalidUserSession: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Helper to manage the user's session cookie accessible via flask.session. | 6259904126238365f5faddfc |
class GoldbachTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_one(self): <NEW_LINE> <INDENT> self.assertEqual([(2, 2)], goldbach(4)) <NEW_LINE> <DEDENT> def test_two(self): <NEW_LINE> <INDENT> self.assertEqual([(3, 3)], goldbach(6)) <NEW_LINE> <DEDENT> def test_three(self): <NEW_LINE> <INDENT> self.assertEqual([(3, 5)], goldbach(8)) <NEW_LINE> <DEDENT> def test_four(self): <NEW_LINE> <INDENT> self.assertEqual([(3, 7), (5, 5)], goldbach(10)) <NEW_LINE> <DEDENT> def test_five(self): <NEW_LINE> <INDENT> self.assertEqual([(3, 97), (11, 89), (17, 83), (29, 71), (41, 59), (47, 53)], goldbach(100)) | docstring for GoldbachTest | 62599041c432627299fa4253 |
class TestTrieRouter(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super(TestTrieRouter, cls).setUpClass() <NEW_LINE> cls.router = Router(nd256_classroom.pop('root_handler()')) <NEW_LINE> for page in nd256_classroom.keys(): <NEW_LINE> <INDENT> cls.router.add_handler(page, nd256_classroom[page]) <NEW_LINE> <DEDENT> <DEDENT> def test_lookup(cls): <NEW_LINE> <INDENT> print("\n##### Test case 1: lookup of existing handlers #####") <NEW_LINE> lookup_paths = nd256_classroom.values() <NEW_LINE> expected_handler = list(nd256_classroom.keys()) <NEW_LINE> for index, path in enumerate(lookup_paths): <NEW_LINE> <INDENT> cls.run_test(path, expected_handler[index]) <NEW_LINE> <DEDENT> <DEDENT> def test_lookup_root(cls): <NEW_LINE> <INDENT> print("\n##### Test case 2: lookup of root handler #####") <NEW_LINE> lookup_paths = ["/","https://classroom.udacity.com/nanodegrees/nd256/"] <NEW_LINE> expected_handler = ['root_handler()','root_handler()'] <NEW_LINE> for index, path in enumerate(lookup_paths): <NEW_LINE> <INDENT> cls.run_test(path, expected_handler[index]) <NEW_LINE> <DEDENT> <DEDENT> def test_lookup_trailing_slash(cls): <NEW_LINE> <INDENT> print("\n##### Test case 3: lookup of paths with trailing slash #####") <NEW_LINE> lookup_paths = nd256_classroom.values() <NEW_LINE> expected_handler = list(nd256_classroom.keys()) <NEW_LINE> for index, path in enumerate(lookup_paths): <NEW_LINE> <INDENT> cls.run_test(path+'/', expected_handler[index]) <NEW_LINE> <DEDENT> <DEDENT> def test_invalid_lookup(cls): <NEW_LINE> <INDENT> print("\n##### Test case 4: lookup of non-existing handlers #####") <NEW_LINE> lookup_paths = ["https://www.udemy.com/", "https://classroom.udacity.com/nanodegrees/nd256/final_certificate"] <NEW_LINE> expected_handler = ["Not found handler", "Not found handler"] <NEW_LINE> for index, path in enumerate(lookup_paths): <NEW_LINE> <INDENT> cls.run_test(path, expected_handler[index]) <NEW_LINE> <DEDENT> <DEDENT> def run_test(cls, lookup_path, expected_handler): <NEW_LINE> <INDENT> print("\nLookup path:") <NEW_LINE> print("'"+lookup_path+"'") <NEW_LINE> print("Expected handler: {}".format(expected_handler)) <NEW_LINE> actual_handler = cls.router.lookup(lookup_path) <NEW_LINE> print("Returned handler: {}".format(actual_handler)) <NEW_LINE> cls.assertEqual(actual_handler, expected_handler) | docstring for TestTrieRouter | 625990418c3a8732951f77fd |
class AssessmentTakenQueryRecord(abc_assessment_records.AssessmentTakenQueryRecord, osid_records.OsidRecord): <NEW_LINE> <INDENT> pass | A record for an ``AssessmentTakenQuery``.
The methods specified by the record type are available through the
underlying object. | 625990413c8af77a43b6888e |
class DecibelSPL(NonLinearConverter): <NEW_LINE> <INDENT> def __call__(self,meas,inv=False): <NEW_LINE> <INDENT> F0 = 1e-12 <NEW_LINE> if not inv: return 10**(-meas)*F0 <NEW_LINE> else: return log10(meas/F0) | Convert a Decibel to intensity W/m2 and back.
This is only valid for Decibels as a sound Pressure level | 625990416e29344779b018f6 |
class BaseNetworkTest(tempest.test.BaseTestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> os = clients.Manager() <NEW_LINE> cls.network_cfg = os.config.network <NEW_LINE> if not cls.network_cfg.quantum_available: <NEW_LINE> <INDENT> raise cls.skipException("Quantum support is required") <NEW_LINE> <DEDENT> cls.client = os.network_client <NEW_LINE> cls.networks = [] <NEW_LINE> cls.subnets = [] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> for subnet in cls.subnets: <NEW_LINE> <INDENT> cls.client.delete_subnet(subnet['id']) <NEW_LINE> <DEDENT> for network in cls.networks: <NEW_LINE> <INDENT> cls.client.delete_network(network['id']) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def create_network(cls, network_name=None): <NEW_LINE> <INDENT> network_name = network_name or rand_name('test-network-') <NEW_LINE> resp, body = cls.client.create_network(network_name) <NEW_LINE> network = body['network'] <NEW_LINE> cls.networks.append(network) <NEW_LINE> return network <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_subnet(cls, network): <NEW_LINE> <INDENT> cidr = netaddr.IPNetwork(cls.network_cfg.tenant_network_cidr) <NEW_LINE> mask_bits = cls.network_cfg.tenant_network_mask_bits <NEW_LINE> for subnet_cidr in cidr.subnet(mask_bits): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resp, body = cls.client.create_subnet(network['id'], str(subnet_cidr)) <NEW_LINE> break <NEW_LINE> <DEDENT> except exceptions.BadRequest as e: <NEW_LINE> <INDENT> is_overlapping_cidr = 'overlaps with another subnet' in str(e) <NEW_LINE> if not is_overlapping_cidr: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> subnet = body['subnet'] <NEW_LINE> cls.subnets.append(subnet) <NEW_LINE> return subnet | Base class for the Quantum tests that use the Tempest Quantum REST client
Per the Quantum API Guide, API v1.x was removed from the source code tree
(docs.openstack.org/api/openstack-network/2.0/content/Overview-d1e71.html)
Therefore, v2.x of the Quantum API is assumed. It is also assumed that the
following options are defined in the [network] section of etc/tempest.conf:
tenant_network_cidr with a block of cidr's from which smaller blocks
can be allocated for tenant networks
tenant_network_mask_bits with the mask bits to be used to partition the
block defined by tenant-network_cidr | 62599041507cdc57c63a6040 |
class WorkflowOperation(HasStrictTraits): <NEW_LINE> <INDENT> do_estimate = Event <NEW_LINE> changed = Event(apply = True, estimate = True) <NEW_LINE> def should_apply(self, changed, payload): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def should_clear_estimate(self, changed, payload): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def clear_estimate(self): <NEW_LINE> <INDENT> raise NotImplementedError("clear_estimate was called but it's not implemented!") <NEW_LINE> <DEDENT> def get_notebook_code(self, idx): <NEW_LINE> <INDENT> raise NotImplementedError("GUI plugins must override get_notebook_code()") | A default implementation of `IWorkflowOperation` | 625990418e05c05ec3f6f7ad |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.