code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Disk(nagiosplugin.Resource): <NEW_LINE> <INDENT> def __init__(self, params): <NEW_LINE> <INDENT> self.params = params <NEW_LINE> self.mountpoint = params.mountpoint <NEW_LINE> self.disksize = params.disksize <NEW_LINE> <DEDENT> def probe(self): <NEW_LINE> <INDENT> usage = psutil.disk_usage(self.mountpoint) <NEW_LINE> _log.debug("probe: %r", usage) <NEW_LINE> if not self.disksize: <NEW_LINE> <INDENT> self.disksize = usage.total / GB <NEW_LINE> <DEDENT> percent = round(100.0 * float(usage.used) / GB / self.disksize, 1) <NEW_LINE> self.params.register_context(self.disksize) <NEW_LINE> return nagiosplugin.Metric( self.mountpoint, percent, "%", min=0.0, max=100.0 )
Does the actual work of querying space usage.
62598fba66656f66f7d5a576
class FakeTask(Requester): <NEW_LINE> <INDENT> NAME = 'task' <NEW_LINE> def __init__(self, **fake_script_options): <NEW_LINE> <INDENT> self._queue = None <NEW_LINE> self._ready = threading.Event() <NEW_LINE> self.fake_script_options = fake_script_options <NEW_LINE> self.loop = None <NEW_LINE> <DEDENT> async def end_request(self): <NEW_LINE> <INDENT> async def _worker(layer, index): <NEW_LINE> <INDENT> with b.apply(index), layer: <NEW_LINE> <INDENT> async with sema: <NEW_LINE> <INDENT> return await layer.run() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._queue = asyncio.Queue() <NEW_LINE> self._ready.set() <NEW_LINE> self.loop = asyncio.get_running_loop() <NEW_LINE> acnt = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> data, options = await self._queue.get() <NEW_LINE> with a.apply(acnt): <NEW_LINE> <INDENT> rule = options.get('rule', 1) <NEW_LINE> options['rule'] = rule <NEW_LINE> script = ScriptLayer(fake_script(data, **options)) <NEW_LINE> await script.execute_script() <NEW_LINE> tasks = [ asyncio.create_task(_worker(s, i)) for i, s in enumerate([script]) ] <NEW_LINE> max_workers = 3 <NEW_LINE> sema = asyncio.Semaphore(max_workers) <NEW_LINE> ctx.add_stopper(script.stop) <NEW_LINE> await asyncio.wait(tasks) <NEW_LINE> self._queue.task_done() <NEW_LINE> <DEDENT> acnt += 1 <NEW_LINE> <DEDENT> <DEDENT> def run(self, o, **options): <NEW_LINE> <INDENT> self._ready.wait(timeout=10) <NEW_LINE> asyncio.run_coroutine_threadsafe( self._queue.put((o, options)), loop=self.loop )
fake task for debugging.
62598fba442bda511e95c5e0
class RegisterIFrameCheckJS(UpgradeStep): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> self.install_upgrade_profile()
Register i frame check js.
62598fba10dbd63aa1c70d3e
class Eth_100Gbase_Cr4Identity(Ethernet_Pmd_TypeIdentity): <NEW_LINE> <INDENT> _prefix = 'oc-opt-types' <NEW_LINE> _revision = '2016-06-17' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> Ethernet_Pmd_TypeIdentity.__init__(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.openconfig._meta import _openconfig_transport_types as meta <NEW_LINE> return meta._meta_table['Eth_100Gbase_Cr4Identity']['meta_info']
Ethernet compliance code\: 100GBASE\_CR4
62598fba3346ee7daa33770a
class Topology(object): <NEW_LINE> <INDENT> def __init__(self, layers, extra_layers=None): <NEW_LINE> <INDENT> def __check__(layers): <NEW_LINE> <INDENT> if not isinstance(layers, collections.Sequence): <NEW_LINE> <INDENT> __check_layer_type__(layers) <NEW_LINE> layers = [layers] <NEW_LINE> <DEDENT> for layer in layers: <NEW_LINE> <INDENT> __check_layer_type__(layer) <NEW_LINE> <DEDENT> return layers <NEW_LINE> <DEDENT> layers = __check__(layers) <NEW_LINE> self.layers = layers <NEW_LINE> if extra_layers is not None: <NEW_LINE> <INDENT> extra_layers = __check__(extra_layers) <NEW_LINE> <DEDENT> self.__model_config__ = v2_layer.parse_network( layers, extra_layers=extra_layers) <NEW_LINE> if extra_layers is not None: <NEW_LINE> <INDENT> self.layers.extend(extra_layers) <NEW_LINE> <DEDENT> assert isinstance(self.__model_config__, ModelConfig) <NEW_LINE> <DEDENT> def use_sparse_updater(self): <NEW_LINE> <INDENT> use_sparse = False <NEW_LINE> for parameter in self.__model_config__.parameters: <NEW_LINE> <INDENT> if parameter.sparse_update or parameter.sparse_remote_update: <NEW_LINE> <INDENT> use_sparse = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return use_sparse <NEW_LINE> <DEDENT> def proto(self): <NEW_LINE> <INDENT> return self.__model_config__ <NEW_LINE> <DEDENT> def get_layer(self, name): <NEW_LINE> <INDENT> return v2_layer.get_layer(name) <NEW_LINE> <DEDENT> def data_layers(self): <NEW_LINE> <INDENT> data_layers = {} <NEW_LINE> for layer in self.proto().layers: <NEW_LINE> <INDENT> l = v2_layer.get_layer(layer.name) <NEW_LINE> if l and l.layer_type == conf_helps.LayerType.DATA: <NEW_LINE> <INDENT> data_layers[layer.name] = l <NEW_LINE> <DEDENT> <DEDENT> return data_layers <NEW_LINE> <DEDENT> def data_type(self): <NEW_LINE> <INDENT> data_layers = self.data_layers() <NEW_LINE> return [(nm, data_layers[nm].data_type) for nm in self.proto().input_layer_names] <NEW_LINE> <DEDENT> def get_layer_proto(self, name): <NEW_LINE> <INDENT> for layer in self.__model_config__.layers: <NEW_LINE> <INDENT> if layer.name == name: <NEW_LINE> <INDENT> return layer <NEW_LINE> <DEDENT> <DEDENT> return None
Topology is used to store the information about all layers and network configs.
62598fbaec188e330fdf8a16
class Meta(object): <NEW_LINE> <INDENT> model = CourseTeamMembership <NEW_LINE> fields = ("user", "date_joined", "last_activity_at") <NEW_LINE> read_only_fields = ("date_joined", "last_activity_at")
Defines meta information for the ModelSerializer.
62598fba0fa83653e46f5068
class BrkBase(object): <NEW_LINE> <INDENT> model = models.KadastraalObject <NEW_LINE> index = 'DS_BRK_INDEX' <NEW_LINE> db = 'brk' <NEW_LINE> q_func = meta_q <NEW_LINE> keywords = [ 'eigenaar_type', 'eigenaar_categorie_id', 'eigenaar_cat', 'buurt_naam', 'buurt_code', 'buurtcombinatie_naam', 'buurtcombinatie_code', 'ggw_naam', 'ggw_code', 'stadsdeel_naam', 'stadsdeel_code', 'openbare_ruimte_naam', 'postcode' ] <NEW_LINE> geo_fields = [ {'query_param': 'shape', 'es_doc_field': 'geometrie', 'es_query_type': 'geo_shape'} ] <NEW_LINE> keyword_mapping = { } <NEW_LINE> raw_fields = []
Base class mixin for data settings
62598fba2c8b7c6e89bd394a
class GeoIP2WebServiceNotConfigured(Exception): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> message = "You tried a query to GeoIP2 webservice, but no valid " "credentials were found in configuration." <NEW_LINE> Exception.__init__(self, message)
GeoIP2 WebService access is still not configured.
62598fbaa8370b77170f0564
class Headers(DataContainer): <NEW_LINE> <INDENT> def __init__(self, init_val=(), encoding=UTF8): <NEW_LINE> <INDENT> cleaned_vals = self.clean_values(init_val) <NEW_LINE> super(Headers, self).__init__(cleaned_vals, encoding) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, headers_str): <NEW_LINE> <INDENT> res = [] <NEW_LINE> splitted_str = headers_str.split('\r\n') <NEW_LINE> for one_header_line in splitted_str: <NEW_LINE> <INDENT> if not one_header_line: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> name, value = one_header_line.split(':', 1) <NEW_LINE> value = value[1:] <NEW_LINE> res.append((name, value)) <NEW_LINE> <DEDENT> return cls(res) <NEW_LINE> <DEDENT> def clean_values(self, init_val): <NEW_LINE> <INDENT> if isinstance(init_val, DataContainer) or isinstance(init_val, dict): <NEW_LINE> <INDENT> return init_val <NEW_LINE> <DEDENT> cleaned_vals = [] <NEW_LINE> for key, value in init_val: <NEW_LINE> <INDENT> if isinstance(value, basestring): <NEW_LINE> <INDENT> value = smart_unicode(value) <NEW_LINE> <DEDENT> cleaned_vals.append( (smart_unicode(key), value) ) <NEW_LINE> <DEDENT> return cleaned_vals <NEW_LINE> <DEDENT> def iget(self, header_name, default=None): <NEW_LINE> <INDENT> for stored_header_name in self: <NEW_LINE> <INDENT> if header_name.lower() == stored_header_name.lower(): <NEW_LINE> <INDENT> return self[stored_header_name], stored_header_name <NEW_LINE> <DEDENT> <DEDENT> return default, None <NEW_LINE> <DEDENT> def clone_with_list_values(self): <NEW_LINE> <INDENT> clone = Headers() <NEW_LINE> for key, value in self.iteritems(): <NEW_LINE> <INDENT> clone[key] = [value, ] <NEW_LINE> <DEDENT> return clone <NEW_LINE> <DEDENT> def __setitem__(self, k, v): <NEW_LINE> <INDENT> if isinstance(k, basestring): <NEW_LINE> <INDENT> if not isinstance(k, unicode): <NEW_LINE> <INDENT> k = k.encode(self.encoding, 'replace') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Header name must be a string.') <NEW_LINE> <DEDENT> if isinstance(v, basestring): <NEW_LINE> <INDENT> if not isinstance(k, unicode): <NEW_LINE> <INDENT> v = v.encode(self.encoding, 'replace') <NEW_LINE> <DEDENT> <DEDENT> super(Headers, self).__setitem__(k, v) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> header_str_unicode = self._to_str_with_separators(u': ', u'\r\n') <NEW_LINE> header_str_unicode += u'\r\n' <NEW_LINE> return header_str_unicode.encode('utf-8') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self._to_str_with_separators(u': ', u'\r\n') + u'\r\n'
This class represents the set of HTTP request headers. :author: Javier Andalia (jandalia AT gmail DOT com)
62598fbaa05bb46b3848a9f0
class FulfilledPrerequisite(models.Model): <NEW_LINE> <INDENT> prerequisite = models.ForeignKey( 'prerequisites.Prerequisite', on_delete=models.CASCADE, ) <NEW_LINE> helper = models.ForeignKey( 'registration.Helper', on_delete=models.CASCADE, ) <NEW_LINE> has_prerequisite = models.BooleanField( default=False, verbose_name=_("Helper fulfils this prerequisite"), ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{} - {}".format(self.prerequisite, self.helper)
Link between helpers and prerequisites Columns: :has_prerequisite: The helper fulfils this prerequisite
62598fba4f88993c371f05cf
class SoftDynamicTimeWarping(torch.nn.Module): <NEW_LINE> <INDENT> def __init__( self, penalty: float = 1.0, gamma: float = 0.01, normalize: bool = False, bandwidth: int = None, dist_func: str = "manhattan", ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.penalty = penalty <NEW_LINE> self.normalize = normalize <NEW_LINE> self.gamma = gamma <NEW_LINE> self.bandwidth = 0 if bandwidth is None else float(bandwidth) <NEW_LINE> self.use_cuda = torch.cuda.is_available() <NEW_LINE> self.dist_func = eval(dist_func) <NEW_LINE> <DEDENT> def _get_func_dtw(self, x, y): <NEW_LINE> <INDENT> bx, lx, dx = x.shape <NEW_LINE> by, ly, dy = y.shape <NEW_LINE> assert bx == by <NEW_LINE> assert dx == dy <NEW_LINE> use_cuda = self.use_cuda <NEW_LINE> if use_cuda and (lx > 1024 or ly > 1024): <NEW_LINE> <INDENT> print("SoftDTW: Cannot use CUDA because the sequence length > 1024 (the maximum block size supported by CUDA)") <NEW_LINE> use_cuda = False <NEW_LINE> <DEDENT> return _SoftDTWCUDA.apply if use_cuda else _SoftDTW.apply <NEW_LINE> <DEDENT> def forward(self, X, Y): <NEW_LINE> <INDENT> func_dtw = self._get_func_dtw(X, Y) <NEW_LINE> X = X.permute(0, 2, 1) <NEW_LINE> Y = Y.permute(0, 2, 1) <NEW_LINE> if self.normalize: <NEW_LINE> <INDENT> x = torch.cat([X, X, Y]) <NEW_LINE> y = torch.cat([Y, X, Y]) <NEW_LINE> D = self.dist_func(x, y) <NEW_LINE> out = func_dtw(D, self.penalty, self.gamma, self.bandwidth) <NEW_LINE> out_xy, out_xx, out_yy = torch.split(out, X.shape[0]) <NEW_LINE> return out_xy - 1 / 2 * (out_xx + out_yy) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> D_xy = self.dist_func(X, Y) <NEW_LINE> return func_dtw(D_xy, self.penalty, self.gamma, self.bandwidth).mean()
High-level wrapper for soft dynamic time warmping implementation that optionally supports CUDA. Args: use_cuda: whether to use CUDA implementation gamma: soft minimum temperature parameter normalize: whether to perform normalization, as discussed in https://github.com/mblondel/soft-dtw/issues/10#issuecomment-383564790 bandwidth: Sakoe-Chiba bandwidth for pruning, pass None to disable dist_func: optional point-wise distance function to use, defaults to smooth Manhattan distance
62598fba60cbc95b063644c4
class ValidateComponents(AbsValidator): <NEW_LINE> <INDENT> def __init__(self, path: str, component_regex: str, *extensions: str) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.path = path <NEW_LINE> self.component_regex = component_regex <NEW_LINE> self.extensions = extensions <NEW_LINE> self._component_mask = re.compile(component_regex) <NEW_LINE> <DEDENT> def validate(self) -> None: <NEW_LINE> <INDENT> components = set() <NEW_LINE> found_files = False <NEW_LINE> logger = logging.getLogger(__name__) <NEW_LINE> report_builder = result.SummaryDirector(source=self.path) <NEW_LINE> for component_file in filter(self._component_filter, os.scandir(self.path)): <NEW_LINE> <INDENT> found_files = True <NEW_LINE> components.add(os.path.splitext(component_file.name)[0]) <NEW_LINE> <DEDENT> if not found_files: <NEW_LINE> <INDENT> raise FileNotFoundError( "No files found with regex {}".format(self.component_regex) ) <NEW_LINE> <DEDENT> for component in sorted(components): <NEW_LINE> <INDENT> for extension in self.extensions: <NEW_LINE> <INDENT> component_file_name = f"{component}{extension}" <NEW_LINE> component_file_path = os.path.join(self.path, component_file_name) <NEW_LINE> if not os.path.exists(component_file_path): <NEW_LINE> <INDENT> report_builder.add_error( "Missing {}".format(component_file_name) ) <NEW_LINE> logger.info("Missing %s", component_file_name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.results = list(report_builder.construct()) <NEW_LINE> <DEDENT> def _component_filter(self, entry: os.DirEntry) -> bool: <NEW_LINE> <INDENT> if not entry.is_file(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> base, _ = os.path.splitext(entry.name) <NEW_LINE> return bool(self._component_mask.fullmatch(base))
Validator for components.
62598fba377c676e912f6e33
class SimpleContent(BaseObject): <NEW_LINE> <INDENT> def __init__(self, ID=None, children=None, attributes=None): <NEW_LINE> <INDENT> self.hasAnnotation = False <NEW_LINE> self.hasContent = False <NEW_LINE> super(SimpleContent, self).__init__(ID, children, attributes) <NEW_LINE> <DEDENT> def addChild(self, newChildren): <NEW_LINE> <INDENT> if isinstance(newChildren, list): <NEW_LINE> <INDENT> for child in newChildren: <NEW_LINE> <INDENT> self.addChild(child) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(newChildren, Annotation): <NEW_LINE> <INDENT> if self.hasAnnotation: <NEW_LINE> <INDENT> addAnnotationError('SimpleContent') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.hasAnnotation = True, <NEW_LINE> self.children.append(newChildren) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(newChildren, (Restriction, Extension)): <NEW_LINE> <INDENT> if self.hasContent: <NEW_LINE> <INDENT> fewi.addFEWI( severity = fewi.Severity.ERROR, cause = 'SCHEMA_VALIDATION_ERROR', message = 'SimpleContent element must contain exactly one of either Restriction or Extension.' ) <NEW_LINE> self.isValid = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.hasContent = True <NEW_LINE> self.children.append(newChildren) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> fewi.addFEWI( severity = fewi.Severity.ERROR, cause = 'SCHEMA_VALIDATION_ERROR', message = 'SimpleContent can only contain the following elements: Annotation, Restriction, Extension. Found: {}'.format(type(newChildren)) ) <NEW_LINE> self.isValid = False
Contains extensions or restrictions on a text-only ComplexType or on a SimpleType as content and contains no elements.
62598fba63b5f9789fe852f4
class AttributeProxy(CommandProxy): <NEW_LINE> <INDENT> @property <NEW_LINE> def base(self) -> BaseProxy: <NEW_LINE> <INDENT> return self._proxy(BaseProxy, 'base') <NEW_LINE> <DEDENT> @property <NEW_LINE> def modifier(self) -> ModifierProxy: <NEW_LINE> <INDENT> return self._proxy(ModifierProxy, 'modifier') <NEW_LINE> <DEDENT> def get(self, scale: Optional[float] = None) -> str: <NEW_LINE> <INDENT> return self._run('get', scale)
Proxy for attribute actions.
62598fba99fddb7c1ca62eae
class NEditable(QObject): <NEW_LINE> <INDENT> def __init__(self, filepath=None, project=None): <NEW_LINE> <INDENT> super(NEditable, self).__init__() <NEW_LINE> self.__editor = None <NEW_LINE> self._nfile = nfile.NFile(filepath) <NEW_LINE> self.text_modified = False <NEW_LINE> self._has_checkers = False <NEW_LINE> self.project = project <NEW_LINE> self.registered_checkers = [] <NEW_LINE> self._checkers_executed = 0 <NEW_LINE> <DEDENT> def set_editor(self, editor): <NEW_LINE> <INDENT> self.__editor = editor <NEW_LINE> content = '' <NEW_LINE> if not self._nfile.is_new_file: <NEW_LINE> <INDENT> content = self._nfile.read() <NEW_LINE> self.__editor.setPlainText(content) <NEW_LINE> encoding = file_manager.get_file_encoding(content) <NEW_LINE> self.__editor.encoding = encoding <NEW_LINE> <DEDENT> if not content: <NEW_LINE> <INDENT> helpers.insert_coding_line(self.__editor) <NEW_LINE> <DEDENT> self.include_checkers() <NEW_LINE> <DEDENT> def save_content(self): <NEW_LINE> <INDENT> content = self.__editor.get_text() <NEW_LINE> self._nfile.save(content) <NEW_LINE> <DEDENT> def update_project(self, project): <NEW_LINE> <INDENT> self.project = project <NEW_LINE> <DEDENT> @property <NEW_LINE> def ID(self): <NEW_LINE> <INDENT> return self._nfile <NEW_LINE> <DEDENT> @property <NEW_LINE> def display_name(self): <NEW_LINE> <INDENT> return self._nfile.display_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def new_document(self): <NEW_LINE> <INDENT> return self._nfile.is_new_file <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_checkers(self): <NEW_LINE> <INDENT> return self._has_checkers <NEW_LINE> <DEDENT> def include_checkers(self, lang='python'): <NEW_LINE> <INDENT> self.registered_checkers = sorted(checkers.get_checkers_for(lang), key=lambda x: x[2]) <NEW_LINE> self._has_checkers = len(self.registered_checkers) > 0 <NEW_LINE> for i, values in enumerate(self.registered_checkers): <NEW_LINE> <INDENT> Checker, color, priority = values <NEW_LINE> check = Checker(self.__editor) <NEW_LINE> self.registered_checkers[i] = (check, color, priority) <NEW_LINE> self.connect(check, SIGNAL("finished()"), self.show_checkers_notifications) <NEW_LINE> <DEDENT> <DEDENT> def update_checkers_metadata(self, blockNumber, diference): <NEW_LINE> <INDENT> for i, values in enumerate(self.registered_checkers): <NEW_LINE> <INDENT> checker, color, priority = values <NEW_LINE> if checker.checks: <NEW_LINE> <INDENT> checker.checks = helpers.add_line_increment_for_dict( checker.checks, blockNumber, diference) <NEW_LINE> <DEDENT> <DEDENT> self.emit(SIGNAL("checkersUpdated()")) <NEW_LINE> <DEDENT> def run_checkers(self, content, path=None, encoding=None): <NEW_LINE> <INDENT> for items in self.registered_checkers: <NEW_LINE> <INDENT> checker = items[0] <NEW_LINE> checker.run_checks() <NEW_LINE> <DEDENT> <DEDENT> def show_checkers_notifications(self): <NEW_LINE> <INDENT> if self._checkers_executed == len(self.registered_checkers): <NEW_LINE> <INDENT> self._checkers_executed = 0 <NEW_LINE> self.emit(SIGNAL("checkersUpdated()")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._checkers_executed += 1
SIGNALS: @checkersUpdated()
62598fba4a966d76dd5ef058
class ItsmReceiver(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name': {'required': True}, 'workspace_id': {'required': True}, 'connection_id': {'required': True}, 'ticket_configuration': {'required': True}, 'region': {'required': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'workspace_id': {'key': 'workspaceId', 'type': 'str'}, 'connection_id': {'key': 'connectionId', 'type': 'str'}, 'ticket_configuration': {'key': 'ticketConfiguration', 'type': 'str'}, 'region': {'key': 'region', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, name: str, workspace_id: str, connection_id: str, ticket_configuration: str, region: str, **kwargs ): <NEW_LINE> <INDENT> super(ItsmReceiver, self).__init__(**kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.workspace_id = workspace_id <NEW_LINE> self.connection_id = connection_id <NEW_LINE> self.ticket_configuration = ticket_configuration <NEW_LINE> self.region = region
An Itsm receiver. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the Itsm receiver. Names must be unique across all receivers within an action group. :type name: str :param workspace_id: Required. OMS LA instance identifier. :type workspace_id: str :param connection_id: Required. Unique identification of ITSM connection among multiple defined in above workspace. :type connection_id: str :param ticket_configuration: Required. JSON blob for the configurations of the ITSM action. CreateMultipleWorkItems option will be part of this blob as well. :type ticket_configuration: str :param region: Required. Region in which workspace resides. Supported values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. :type region: str
62598fba23849d37ff851239
class SetIamPolicyRequest(_messages.Message): <NEW_LINE> <INDENT> policy = _messages.MessageField('Policy', 1) <NEW_LINE> updateMask = _messages.StringField(2)
Request message for `SetIamPolicy` method. Fields: policy: REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. updateMask: OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be modified. If no mask is provided, a default mask is used: paths: "bindings, etag" This field is only used by Cloud IAM.
62598fbacc40096d6161a29c
class TestAll(unittest.TestCase): <NEW_LINE> <INDENT> def test01_size(self): <NEW_LINE> <INDENT> gen = PixelGen() <NEW_LINE> self.assertEqual(len(gen.size), 2) <NEW_LINE> self.assertEqual(int(gen.size[0]), gen.size[0]) <NEW_LINE> self.assertEqual(int(gen.size[1]), gen.size[1]) <NEW_LINE> <DEDENT> def test02_background_color(self): <NEW_LINE> <INDENT> gen = PixelGen() <NEW_LINE> self.assertEqual(len(gen.background_color), 3) <NEW_LINE> <DEDENT> def test03_pixel(self): <NEW_LINE> <INDENT> gen = PixelGen() <NEW_LINE> self.assertEqual(gen.pixel(0, 0), (0, 0, 0)) <NEW_LINE> self.assertEqual(gen.pixel(0, 0, 2, 222), (222, 0, 0)) <NEW_LINE> self.assertEqual(gen.pixel(1, 0, 2, 222), None) <NEW_LINE> self.assertEqual(gen.pixel(3, 3, 9, 0), (25, 0, 0)) <NEW_LINE> self.assertEqual(gen.pixel(0, 0, 9, 55), (55, 0, 0)) <NEW_LINE> self.assertEqual(gen.pixel(3, 0, 9, 55), None)
Tests.
62598fba099cdd3c636754a5
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.image = pygame.image.load('images/pig.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.location = random.uniform(self.rect.width, ai_settings.screen_width - self.rect.width) <NEW_LINE> self.rect.x = self.location <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def check_y(self): <NEW_LINE> <INDENT> if self.y > 150: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def update(self, ai_settings): <NEW_LINE> <INDENT> self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.alien_direction) <NEW_LINE> self.rect.x = self.x <NEW_LINE> self.y += ai_settings.alien_drop_speed <NEW_LINE> self.rect.y = self.y <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect)
表示单个外星人的类
62598fba851cf427c66b843c
class InvPOSResourcePurpose(models.Model): <NEW_LINE> <INDENT> id = models.IntegerField(unique=True, primary_key=True) <NEW_LINE> purpose = models.CharField(max_length=100, blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'eve_db' <NEW_LINE> ordering = ['id'] <NEW_LINE> verbose_name = 'POS Resource Purpose' <NEW_LINE> verbose_name_plural = 'POS Resource Purposes' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.purpose <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__unicode__()
Types of tasks for which POS need resources, i.e. Online, Reinforced. CCP Table: invControlTowerResourcePurposes CCP Primary key: "purpose" tinyint(4)
62598fbabe7bc26dc9251f1f
class SIDLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, eps=1e-3): <NEW_LINE> <INDENT> super(SIDLoss, self).__init__() <NEW_LINE> self.eps = eps <NEW_LINE> <DEDENT> def forward(self, p, q): <NEW_LINE> <INDENT> N, C, H, W = p.shape <NEW_LINE> kl_1 = p * torch.log10((p+self.eps) / (q+self.eps)) <NEW_LINE> kl_2 = q * torch.log10((q+self.eps) / (p+self.eps)) <NEW_LINE> sid = kl_1.sum(dim=2).sum(dim=2) <NEW_LINE> sid += kl_2.sum(dim=2).sum(dim=2) <NEW_LINE> sid = torch.abs(sid) <NEW_LINE> sid = torch.sum(sid) / (N * H * W * C) <NEW_LINE> return sid
Spectral Information Divergency
62598fba66673b3332c30557
class Configuration: <NEW_LINE> <INDENT> initialized = False <NEW_LINE> project_name = "" <NEW_LINE> project_location = "" <NEW_LINE> component_type = "" <NEW_LINE> template_source = "" <NEW_LINE> platform_type = 0 <NEW_LINE> platform_version = "" <NEW_LINE> modules = [] <NEW_LINE> qt_libs = [] <NEW_LINE> libs = [] <NEW_LINE> interfaces = {} <NEW_LINE> def toJson(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> output['project_name'] = self.project_name <NEW_LINE> output['project_location'] = self.project_location <NEW_LINE> output['template_source'] = self.template_source <NEW_LINE> output['component_type'] = self.component_type <NEW_LINE> output['platform_type'] = self.platform_type <NEW_LINE> output['platform_version'] = self.platform_version <NEW_LINE> output['qt_libs'] = self.qt_libs <NEW_LINE> output['modules'] = self.modules <NEW_LINE> output['libs'] = self.libs <NEW_LINE> output['interfaces'] = self.interfaces <NEW_LINE> return json.dumps(output) <NEW_LINE> <DEDENT> def fromJson(self,content): <NEW_LINE> <INDENT> inputs = json.loads(content) <NEW_LINE> self.project_name = inputs['project_name'] <NEW_LINE> self.project_location = inputs['project_location'] <NEW_LINE> self.template_source = inputs['template_source'] <NEW_LINE> self.component_type = inputs['component_type'] <NEW_LINE> self.platform_type = inputs['platform_type'] <NEW_LINE> self.platform_version = inputs['platform_version'] <NEW_LINE> self.qt_libs = inputs['qt_libs'] <NEW_LINE> self.modules = inputs['modules'] <NEW_LINE> self.libs = inputs['libs'] <NEW_LINE> self.interfaces = inputs['interfaces'] <NEW_LINE> self.initialized = True
用来存储每个页面生成的配置信息
62598fba56b00c62f0fb2a41
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_FEEDBACK_SUBMISSION': True}) <NEW_LINE> class HelpModalTests(ModuleStoreTestCase): <NEW_LINE> <INDENT> shard = 5 <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(HelpModalTests, self).setUp() <NEW_LINE> self.course = CourseFactory.create() <NEW_LINE> <DEDENT> def test_simple_test(self): <NEW_LINE> <INDENT> url = reverse(course_home_url_name(self.course.id), args=[text_type(self.course.id)]) <NEW_LINE> resp = self.client.get(url) <NEW_LINE> self.assertEqual(resp.status_code, 200)
Tests for the help modal
62598fba10dbd63aa1c70d40
class DeMorgan: <NEW_LINE> <INDENT> def filter(self, node): <NEW_LINE> <INDENT> return is_not(node) and has_name(node[1]) <NEW_LINE> <DEDENT> def mutations(self, node): <NEW_LINE> <INDENT> if get_name(node[1]) == 'and': <NEW_LINE> <INDENT> res = [['not', t] for t in node[1][1:]] <NEW_LINE> return [['or', *res]] <NEW_LINE> <DEDENT> if get_name(node[1]) == 'or': <NEW_LINE> <INDENT> res = [['not', t] for t in node[1][1:]] <NEW_LINE> return [['and', *res]] <NEW_LINE> <DEDENT> return [] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'push negation inside'
Uses de Morgans rules to push negations inside.
62598fba0fa83653e46f506a
class SeracDevtools(BundlePackage): <NEW_LINE> <INDENT> version('fakeversion') <NEW_LINE> depends_on('cmake') <NEW_LINE> depends_on('cppcheck') <NEW_LINE> depends_on('doxygen') <NEW_LINE> depends_on("llvm+clang@10.0.0") <NEW_LINE> depends_on('python') <NEW_LINE> depends_on('py-ats') <NEW_LINE> depends_on('py-sphinx')
This is a set of tools necessary for the developers of Serac
62598fba71ff763f4b5e7900
class TargetedClickthroughsByCodename(Base): <NEW_LINE> <INDENT> __tablename__ = "traffic_clicktarget" <NEW_LINE> codename = Column("fullname", String(), nullable=False, primary_key=True) <NEW_LINE> subreddit = Column(String(), nullable=False, primary_key=True) <NEW_LINE> date = Column(DateTime(), nullable=False, primary_key=True) <NEW_LINE> interval = Column(String(), nullable=False, primary_key=True) <NEW_LINE> unique_count = Column("unique", Integer()) <NEW_LINE> pageview_count = Column("total", Integer()) <NEW_LINE> @classmethod <NEW_LINE> @memoize_traffic(time=3600) <NEW_LINE> def total_by_codename(cls, codenames): <NEW_LINE> <INDENT> return total_by_codename(cls, codenames)
Clickthroughs for ads, correlated by ad campaign.
62598fba091ae35668704da9
class BaseHandle(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def input_text(element, text): <NEW_LINE> <INDENT> element.clear() <NEW_LINE> element.send_keys(text) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def click_func(element): <NEW_LINE> <INDENT> element.click()
操作层基类
62598fba60cbc95b063644c6
class startswithExpression(textcompareExpression): <NEW_LINE> <INDENT> def __init__(self, field, text, caseless): <NEW_LINE> <INDENT> super(startswithExpression, self).__init__(field, text, caseless) <NEW_LINE> <DEDENT> def operator(self): <NEW_LINE> <INDENT> return "starts with"
Text STARTSWITH (sub-string match) expression.
62598fba76e4537e8c3ef72e
class WeaponDB(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.wepdb = {'None' : "Error: No Weapon stats to get selected.", 'Sword' : ("Sword", 3, 5, 1.5, 2.0), 'Sword1' : ("Sword+1", 4, 6, 1.5, 2.0), 'Sword2' : ("Sword+2", 5, 7, 1.5, 2.0), 'Sword3' : ("Sword+3", 6, 8, 1.5, 2.0), } <NEW_LINE> <DEDENT> def getDBValues(self, key='None'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.wepdb[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return self.wepdb['None'] <NEW_LINE> <DEDENT> <DEDENT> def getItemList(self): <NEW_LINE> <INDENT> for key in self.wepdb: <NEW_LINE> <INDENT> print(self.wepdb[key])
Here be thine weapons of thy holy might
62598fba91f36d47f2230f6e
class CareerCommitment(Inventory): <NEW_LINE> <INDENT> name = 'Career Commitment' <NEW_LINE> template = 'career_commitment.html' <NEW_LINE> question_text = { 1: 'My major/career field is an important part of who I am.', 2: 'My major/career field has a great deal of personal meaning to me.', 3: 'I do not feel "emotionally attached" to my major/career field.', 4: 'I strongly identify with my chosen major/career field.', 5: 'I do not have a strategy for achieving my goals in my major/career field.', 6: 'I have created a plan for my development in my major/career field.', 7: 'I do not identify specific goals for my development in my major/career field.', 8: 'I do not often think about my personal development in my major/career field.' } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.questions = [] <NEW_LINE> for qid in range(1, len(self.question_text)+1): <NEW_LINE> <INDENT> text = self.question_text[qid] <NEW_LINE> self.questions.append(CareerCommitmentQuestion(qid, text)) <NEW_LINE> <DEDENT> <DEDENT> def compute_metrics(self): <NEW_LINE> <INDENT> def reverse(s): <NEW_LINE> <INDENT> return 6 - int(s) <NEW_LINE> <DEDENT> self.metrics = { 'identity': (int(self.answers[1]) + int(self.answers[2]) + reverse(self.answers[3]) + int(self.answers[4]))/4., 'planning': (reverse(self.answers[5]) + int(self.answers[6]) + reverse(self.answers[7]) + reverse(self.answers[8]))/4. } <NEW_LINE> <DEDENT> def review_process_metrics(self, data, metrics): <NEW_LINE> <INDENT> labels = { 'identity': 'Identity factor', 'planning': 'Planning factor' } <NEW_LINE> data['slider_containers'] = {} <NEW_LINE> min_score = 1 <NEW_LINE> max_score = 5 <NEW_LINE> for metric in metrics: <NEW_LINE> <INDENT> marker = SliderMarker('you', 'You', metric.value) <NEW_LINE> slider = Slider(min_score, max_score, (marker,)) <NEW_LINE> labels2 = (labels[metric.key], '') <NEW_LINE> data['slider_containers'][metric.key] = SliderContainer(labels2, slider)
Define the questions and score computation
62598fba5166f23b2e243565
class Count(sdb.Command): <NEW_LINE> <INDENT> names = ["count", "cnt", "wc"] <NEW_LINE> def _call(self, objs: Iterable[drgn.Object]) -> Iterable[drgn.Object]: <NEW_LINE> <INDENT> yield sdb.create_object('unsigned long long', sum(1 for _ in objs))
Return a count of the number of objects in the pipeline EXAMPLES Print the number of addresses given sdb> addr 0 | count (unsigned long long)1 sdb> addr 0 | addr 1 | count (unsigned long long)2 Print the number of ZFS dbufs sdb> dbuf | count (unsigned long long)19 Print the number of root slab caches in the system sdb> slabs | count (unsigned long long)136 Print the number of level 3 log statements in the kernel log buffer sdb> dmesg | filter obj.level == 3 | count (unsigned long long)24
62598fba4527f215b58ea05c
class Feed(models.Model): <NEW_LINE> <INDENT> uuid = models.UUIDField(default=uuid4, editable=False, unique=True) <NEW_LINE> user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name="feeds" ) <NEW_LINE> url = models.URLField(_("Url")) <NEW_LINE> title = models.CharField( _("Title"), max_length=255, db_index=True, blank=True, null=True ) <NEW_LINE> subtitle = models.TextField(_("Subtitle"), blank=True, null=True) <NEW_LINE> rights = models.CharField(_("Rights"), max_length=255, blank=True, null=True) <NEW_LINE> info = models.CharField(_("Infos"), max_length=255, blank=True, null=True) <NEW_LINE> language = models.CharField(_("Language"), max_length=50, blank=True, null=True) <NEW_LINE> guid = models.CharField( _("Global Unique Identifier"), max_length=32, blank=True, null=True, db_index=True, ) <NEW_LINE> icon_url = models.URLField(_("Icon URL"), blank=True, null=True) <NEW_LINE> image_url = models.URLField(_("Image URL"), blank=True, null=True) <NEW_LINE> last_modified = models.DateTimeField( _("Last modified"), null=True, blank=True, db_index=True ) <NEW_LINE> last_updated = models.DateTimeField(_("Last updated"), null=True, blank=True) <NEW_LINE> is_active = models.BooleanField(default=False) <NEW_LINE> objects = FeedManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = "feeds" <NEW_LINE> verbose_name = _("Feed") <NEW_LINE> verbose_name_plural = _("Feeds") <NEW_LINE> constraints = [ models.UniqueConstraint(fields=["url", "user"], name="unique_feed_per_user") ] <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return str(self.uuid)
All of these fields are from Feedparser's Feed object
62598fba3539df3088ecc434
@pytest.mark.usefixtures('db') <NEW_LINE> class TestAuthController: <NEW_LINE> <INDENT> def test_create_jwt(self): <NEW_LINE> <INDENT> token = auth.create_jwt(12345) <NEW_LINE> assert isinstance(token, str) <NEW_LINE> <DEDENT> def test_login_success_new_user(self): <NEW_LINE> <INDENT> mock_amazon = Mock(name='get') <NEW_LINE> mock_amazon.return_value = AmazonSuccess <NEW_LINE> with patch.object(requests, 'get', mock_amazon): <NEW_LINE> <INDENT> response = auth.login('test_token') <NEW_LINE> assert response['email'] == 'test@test.com' <NEW_LINE> <DEDENT> <DEDENT> def test_login_success_existing_user(self): <NEW_LINE> <INDENT> user = User('test@test.com') <NEW_LINE> user.save() <NEW_LINE> mock_amazon = Mock(name='get') <NEW_LINE> mock_amazon.return_value = AmazonSuccess <NEW_LINE> with patch.object(requests, 'get', mock_amazon): <NEW_LINE> <INDENT> response = auth.login('test_token') <NEW_LINE> assert response['email'] == 'test@test.com' <NEW_LINE> <DEDENT> <DEDENT> def test_login_fail(self): <NEW_LINE> <INDENT> mock_amazon = Mock(name='get') <NEW_LINE> mock_amazon.return_value = AmazonFail <NEW_LINE> with patch.object(requests, 'get', mock_amazon): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = auth.login('test_token') <NEW_LINE> <DEDENT> except FlaskError as e: <NEW_LINE> <INDENT> assert e.to_dict() == { 'message': 'Could not authenticate user', 'status_code': 401 } <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_get_user(self): <NEW_LINE> <INDENT> user = create_user('test@test.com') <NEW_LINE> retrieved = auth.get_user(user['token']).to_dict() <NEW_LINE> assert retrieved['id'] == user['user'].id <NEW_LINE> assert retrieved['email'] == user['email'] <NEW_LINE> <DEDENT> def test_get_user_notfound(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> token = auth.create_jwt('test@test.com') <NEW_LINE> retrieved = auth.get_user(token).to_dict() <NEW_LINE> <DEDENT> except FlaskError as e: <NEW_LINE> <INDENT> assert e.to_dict() == {'message': 'User not found', 'status_code': 401}
Tests for AuthController
62598fbaf548e778e596b72d
class HelpIntentHandler(AbstractRequestHandler): <NEW_LINE> <INDENT> def can_handle(self, handler_input): <NEW_LINE> <INDENT> return ( is_intent_name("AMAZON.HelpIntent")(handler_input) or is_intent_name("noticias_ayuda")(handler_input) ) <NEW_LINE> <DEDENT> def handle(self, handler_input): <NEW_LINE> <INDENT> logger.info("In HelpIntentHandler") <NEW_LINE> handler_input.response_builder.speak(HELP_MESSAGE).ask( HELP_REPROMPT).set_card(SimpleCard( SKILL_NAME, re.sub('<[^<]+>', "",HELP_MESSAGE))).set_should_end_session(False) <NEW_LINE> return handler_input.response_builder.response
Handler for Help Intent.
62598fbad7e4931a7ef3c21e
class Session(pydantic.BaseModel, orm_mode=True): <NEW_LINE> <INDENT> uuid: uuid.UUID <NEW_LINE> expiration_time: datetime <NEW_LINE> revoked: bool
This related to refresh tokens, which have a session uuid ("sid") claim. When the client attempts to use a refresh token, we first check here to ensure that the "session", which is associated with a chain of refresh tokens that came from a single authentication, are still valid.
62598fbaff9c53063f51a7d6
class _Loader(object): <NEW_LINE> <INDENT> def __init__(self, object_graph_proto, saved_model_proto, export_dir): <NEW_LINE> <INDENT> meta_graph = saved_model_proto.meta_graphs[0] <NEW_LINE> self._asset_file_def = meta_graph.asset_file_def <NEW_LINE> self._proto = object_graph_proto <NEW_LINE> self._export_dir = export_dir <NEW_LINE> self._defined_functions = {} <NEW_LINE> for defined_function in function_lib.from_library( meta_graph.graph_def.library): <NEW_LINE> <INDENT> defined_function.add_to_graph(None) <NEW_LINE> self._defined_functions[defined_function.name] = defined_function <NEW_LINE> <DEDENT> self._load_all() <NEW_LINE> self._restore_checkpoint() <NEW_LINE> <DEDENT> def _load_all(self): <NEW_LINE> <INDENT> self._nodes = [self._recreate(proto) for proto in self._proto.nodes] <NEW_LINE> for obj, object_proto in zip(self._nodes, self._proto.nodes): <NEW_LINE> <INDENT> for reference in object_proto.children: <NEW_LINE> <INDENT> setattr(obj, reference.local_name, self._nodes[reference.node_id]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _restore_checkpoint(self): <NEW_LINE> <INDENT> variables_path = saved_model_utils.get_variables_path(self._export_dir) <NEW_LINE> saver = util.CheckpointableSaver(self.get(0)) <NEW_LINE> saver.restore(variables_path).assert_consumed() <NEW_LINE> <DEDENT> def get(self, node_id): <NEW_LINE> <INDENT> return self._nodes[node_id] <NEW_LINE> <DEDENT> def _recreate(self, proto): <NEW_LINE> <INDENT> factory = { "user_object": lambda: self._recreate_user_object(proto.user_object), "asset": lambda: self._recreate_asset(proto.asset), "function": lambda: self._recreate_function(proto.function), "variable": lambda: self._recreate_variable(proto.variable), } <NEW_LINE> kind = proto.WhichOneof("kind") <NEW_LINE> if kind not in factory: <NEW_LINE> <INDENT> raise ValueError("Unknown SavedObject type: %r" % kind) <NEW_LINE> <DEDENT> return factory[kind]() <NEW_LINE> <DEDENT> def _recreate_user_object(self, proto): <NEW_LINE> <INDENT> del proto <NEW_LINE> return tracking.Checkpointable() <NEW_LINE> <DEDENT> def _recreate_asset(self, proto): <NEW_LINE> <INDENT> filename = os.path.join( saved_model_utils.get_assets_dir(self._export_dir), self._asset_file_def[proto.asset_file_def_index].filename) <NEW_LINE> return tracking.TrackableAsset(filename) <NEW_LINE> <DEDENT> def _recreate_function(self, proto): <NEW_LINE> <INDENT> return function_deserialization.recreate_polymorphic_function( proto, self._defined_functions) <NEW_LINE> <DEDENT> def _recreate_variable(self, proto): <NEW_LINE> <INDENT> dummy_value = init_ops.Zeros(dtype=proto.dtype)(shape=proto.shape) <NEW_LINE> return variables.Variable(dummy_value)
Helper class to load an object-based SavedModel.
62598fba656771135c4897f6
class Dataset(data.Dataset): <NEW_LINE> <INDENT> def __init__(self, table, vocab, transform=None): <NEW_LINE> <INDENT> with open(table, 'rb') as f: <NEW_LINE> <INDENT> self.table = pickle.load(f) <NEW_LINE> <DEDENT> self.ids = list(self.table.id) <NEW_LINE> self.vocab = vocab <NEW_LINE> self.transform = transform <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> table = self.table <NEW_LINE> vocab = self.vocab <NEW_LINE> ann_id = self.ids[index] <NEW_LINE> caption = table[table.id==ann_id]['sentence'].item() <NEW_LINE> path = table[table.id==ann_id]['file'].item() <NEW_LINE> images=[] <NEW_LINE> for i in range(151): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> p=path[i] <NEW_LINE> image = Image.open(p).convert('RGB') <NEW_LINE> image=np.transpose(image, (2, 0, 1)) <NEW_LINE> image=torch.from_numpy(np.array(image)).float() <NEW_LINE> transform = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) <NEW_LINE> image=transform(image) <NEW_LINE> images.append(image) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> images.append(torch.from_numpy(np.zeros((3,224,224))).float()) <NEW_LINE> <DEDENT> <DEDENT> seq_img=torch.stack(images,0) <NEW_LINE> tokens = (str(caption).lower()).split() <NEW_LINE> caption = [] <NEW_LINE> caption.append(vocab('<start>')) <NEW_LINE> caption.extend([vocab(token) for token in tokens]) <NEW_LINE> caption.append(vocab('<end>')) <NEW_LINE> target = torch.Tensor(caption) <NEW_LINE> return seq_img, target <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.ids)
COCO Custom Dataset compatible with torch.utils.data.DataLoader.
62598fba3346ee7daa33770c
@ut.skipUnless(h5py.version.hdf5_version_tuple >= (1, 9, 178), 'SWMR requires HDF5 >= 1.9.178') <NEW_LINE> class TestDatasetSwmrRead(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> TestCase.setUp(self) <NEW_LINE> self.data = np.arange(13).astype('f') <NEW_LINE> self.dset = self.f.create_dataset('data', chunks=(13,), maxshape=(None,), data=self.data) <NEW_LINE> fname = self.f.filename <NEW_LINE> self.f.close() <NEW_LINE> self.f = h5py.File(fname, 'r', swmr=True) <NEW_LINE> self.dset = self.f['data'] <NEW_LINE> <DEDENT> def test_initial_swmr_mode_on(self): <NEW_LINE> <INDENT> self.assertTrue(self.f.swmr_mode) <NEW_LINE> <DEDENT> def test_read_data(self): <NEW_LINE> <INDENT> self.assertArrayEqual(self.dset, self.data) <NEW_LINE> <DEDENT> def test_refresh(self): <NEW_LINE> <INDENT> self.dset.refresh() <NEW_LINE> <DEDENT> def test_force_swmr_mode_on_raises(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> self.f.swmr_mode = True <NEW_LINE> <DEDENT> self.assertTrue(self.f.swmr_mode) <NEW_LINE> <DEDENT> def test_force_swmr_mode_off_raises(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> self.f.swmr_mode = False <NEW_LINE> <DEDENT> self.assertTrue(self.f.swmr_mode)
Testing SWMR functions when reading a dataset. Skip this test if the HDF5 library does not have the SWMR features.
62598fba2c8b7c6e89bd394e
class ConfigHelper: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_agent_service_address() -> str: <NEW_LINE> <INDENT> address = os.getenv("TP_AGENT_URL") <NEW_LINE> if address is None: <NEW_LINE> <INDENT> logging.info( "No Agent service address found in TP_AGENT_URL environment variable, " "defaulting to http://127.0.0.1:8585 (localhost)" ) <NEW_LINE> return "http://127.0.0.1:8585" <NEW_LINE> <DEDENT> address = address.replace("localhost", "127.0.0.1") <NEW_LINE> logging.info(f"Using {address} as the Agent URL") <NEW_LINE> return address <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_developer_token() -> str: <NEW_LINE> <INDENT> token = os.getenv("TP_DEV_TOKEN") <NEW_LINE> if token is None: <NEW_LINE> <INDENT> logging.error("No developer token was found, did you set it in the TP_DEV_TOKEN environment variable?") <NEW_LINE> logging.error("You can get a developer token from https://app.testproject.io/#/integrations/sdk?lang=Python") <NEW_LINE> raise SdkException("No development token defined in TP_DEV_TOKEN environment variable") <NEW_LINE> <DEDENT> return token <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_sdk_version() -> str: <NEW_LINE> <INDENT> return definitions.get_sdk_version()
Contains helper methods for SDK configuration
62598fbaa05bb46b3848a9f4
class Bebee(Platform): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.platformName = "Bebee" <NEW_LINE> self.tags = ["jobs"] <NEW_LINE> self.isValidMode = {} <NEW_LINE> self.isValidMode["phonefy"] = False <NEW_LINE> self.isValidMode["usufy"] = True <NEW_LINE> self.isValidMode["searchfy"] = False <NEW_LINE> self.url = {} <NEW_LINE> self.url["usufy"] = "https://bebee.com/bee/" + "<usufy>" <NEW_LINE> self.needsCredentials = {} <NEW_LINE> self.needsCredentials["usufy"] = False <NEW_LINE> self.validQuery = {} <NEW_LINE> self.validQuery["usufy"] = ".+" <NEW_LINE> self.notFoundText = {} <NEW_LINE> self.notFoundText["usufy"] = ['<link rel="canonical" href="https://.bebee.com/bees/search">'] <NEW_LINE> self.fieldsRegExp = {} <NEW_LINE> self.fieldsRegExp["usufy"] = {} <NEW_LINE> self.fieldsRegExp["usufy"]["i3visio.fullname"] = {"start": '<title>', "end": '- beBee</title>'} <NEW_LINE> self.fieldsRegExp["usufy"]["i3visio.location"] = {"start": '<span itemprop="addressRegion">', "end": '</span>'} <NEW_LINE> self.fieldsRegExp["usufy"]["i3visio.alias.googleplus"] = {"start": '<div><a rel="nofollow" class="color_corp_three" href="https://plus.google.com/u/0/', "end": '"'} <NEW_LINE> self.fieldsRegExp["usufy"]["i3visio.alias.linkedin"] = {"start": '<div><a rel="nofollow" class="color_corp_three" href="http://br.linkedin.com/in/', "end": '"'} <NEW_LINE> self.foundFields = {}
A <Platform> object for Bebee.
62598fba283ffb24f3cf3a0c
class treeNode(object): <NEW_LINE> <INDENT> def __init__(self,variableBindings,predicate): <NEW_LINE> <INDENT> self.variableBindings = variableBindings <NEW_LINE> self.predicate = predicate <NEW_LINE> self.proved = False <NEW_LINE> <DEDENT> def allVariablesBound(self,fact): <NEW_LINE> <INDENT> for variable in self.variableBindings: <NEW_LINE> <INDENT> if self.variableBindings[variable] == "unbound": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if variable in self.predicate.variables: <NEW_LINE> <INDENT> pos = self.predicate.variables.index(variable) <NEW_LINE> if not fact.objects[pos] == self.variableBindings[variable]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def matchFound(self,fact): <NEW_LINE> <INDENT> match = True <NEW_LINE> for variable in self.variableBindings: <NEW_LINE> <INDENT> if not self.variableBindings[variable] == "unbound": <NEW_LINE> <INDENT> obj = self.variableBindings[variable] <NEW_LINE> if variable in self.predicate.variables: <NEW_LINE> <INDENT> if fact.objects[self.predicate.variables.index(variable)] != obj: <NEW_LINE> <INDENT> match = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return match <NEW_LINE> <DEDENT> def bindUnboundVariables(self,fact): <NEW_LINE> <INDENT> newVariableBindings = deepcopy(self.variableBindings) <NEW_LINE> for variable in newVariableBindings: <NEW_LINE> <INDENT> if newVariableBindings[variable] == "unbound": <NEW_LINE> <INDENT> pos = self.predicate.variables.index(variable) <NEW_LINE> newVariableBindings[variable] = fact.objects[pos] <NEW_LINE> <DEDENT> <DEDENT> return newVariableBindings <NEW_LINE> <DEDENT> def searchFacts(self,facts,stack): <NEW_LINE> <INDENT> for fact in facts: <NEW_LINE> <INDENT> if self.predicate.relation == fact.relation: <NEW_LINE> <INDENT> if self.allVariablesBound(fact): <NEW_LINE> <INDENT> self.proved = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.matchFound(fact): <NEW_LINE> <INDENT> stack.append(treeNode(self.bindUnboundVariables(fact),self.predicate))
class for a node in the proof tree
62598fba63b5f9789fe852f8
class Task(object): <NEW_LINE> <INDENT> def __init__(self, init_time, init_rect, labels=None, last_time=None, attributes=None): <NEW_LINE> <INDENT> self.init_time = init_time <NEW_LINE> self.init_rect = init_rect <NEW_LINE> if labels: <NEW_LINE> <INDENT> if init_time in labels: <NEW_LINE> <INDENT> raise ValueError('labels should not contain init time') <NEW_LINE> <DEDENT> <DEDENT> self.labels = labels <NEW_LINE> if last_time is None and labels is not None: <NEW_LINE> <INDENT> self.last_time = labels.sorted_keys()[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.last_time = last_time <NEW_LINE> <DEDENT> self.attributes = attributes or {} <NEW_LINE> <DEDENT> def len(self): <NEW_LINE> <INDENT> return self.last_time - self.init_time + 1
Describes a tracking task with optional ground-truth annotations.
62598fba4a966d76dd5ef05c
class Grid(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.grid_size = params.grid_size <NEW_LINE> self.grid = [[Cell(i, j) for j in range(params.grid_size[0])] for i in range(params.grid_size[1])] <NEW_LINE> self.nests = [] <NEW_LINE> self.update_time = 0 <NEW_LINE> self.step = params.step <NEW_LINE> <DEDENT> def __getitem__(self, pos): <NEW_LINE> <INDENT> i, j = pos <NEW_LINE> if (i*(i-self.grid_size[0]) > 0) or (j*(j-self.grid_size[1]) > 0): <NEW_LINE> <INDENT> print("coordinates out of bound, grid size :", (i, j), "out of", self.grid_size) <NEW_LINE> raise NameError("Cell not found") <NEW_LINE> return None <NEW_LINE> <DEDENT> return self.grid[i][j] <NEW_LINE> <DEDENT> def load_grid(self, filename): <NEW_LINE> <INDENT> file = open(filename, "r") <NEW_LINE> lines = file.readlines() <NEW_LINE> file.close() <NEW_LINE> for i in lines: <NEW_LINE> <INDENT> i = i.replace("\n", "").split(",") <NEW_LINE> self.grid[int(i[0])][int(i[1])].type = i[2].upper() <NEW_LINE> if i[2] == "NEST": <NEW_LINE> <INDENT> self.nests.append([int(n) for n in i[:2]]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def save_grid(self, filename): <NEW_LINE> <INDENT> file = open(filename, "w") <NEW_LINE> for i in range(self.grid_size[0]): <NEW_LINE> <INDENT> for j in range(self.grid_size[1]): <NEW_LINE> <INDENT> if self.grid[i][j].type != "ROAD": <NEW_LINE> <INDENT> file.write(str(i)+","+str(j)+","+self.grid[i][j].type+"\n") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> file.close() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.update_time = (self.update_time+1)%self.step <NEW_LINE> if self.update_time == 0: <NEW_LINE> <INDENT> for row in self.grid: <NEW_LINE> <INDENT> for cell in row: <NEW_LINE> <INDENT> cell.update() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def draw(self, display): <NEW_LINE> <INDENT> for row in self.grid: <NEW_LINE> <INDENT> for cell in row: <NEW_LINE> <INDENT> cell.draw(display, params.block_size)
Definig the Grid object The Grid is basically a matrix of Cells
62598fba21bff66bcd722df3
class Post(models.Model): <NEW_LINE> <INDENT> title = models.CharField(u'标题',max_length = 200) <NEW_LINE> body = models.TextField(u'内容') <NEW_LINE> createDatetime = models.DateTimeField(u'创建时间',auto_now_add = True) <NEW_LINE> updateDatetime = models.DateTimeField(u'修改时间',auto_now = True) <NEW_LINE> tag = models.ManyToManyField('Tag') <NEW_LINE> count = models.IntegerField(default=0) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'blog' <NEW_LINE> verbose_name = u'博客' <NEW_LINE> verbose_name_plural = u'博客' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.title
存储blog的主表
62598fbadc8b845886d53742
class ScopeTracker(object): <NEW_LINE> <INDENT> def __init__(self, fn=None): <NEW_LINE> <INDENT> self._scopes = [] <NEW_LINE> self._fn = fn if fn is not None else lambda *args, **kwargs: None <NEW_LINE> <DEDENT> def scopes(self): <NEW_LINE> <INDENT> return self._scopes <NEW_LINE> <DEDENT> def latest(self): <NEW_LINE> <INDENT> if not self._scopes: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._scopes[-1] <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> scope = tf.get_variable_scope() <NEW_LINE> self._scopes.append(scope) <NEW_LINE> return self._fn(*args, **kwargs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def empty(cls): <NEW_LINE> <INDENT> def _empty(*args, **kwargs): <NEW_LINE> <INDENT> _, _ = args, kwargs <NEW_LINE> <DEDENT> return ScopeTracker(_empty) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def identity(cls): <NEW_LINE> <INDENT> return ScopeTracker(lambda x: x)
Function class that just tracks the tf.VariableScope.
62598fba7047854f4633f55f
class XsrfSecret(ndb.Model): <NEW_LINE> <INDENT> secret = ndb.StringProperty(required=True) <NEW_LINE> @staticmethod <NEW_LINE> def get(): <NEW_LINE> <INDENT> secret = memcache.get('xsrf_secret') <NEW_LINE> if not secret: <NEW_LINE> <INDENT> xsrf_secret = XsrfSecret.query().get() <NEW_LINE> if not xsrf_secret: <NEW_LINE> <INDENT> secret = binascii.b2a_hex(os.urandom(16)) <NEW_LINE> xsrf_secret = XsrfSecret(secret=secret) <NEW_LINE> xsrf_secret.put() <NEW_LINE> <DEDENT> secret = xsrf_secret.secret <NEW_LINE> memcache.set('xsrf_secret', secret) <NEW_LINE> <DEDENT> return secret
Model for datastore to store the XSRF secret.
62598fba5fc7496912d48340
class ChunkReader(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.mode = "start" <NEW_LINE> self.start = True <NEW_LINE> self.remaining = 0 <NEW_LINE> <DEDENT> def feed_predict(self): <NEW_LINE> <INDENT> if self.mode == 'start': <NEW_LINE> <INDENT> return None, '\r\n' <NEW_LINE> <DEDENT> elif self.mode == 'chunk': <NEW_LINE> <INDENT> if self.remaining == 0: <NEW_LINE> <INDENT> return None, '\r\n' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.remaining, None <NEW_LINE> <DEDENT> <DEDENT> elif self.mode == 'trailer': <NEW_LINE> <INDENT> return None, '\r\n' <NEW_LINE> <DEDENT> elif self.mode == 'end': <NEW_LINE> <INDENT> return 0, None <NEW_LINE> <DEDENT> <DEDENT> def feed_start(self, parser, text): <NEW_LINE> <INDENT> pos = len(parser.buffer) <NEW_LINE> line, text = parser.feed_line(text) <NEW_LINE> offset = len(parser.buffer) <NEW_LINE> if line is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chunk = int(line.split(b';', 1)[0], 16) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> if self.start: <NEW_LINE> <INDENT> del parser.buffer[pos:] <NEW_LINE> parser.offset = len(parser.buffer) <NEW_LINE> raise BrokenChunks() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> parser.body_chunks.append((offset, chunk)) <NEW_LINE> self.remaining = chunk <NEW_LINE> if chunk == 0: <NEW_LINE> <INDENT> self.mode = 'trailer' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mode = 'chunk' <NEW_LINE> <DEDENT> <DEDENT> self.start = False <NEW_LINE> return text <NEW_LINE> <DEDENT> def feed_chunk(self, parser, text): <NEW_LINE> <INDENT> if self.remaining > 0: <NEW_LINE> <INDENT> self.remaining, text = parser.feed_length(text, self.remaining) <NEW_LINE> <DEDENT> if self.remaining == 0: <NEW_LINE> <INDENT> end_of_chunk, text = parser.feed_line(text) <NEW_LINE> if end_of_chunk: <NEW_LINE> <INDENT> self.mode = 'start' <NEW_LINE> <DEDENT> <DEDENT> return text <NEW_LINE> <DEDENT> def feed_trailer(self, parser, text): <NEW_LINE> <INDENT> line, text = parser.feed_line(text) <NEW_LINE> if line is not None: <NEW_LINE> <INDENT> parser.header.add_trailer_line(line) <NEW_LINE> if line in NEWLINES: <NEW_LINE> <INDENT> self.mode = 'end' <NEW_LINE> <DEDENT> <DEDENT> return text <NEW_LINE> <DEDENT> def feed(self, parser, text): <NEW_LINE> <INDENT> while text: <NEW_LINE> <INDENT> if self.mode == 'start': <NEW_LINE> <INDENT> text = self.feed_start(parser, text) <NEW_LINE> <DEDENT> if text and self.mode == 'chunk': <NEW_LINE> <INDENT> text = self.feed_chunk(parser, text) <NEW_LINE> <DEDENT> if text and self.mode == 'trailer': <NEW_LINE> <INDENT> text = self.feed_trailer(parser, text) <NEW_LINE> <DEDENT> if self.mode == 'end': <NEW_LINE> <INDENT> parser.mode = 'end' <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return text
Reads the body of a HTTP message with chunked encoding.
62598fba283ffb24f3cf3a0d
class FanStatusP5(DeviceStatus): <NEW_LINE> <INDENT> def __init__(self, data: Dict[str, Any]) -> None: <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> @property <NEW_LINE> def power(self) -> str: <NEW_LINE> <INDENT> return "on" if self.data["power"] else "off" <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self) -> bool: <NEW_LINE> <INDENT> return self.data["power"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def mode(self) -> OperationMode: <NEW_LINE> <INDENT> return OperationMode(self.data["mode"]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def speed(self) -> int: <NEW_LINE> <INDENT> return self.data["speed"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def oscillate(self) -> bool: <NEW_LINE> <INDENT> return self.data["roll_enable"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def angle(self) -> int: <NEW_LINE> <INDENT> return self.data["roll_angle"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def delay_off_countdown(self) -> int: <NEW_LINE> <INDENT> return self.data["time_off"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def led(self) -> bool: <NEW_LINE> <INDENT> return self.data["light"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def buzzer(self) -> bool: <NEW_LINE> <INDENT> return self.data["beep_sound"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def child_lock(self) -> bool: <NEW_LINE> <INDENT> return self.data["child_lock"]
Container for status reports from the Xiaomi Mi Smart Pedestal Fan DMaker P5.
62598fbacc0a2c111447b197
class _AtomType(object): <NEW_LINE> <INDENT> def __init__(self, name, atomClass, mass, element): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.atomClass = atomClass <NEW_LINE> self.mass = mass <NEW_LINE> self.element = element
Inner class used to record atom types and associated properties.
62598fbad7e4931a7ef3c220
class x_amber_mdout_single_configuration_calculation(MCategory): <NEW_LINE> <INDENT> m_def = Category( a_legacy=LegacyDefinition(name='x_amber_mdout_single_configuration_calculation'))
Parameters of mdout belonging to section_single_configuration_calculation.
62598fba57b8e32f525081e1
class Movie(): <NEW_LINE> <INDENT> def __init__(self, movie_title, poster_image, trailer_youtube): <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.poster_image_url = poster_image <NEW_LINE> self.trailer_youtube_url = trailer_youtube
This class provides a way to store movie related information, including the title, poster image and trailer URL.
62598fba56ac1b37e6302377
class InlineCommand(CommandBase): <NEW_LINE> <INDENT> RE = re.compile(r'\[' r'!(?P<command>\w+)' r'(?:!(?P<subcommand>\S+))?' r' *(?P<settings>\w+=.*?)?' r'\]' r'(?:\((?P<inline>.*?)\))?', flags=re.UNICODE|re.DOTALL)
Inline commands as: [!command key=value] [!command](content in here) [!command!subcommand key=value] [!command!subcommand key=value](content in here) https://regex101.com/r/B7er21/1
62598fba92d797404e388c28
class Subscription(models.BASE, models.NovaBase): <NEW_LINE> <INDENT> __tablename__ = 'subscriptions' <NEW_LINE> id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) <NEW_LINE> project_id = Column(Integer, nullable=False, index=True) <NEW_LINE> product_id = Column(Integer, ForeignKey(Product.id), nullable=False) <NEW_LINE> product = relationship(Product, backref=backref('subscriptions'), foreign_keys=product_id, primaryjoin='and_(' 'Subscription.product_id == Product.id,' 'Subscription.deleted == False)') <NEW_LINE> resource_uuid = Column(String(255), nullable=False, index=True) <NEW_LINE> resource_name = Column(String(255), nullable=False) <NEW_LINE> expires_at = Column(DateTime, nullable=False, index=True) <NEW_LINE> status = Column(String(255), nullable=False)
Represents subscriptions.
62598fba442bda511e95c5e6
class Export_pc2(bpy.types.Operator, ExportHelper): <NEW_LINE> <INDENT> bl_idname = "export_shape.pc2" <NEW_LINE> bl_label = "Export Pointcache (.pc2)" <NEW_LINE> filename_ext = ".pc2" <NEW_LINE> rot_x90 = BoolProperty(name="Convert to Y-up", description="Rotate 90 degrees around X to convert to y-up", default=True, ) <NEW_LINE> world_space = BoolProperty(name="Export into Worldspace", description="Transform the Vertexcoordinates into Worldspace", default=False, ) <NEW_LINE> apply_modifiers = BoolProperty(name="Apply Modifiers", description="Applies the Modifiers", default=True, ) <NEW_LINE> range_start = IntProperty(name='Start Frame', description='First frame to use for Export', default=1, ) <NEW_LINE> range_end = IntProperty(name='End Frame', description='Last frame to use for Export', default=250, ) <NEW_LINE> sampling = EnumProperty(name='Sampling', description='Sampling --> frames per sample (0.1 yields 10 samples per frame)', items=(('0.01', '0.01', ''), ('0.05', '0.05', ''), ('0.1', '0.1', ''), ('0.2', '0.2', ''), ('0.25', '0.25', ''), ('0.5', '0.5', ''), ('1', '1', ''), ('2', '2', ''), ('3', '3', ''), ('4', '4', ''), ('5', '5', ''), ('10', '10', ''), ), default='1', ) <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return context.active_object.type in {'MESH', 'CURVE', 'SURFACE', 'FONT'} <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> print('\n_____START_____') <NEW_LINE> props = self.properties <NEW_LINE> filepath = self.filepath <NEW_LINE> filepath = bpy.path.ensure_ext(filepath, self.filename_ext) <NEW_LINE> exported = do_export(context, props, filepath) <NEW_LINE> if exported: <NEW_LINE> <INDENT> print('finished export in %s seconds' %((time.time() - start_time))) <NEW_LINE> print(filepath) <NEW_LINE> <DEDENT> return {'FINISHED'} <NEW_LINE> <DEDENT> def invoke(self, context, event): <NEW_LINE> <INDENT> wm = context.window_manager <NEW_LINE> if True: <NEW_LINE> <INDENT> wm.fileselect_add(self) <NEW_LINE> return {'RUNNING_MODAL'} <NEW_LINE> <DEDENT> elif True: <NEW_LINE> <INDENT> wm.invoke_search_popup(self) <NEW_LINE> return {'RUNNING_MODAL'} <NEW_LINE> <DEDENT> elif False: <NEW_LINE> <INDENT> return wm.invoke_props_popup(self, event) <NEW_LINE> <DEDENT> elif False: <NEW_LINE> <INDENT> return self.execute(context)
Export the active Object as a .pc2 Pointcache file
62598fba66673b3332c3055b
class ProdConfig(Config): <NEW_LINE> <INDENT> SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL") <NEW_LINE> JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY')
Production configuration child class Args: Config: The parent configuration class with General configuration settings
62598fba8a349b6b436863c7
class UserMixin(object): <NEW_LINE> <INDENT> @declared_attr <NEW_LINE> def created_by_id(cls): <NEW_LINE> <INDENT> return Column(None, ForeignKey('users.id'), nullable=False, default=1) <NEW_LINE> <DEDENT> @declared_attr <NEW_LINE> def created_time(cls): <NEW_LINE> <INDENT> return Column('created_time', types.DateTime, default=utils.utcnow, nullable=False) <NEW_LINE> <DEDENT> @declared_attr <NEW_LINE> def updated_by_id(cls): <NEW_LINE> <INDENT> return Column(None, ForeignKey('users.id'), nullable=False, default=1) <NEW_LINE> <DEDENT> @declared_attr <NEW_LINE> def updated_time(cls): <NEW_LINE> <INDENT> return Column('updated_time', types.DateTime, default=utils.utcnow, nullable=False) <NEW_LINE> <DEDENT> @declared_attr <NEW_LINE> def created_by(cls): <NEW_LINE> <INDENT> return orm.relationship( 'User', foreign_keys='%s.created_by_id' % cls.__name__, remote_side='User.id', post_update=True) <NEW_LINE> <DEDENT> @declared_attr <NEW_LINE> def updated_by(cls): <NEW_LINE> <INDENT> return orm.relationship( 'User', foreign_keys='%s.updated_by_id' % cls.__name__, remote_side='User.id', post_update=True)
Use as a mixin on a sqlalchemy declarative class to add the created_by, created_time, updated_by, and updated_time attributes to track modification history.
62598fbaaad79263cf42e95f
@dataclass(frozen=True) <NEW_LINE> class EventPaymentSentFailed(Event): <NEW_LINE> <INDENT> token_network_registry_address: TokenNetworkRegistryAddress <NEW_LINE> token_network_address: TokenNetworkAddress <NEW_LINE> identifier: PaymentID <NEW_LINE> target: TargetAddress <NEW_LINE> reason: str <NEW_LINE> def __repr__(self) -> str: <NEW_LINE> <INDENT> return ( f"{self.__class__.__name__}< " f"token_network_address: {to_checksum_address(self.token_network_address)} " f"identifier: {self.identifier} " f"target: {to_checksum_address(self.target)} " f"reason: {self.reason} " f">" )
Event emitted by the payer when a transfer has failed. Note: Mediators cannot use this event since they don't know when a transfer has failed, they may infer about lock successes and failures.
62598fba167d2b6e312b7100
class PermissionHelper(object): <NEW_LINE> <INDENT> def __init__(self, model, inspect_view_enabled=False): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.opts = model._meta <NEW_LINE> self.inspect_view_enabled = inspect_view_enabled <NEW_LINE> <DEDENT> def get_all_model_permissions(self): <NEW_LINE> <INDENT> return Permission.objects.filter( content_type__app_label=self.opts.app_label, content_type__model=self.opts.model_name, ) <NEW_LINE> <DEDENT> def get_perm_codename(self, action): <NEW_LINE> <INDENT> return get_permission_codename(action, self.opts) <NEW_LINE> <DEDENT> def user_has_specific_permission(self, user, perm_codename): <NEW_LINE> <INDENT> return user.has_perm("%s.%s" % (self.opts.app_label, perm_codename)) <NEW_LINE> <DEDENT> def user_has_any_permissions(self, user): <NEW_LINE> <INDENT> for perm in self.get_all_model_permissions().values('codename'): <NEW_LINE> <INDENT> if self.user_has_specific_permission(user, perm['codename']): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def user_can_list(self, user): <NEW_LINE> <INDENT> return self.user_has_any_permissions(user) <NEW_LINE> <DEDENT> def user_can_create(self, user): <NEW_LINE> <INDENT> perm_codename = self.get_perm_codename('add') <NEW_LINE> return self.user_has_specific_permission(user, perm_codename) <NEW_LINE> <DEDENT> def user_can_inspect_obj(self, user, obj): <NEW_LINE> <INDENT> return self.inspect_view_enabled and self.user_has_any_permissions( user) <NEW_LINE> <DEDENT> def user_can_edit_obj(self, user, obj): <NEW_LINE> <INDENT> perm_codename = self.get_perm_codename('change') <NEW_LINE> return self.user_has_specific_permission(user, perm_codename) <NEW_LINE> <DEDENT> def user_can_delete_obj(self, user, obj): <NEW_LINE> <INDENT> perm_codename = self.get_perm_codename('delete') <NEW_LINE> return self.user_has_specific_permission(user, perm_codename) <NEW_LINE> <DEDENT> def user_can_unpublish_obj(self, user, obj): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def user_can_copy_obj(self, user, obj): <NEW_LINE> <INDENT> return False
Provides permission-related helper functions to help determine what a user can do with a 'typical' model (where permissions are granted model-wide), and to a specific instance of that model.
62598fba091ae35668704dad
class BaseOneHotEncodingFeaturizer(ParallelBaseFeaturizer): <NEW_LINE> <INDENT> ALPHABET = None <NEW_LINE> def __init__(self, dictionary: dict = None, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> if dictionary is None: <NEW_LINE> <INDENT> dictionary = {c: i for i, c in enumerate(self.ALPHABET)} <NEW_LINE> <DEDENT> self.dictionary = dictionary <NEW_LINE> if not self.dictionary: <NEW_LINE> <INDENT> raise ValueError("This featurizer requires a populated dictionary!") <NEW_LINE> <DEDENT> <DEDENT> def _featurize_one( self, system: Union[LigandSystem, ProteinLigandComplex] ) -> Union[np.ndarray, None]: <NEW_LINE> <INDENT> sequence = self._retrieve_sequence(system) <NEW_LINE> if sequence == "": <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.one_hot_encode(sequence, self.dictionary) <NEW_LINE> <DEDENT> def _retrieve_sequence(self, system: System): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def one_hot_encode(sequence: Iterable, dictionary: dict | Sequence) -> np.ndarray: <NEW_LINE> <INDENT> if not isinstance(dictionary, dict): <NEW_LINE> <INDENT> dictionary = {value: index for (index, value) in enumerate(dictionary)} <NEW_LINE> <DEDENT> ohe_matrix = np.zeros((len(dictionary), len(sequence))) <NEW_LINE> for i, character in enumerate(sequence): <NEW_LINE> <INDENT> ohe_matrix[dictionary[character], i] = 1 <NEW_LINE> <DEDENT> return ohe_matrix
Base class for Featurizers concerning one hot encoding.
62598fbaa05bb46b3848a9f6
class Device(object): <NEW_LINE> <INDENT> config = EnlightnsConfig() <NEW_LINE> @classmethod <NEW_LINE> def interfaces_only(self): <NEW_LINE> <INDENT> local_interfaces = ni.interfaces() <NEW_LINE> return local_interfaces <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def interfaces(self): <NEW_LINE> <INDENT> local_interfaces = ni.interfaces() <NEW_LINE> inet_and_ip = {} <NEW_LINE> for inet in local_interfaces: <NEW_LINE> <INDENT> inet_and_ip[inet] = {} <NEW_LINE> try: <NEW_LINE> <INDENT> ipv4 = ni.ifaddresses(inet)[ni.AF_INET][0]['addr'] <NEW_LINE> inet_and_ip[inet]['ipv4'] = ipv4 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> inet_and_ip[inet]['ipv4'] = '' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ipv6 = ni.ifaddresses(inet)[ni.AF_INET6][0]['addr'] <NEW_LINE> inet_and_ip[inet]['ipv6'] = ipv6 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> inet_and_ip[inet]['ipv6'] = '' <NEW_LINE> <DEDENT> <DEDENT> return inet_and_ip <NEW_LINE> <DEDENT> def get_ip(self, interface): <NEW_LINE> <INDENT> if self.config.ipv6 and self.config.ipv6 == 'on': <NEW_LINE> <INDENT> inet = ni.AF_INET6 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inet = ni.AF_INET <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> lan_ip = ni.ifaddresses(interface)[inet][0]['addr'].strip() <NEW_LINE> lan_ip = lan_ip.split('%')[0] <NEW_LINE> IP(lan_ip) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> lan_ip = False <NEW_LINE> <DEDENT> if not lan_ip: <NEW_LINE> <INDENT> gws_ip, inet = ni.gateways()['default'][ni.AF_INET] <NEW_LINE> try: <NEW_LINE> <INDENT> if self.config.ipv6 == 'off': <NEW_LINE> <INDENT> lan_ip = ni.ifaddresses(inet)[ni.AF_INET][0]['addr'] <NEW_LINE> IP(lan_ip) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lan_ip = ni.ifaddresses(inet)[ni.AF_INET6][0]['addr'] <NEW_LINE> IP(lan_ip) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> lan_ip = False <NEW_LINE> <DEDENT> <DEDENT> return lan_ip
Represents the device where the CLI is executed.
62598fba91f36d47f2230f70
class User(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(20), nullable=False) <NEW_LINE> email = db.Column(db.String(20), unique=True, nullable=False) <NEW_LINE> idade = db.Column(db.Integer, default=0) <NEW_LINE> def json(self): <NEW_LINE> <INDENT> user_json = {'id': self.id, 'name': self.name, 'email': self.email, 'idade': self.idade} <NEW_LINE> return user_json
Classe que representa uma tabela no banco de dados tem que herdar de db.Model pro SQLAlquemy reconhecer.
62598fbaf548e778e596b732
class Solution: <NEW_LINE> <INDENT> def bfs(self, node, tmp): <NEW_LINE> <INDENT> queue = collections.deque() <NEW_LINE> queue.append(node) <NEW_LINE> self.v[node.label] = True <NEW_LINE> while queue: <NEW_LINE> <INDENT> size = len(queue) <NEW_LINE> for i in range(0, size): <NEW_LINE> <INDENT> currnode = queue.popleft() <NEW_LINE> tmp.append(currnode.label) <NEW_LINE> for neighbor in currnode.neighbors: <NEW_LINE> <INDENT> if not self.v[neighbor.label]: <NEW_LINE> <INDENT> queue.append(neighbor) <NEW_LINE> self.v[neighbor.label] = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def connectedSet(self, nodes): <NEW_LINE> <INDENT> result = [] <NEW_LINE> self.v = {} <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> self.v[node.label] = False <NEW_LINE> <DEDENT> for node in nodes: <NEW_LINE> <INDENT> if not self.v[node.label]: <NEW_LINE> <INDENT> tmp = [] <NEW_LINE> self.bfs(node, tmp) <NEW_LINE> result.append(sorted(tmp)) <NEW_LINE> <DEDENT> <DEDENT> return result
@param: nodes: a array of Undirected graph node @return: a connected set of a Undirected graph
62598fba23849d37ff85123f
class IOHandler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> _lib.JupyROOTExecutorHandler_Ctor() <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> _lib.JupyROOTExecutorHandler_Dtor() <NEW_LINE> <DEDENT> def Clear(self): <NEW_LINE> <INDENT> _lib.JupyROOTExecutorHandler_Clear() <NEW_LINE> <DEDENT> def Poll(self): <NEW_LINE> <INDENT> _lib.JupyROOTExecutorHandler_Poll() <NEW_LINE> <DEDENT> def InitCapture(self): <NEW_LINE> <INDENT> _lib.JupyROOTExecutorHandler_InitCapture() <NEW_LINE> <DEDENT> def EndCapture(self): <NEW_LINE> <INDENT> _lib.JupyROOTExecutorHandler_EndCapture() <NEW_LINE> <DEDENT> def GetStdout(self): <NEW_LINE> <INDENT> return _lib.JupyROOTExecutorHandler_GetStdout() <NEW_LINE> <DEDENT> def GetStderr(self): <NEW_LINE> <INDENT> return _lib.JupyROOTExecutorHandler_GetStderr() <NEW_LINE> <DEDENT> def GetStreamsDicts(self): <NEW_LINE> <INDENT> out = self.GetStdout() <NEW_LINE> err = self.GetStderr() <NEW_LINE> outDict = {'name': 'stdout', 'text': out} if out != "" else None <NEW_LINE> errDict = {'name': 'stderr', 'text': err} if err != "" else None <NEW_LINE> return outDict,errDict
Class used to capture output from C/C++ libraries. >>> import sys >>> h = IOHandler() >>> h.GetStdout() '' >>> h.GetStderr() '' >>> h.GetStreamsDicts() (None, None) >>> del h
62598fba4527f215b58ea061
class AjaxDeleteImgBgPanelFront(View): <NEW_LINE> <INDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> map_id = request.POST.get('mapID') <NEW_LINE> ymap = Map.objects.get(pk=map_id) <NEW_LINE> general_settings = ymap.general_settings <NEW_LINE> general_settings.img_bg_panel_front = None <NEW_LINE> general_settings.save() <NEW_LINE> response_data = {'successfully': True} <NEW_LINE> return JsonResponse(response_data) <NEW_LINE> <DEDENT> @ajax_login_required_and_staff <NEW_LINE> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(AjaxDeleteImgBgPanelFront, self).dispatch(request, *args, **kwargs)
Ajax - Delete the background image for the panel.
62598fba099cdd3c636754a8
class Society(models.Model): <NEW_LINE> <INDENT> def __str__(self):return self.name <NEW_LINE> name=models.CharField(max_length=50)
Society in college
62598fba5fdd1c0f98e5e11d
class Dealer(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.suits = SUITS <NEW_LINE> self.card_values = VALUES <NEW_LINE> self.cards = [Card(x, y) for x in self.suits for y in self.card_values] <NEW_LINE> self.counter = 0 <NEW_LINE> self.shuffle() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> if self.counter >= 52: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.counter += 1 <NEW_LINE> return self.cards[self.counter - 1] <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'deck with %i cards left' % (52 - self.counter) <NEW_LINE> <DEDENT> def shuffle(self) -> None: <NEW_LINE> <INDENT> self.counter = 0 <NEW_LINE> random.shuffle(self.cards) <NEW_LINE> <DEDENT> def deal_players(self, players: int) -> Dict[int, List[Card]]: <NEW_LINE> <INDENT> cards_dealt = [next(self) for x in range(players * 2)] <NEW_LINE> return {x: [cards_dealt[x], cards_dealt[x + players]] for x in range(players)} <NEW_LINE> <DEDENT> def deal_common(self, num_cards: int) -> List[Card]: <NEW_LINE> <INDENT> cards_dealt = [next(self) for x in range(num_cards + 1)] <NEW_LINE> return cards_dealt[1:]
deals with the mechanics of how the cards are dealt
62598fba44b2445a339b6a3b
class Feature(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey(User.id)) <NEW_LINE> client_id = db.Column(db.Integer, db.ForeignKey(Client.id)) <NEW_LINE> product_id = db.Column(db.Integer, db.ForeignKey(Product.id)) <NEW_LINE> created = db.Column(db.DateTime, default=datetime.now) <NEW_LINE> title = db.Column(db.String(50)) <NEW_LINE> description = db.Column(db.String(500)) <NEW_LINE> priority = db.Column(db.SmallInteger) <NEW_LINE> target_date = db.Column(db.Date) <NEW_LINE> ticket_url = db.Column(db.String(2000)) <NEW_LINE> user = db.relationship(User) <NEW_LINE> client = db.relationship(Client) <NEW_LINE> product_area = db.relationship(Product)
Feature table, stores each individual feature request.
62598fba656771135c4897fa
class Neuron: <NEW_LINE> <INDENT> def __init__(self, weights): <NEW_LINE> <INDENT> self.weights = list(weights) <NEW_LINE> self.value = 0 <NEW_LINE> <DEDENT> def calculate(self, inputs, activation_function, bias): <NEW_LINE> <INDENT> if len(inputs) != len(self.weights): <NEW_LINE> <INDENT> raise ValueError('Different number of inputs and weights') <NEW_LINE> <DEDENT> neuron_base_value = 0 <NEW_LINE> for i, value in enumerate(inputs): <NEW_LINE> <INDENT> neuron_base_value += value * self.weights[i] <NEW_LINE> <DEDENT> self.value = activation_function(neuron_base_value + bias) <NEW_LINE> <DEDENT> def get_weights(self): <NEW_LINE> <INDENT> return self.weights <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def update_weights(self, corrections): <NEW_LINE> <INDENT> for i, value in enumerate(corrections): <NEW_LINE> <INDENT> self.weights[i] += value
Basic structural unit of networks
62598fbad486a94d0ba2c15b
class SubStatsFormatter(LatexFormatter): <NEW_LINE> <INDENT> template_path = templates_path / 'subplot-stats-template.tex' <NEW_LINE> template = template_path.read_text() <NEW_LINE> headers = False <NEW_LINE> title = False <NEW_LINE> def format(self, lot): <NEW_LINE> <INDENT> table = self._build_table(lot) <NEW_LINE> return self._get_latex(table) <NEW_LINE> <DEDENT> def _build_table(self, lot): <NEW_LINE> <INDENT> headers = ['NOME', 'AREA PROJECAO', 'AREA SUBLOTE', 'TAXA OCUPACAO', 'COEF.APROVEITAMENTO', 'AREA PERMEAVEL', 'TAXA PERMEABILIDADE'] <NEW_LINE> body = [self._gen_row(sub) for sub in lot.lands + [lot]] <NEW_LINE> body[-1][3] = '-' <NEW_LINE> body[-1][4] = '-' <NEW_LINE> body[-1][6] = '-' <NEW_LINE> return body <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _gen_row(s): <NEW_LINE> <INDENT> row = [s.name.upper()] <NEW_LINE> row.append(fmt_area(s.super_building.area_proj)) <NEW_LINE> row.append(fmt_area(s.area)) <NEW_LINE> row.append(fmt_perc(s.taxa_ocp)) <NEW_LINE> row.append(fmt_float(s.coef_aprov)) <NEW_LINE> row.append(fmt_area(s.area_perm)) <NEW_LINE> row.append(fmt_perc(s.taxa_perm)) <NEW_LINE> return row
Operate on lot to produce the Suplot stats text for the Subplot stats table
62598fba7cff6e4e811b5bae
class TabsExtraFilePathCommand(sublime_plugin.WindowCommand): <NEW_LINE> <INDENT> def run(self, group=-1, index=-1, path_type='path'): <NEW_LINE> <INDENT> if group >= 0 and index >= 0: <NEW_LINE> <INDENT> view = get_group_view(self.window, group, index) <NEW_LINE> if view is not None: <NEW_LINE> <INDENT> self.window.focus_view(view) <NEW_LINE> view.run_command('copy_path') <NEW_LINE> pth = sublime.get_clipboard() <NEW_LINE> if path_type == 'name': <NEW_LINE> <INDENT> pth = os.path.basename(pth) <NEW_LINE> <DEDENT> if view.name(): <NEW_LINE> <INDENT> pth = view.name() <NEW_LINE> <DEDENT> elif path_type == 'path_uri': <NEW_LINE> <INDENT> pth = urljoin('file:', pathname2url(pth)) <NEW_LINE> <DEDENT> sublime.set_clipboard(pth) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def is_enabled(self, group=-1, index=-1, path_type='path'): <NEW_LINE> <INDENT> enabled = False <NEW_LINE> if group >= 0 and index >= 0: <NEW_LINE> <INDENT> view = get_group_view(self.window, group, index) <NEW_LINE> if view is not None: <NEW_LINE> <INDENT> enabled = view.file_name() is not None or view.name() is not None <NEW_LINE> <DEDENT> <DEDENT> return enabled
Get file paths.
62598fba3617ad0b5ee062d4
class AuthenticationError(_error.Error): <NEW_LINE> <INDENT> code = 13001 <NEW_LINE> description = "身份验证错误"
身份验证错误
62598fba55399d3f056266a1
class CorrelationReducer(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self, thresh=.8, method='pearson'): <NEW_LINE> <INDENT> self.thresh = thresh <NEW_LINE> self.method = method <NEW_LINE> <DEDENT> def fit(self, X, y=None): <NEW_LINE> <INDENT> check_is_dataframe(X) <NEW_LINE> self.correlated_cols_ = self._reduce_corr(X, self.thresh, self.method) <NEW_LINE> return self <NEW_LINE> <DEDENT> def transform(self, X): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> getattr(self, 'correlated_cols_') <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise RuntimeError('Could not find the attribute.\n' 'Fitting is necessary before you do ' 'the transformation.') <NEW_LINE> <DEDENT> check_is_dataframe(X) <NEW_LINE> X_new = X.drop(self.correlated_cols_, axis=1) <NEW_LINE> return X_new <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _reduce_corr(X, thresh, method): <NEW_LINE> <INDENT> df = X.corr() <NEW_LINE> arr_one = np.ones(shape=df.shape, dtype=bool) <NEW_LINE> L_arr_one = np.tril(arr_one) <NEW_LINE> df.mask(L_arr_one, other=0., inplace=True) <NEW_LINE> corr_cols = (df.abs() >= thresh).any() <NEW_LINE> cols_out = corr_cols[corr_cols].index.tolist() <NEW_LINE> return cols_out
Removes correlated columns exceeding the thresh value. Parameters ---------- method: string, optional (default='pearson') Compute pairwise correlation of columns, excluding NA/null values (based on pandas.DataFrame.corr). - `pearson`: Standard correlation coefficient. - `kendall`: Kendall Tau correlation coefficient. - `spearman`: Spearman rank correlation. thresh: float, optional (default=.8) Threshold value after which further rejection of variables is discontinued. Attributes ---------- correlated_cols_: list List of correlated features from a given dataset that exceeded thresh.
62598fbbf548e778e596b733
class PyIdc_cvt_int64__(pyidc_cvt_helper__): <NEW_LINE> <INDENT> def __init__(self, v): <NEW_LINE> <INDENT> super(self.__class__, self).__init__(PY_ICID_INT64, v) <NEW_LINE> <DEDENT> __op_table = { 0: lambda a, b: a + b, 1: lambda a, b: a - b, 2: lambda a, b: a * b, 3: lambda a, b: a / b } <NEW_LINE> def __op(self, op_n, other, rev=False): <NEW_LINE> <INDENT> a = self.value <NEW_LINE> if type(other) == type(self): <NEW_LINE> <INDENT> b = other.value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> b = other <NEW_LINE> <DEDENT> if rev: <NEW_LINE> <INDENT> t = a <NEW_LINE> a = b <NEW_LINE> b = t <NEW_LINE> <DEDENT> return self.__class__(self.__op_table[op_n](a, b)) <NEW_LINE> <DEDENT> def __add__(self, other): return self.__op(0, other) <NEW_LINE> def __sub__(self, other): return self.__op(1, other) <NEW_LINE> def __mul__(self, other): return self.__op(2, other) <NEW_LINE> def __div__(self, other): return self.__op(3, other) <NEW_LINE> def __radd__(self, other): return self.__op(0, other, True) <NEW_LINE> def __rsub__(self, other): return self.__op(1, other, True) <NEW_LINE> def __rmul__(self, other): return self.__op(2, other, True) <NEW_LINE> def __rdiv__(self, other): return self.__op(3, other, True)
Helper class for explicitly representing VT_INT64 values
62598fbb3d592f4c4edbb04b
class SimpleAttentionWriter2d(SimpleAttentionCore2d): <NEW_LINE> <INDENT> def __init__(self, x_dim, con_dim, height, width, N, img_scale, att_scale, stay_within_boundary=False, **kwargs): <NEW_LINE> <INDENT> super(SimpleAttentionWriter2d, self).__init__( x_dim=x_dim, con_dim=con_dim, height=height, width=width, N=N, img_scale=img_scale, att_scale=att_scale, name="writer2d", stay_within_boundary=stay_within_boundary, **kwargs ) <NEW_LINE> return <NEW_LINE> <DEDENT> def get_dim(self, name): <NEW_LINE> <INDENT> return super(SimpleAttentionWriter2d, self).get_dim(name) <NEW_LINE> <DEDENT> @application(inputs=['windows', 'h_con'], outputs=['i12']) <NEW_LINE> def apply(self, windows, h_con): <NEW_LINE> <INDENT> i12 = self.write(windows, h_con) <NEW_LINE> return i12
This wraps SimpleAttentionCore2d -- for use as a "writer MLP". Parameters: x_dim: dimension of "vectorized" inputs con_dim: dimension of the controller providing attention params height: #rows after reshaping inputs to 2d width: #cols after reshaping inputs to 2d N: this will be an N x N reader -- N x N at two scales! img_scale: the scale of source image, which will have coordinates in the range [-img_scale...img_scale]. att_scale: initial portion of the image covered by the attention grid
62598fbb3d592f4c4edbb04c
class Normed(MathFunctionsMixin, ABC): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def __abs__(self): <NEW_LINE> <INDENT> return self.norm(None) <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def norm(self, which=None): <NEW_LINE> <INDENT> tname = type(self).__name__ <NEW_LINE> raise TypeError('%s object does not define a norm' % tname) <NEW_LINE> <DEDENT> def norm_sqr(self, which=None): <NEW_LINE> <INDENT> value = self.norm(which) <NEW_LINE> return value * value <NEW_LINE> <DEDENT> def normalize(self, which=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Z = self.norm(which) <NEW_LINE> return self / Z <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> raise ValueError('null element cannot be normalized') <NEW_LINE> <DEDENT> <DEDENT> @mutating <NEW_LINE> def inormalize(self, which=None): <NEW_LINE> <INDENT> if isinstance(self, Immutable): <NEW_LINE> <INDENT> raise TypeError('cannot normalize immutable object') <NEW_LINE> <DEDENT> self.__idiv__(self.norm(which)) <NEW_LINE> <DEDENT> def is_unity(self, norm=None, tol=1e-6): <NEW_LINE> <INDENT> value = self.norm(norm) <NEW_LINE> return abs(value - 1) < tol <NEW_LINE> <DEDENT> def is_null(self): <NEW_LINE> <INDENT> return self.norm() == 0.0 <NEW_LINE> <DEDENT> def __idiv__(self, param): <NEW_LINE> <INDENT> return NotImplementedError
Base class for all objects that have a notion of norm
62598fbb4c3428357761a449
class SignalMixin(object): <NEW_LINE> <INDENT> signal_name = "data_changed" <NEW_LINE> def __set__(self, instance, value): <NEW_LINE> <INDENT> signal = rec_getattr(instance, self.signal_name, None) <NEW_LINE> if signal is not None: <NEW_LINE> <INDENT> old = getattr(instance, self.label) <NEW_LINE> with signal.ignore(): <NEW_LINE> <INDENT> super(SignalMixin, self).__set__(instance, value) <NEW_LINE> <DEDENT> new = getattr(instance, self.label) <NEW_LINE> if isinstance(old, observables.ObsWrapperBase) or old != new: <NEW_LINE> <INDENT> signal.emit() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> super(SignalMixin, self).__set__(instance, value) <NEW_LINE> <DEDENT> <DEDENT> pass
A descriptor mixin that will invoke a signal on the instance owning this property when set. Expects two more keyword arguments to be passed to the property constructor: - signal_name: a dotted string describing where to get the signal object from the instance
62598fbbcc40096d6161a2a0
class NIONAT(NIO): <NEW_LINE> <INDENT> def __init__(self, identifier): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._identifier = identifier <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "NIO_NAT" <NEW_LINE> <DEDENT> def identifier(self): <NEW_LINE> <INDENT> return self._identifier
NAT NIO.
62598fbb01c39578d7f12f09
class INeighborhoodSkin(ISkinLayer, ICommonSkinLayer): <NEW_LINE> <INDENT> pass
Neighborhood skin
62598fbb56ac1b37e630237b
class ATMetricsTestCase(): <NEW_LINE> <INDENT> def test_flowup(self): <NEW_LINE> <INDENT> at = testAT1() <NEW_LINE> at.flowup() <NEW_LINE> correct_values_dict = { 'risk': 10, 'cost': 1, 'impact': 8 } <NEW_LINE> for k, v in correct_values_dict.items(): <NEW_LINE> <INDENT> assert v == at.rootnode.values[k] <NEW_LINE> <DEDENT> <DEDENT> def test_fusedAT(self): <NEW_LINE> <INDENT> at = testAT2() <NEW_LINE> at.flowup() <NEW_LINE> correct_values_dict = { 'risk': 10, 'cost': 1, 'impact': 8 } <NEW_LINE> for k, v in correct_values_dict.items(): <NEW_LINE> <INDENT> assert v == at.rootnode.values[k]
Test the calculation methods for the AttackTree class
62598fbb9c8ee8231304023b
class PrimaryKeyFetchException(Exception): <NEW_LINE> <INDENT> pass
Custom exception thrown when a query fails while trying to retrieve a collection of primary keys.
62598fbb66656f66f7d5a581
class Cue(Communication): <NEW_LINE> <INDENT> def __init__(self, id=1, location=( 0, 0), radius=20, object_to_communicate=None): <NEW_LINE> <INDENT> super().__init__(id, location, radius, object_to_communicate) <NEW_LINE> self.dropable = False <NEW_LINE> self.carryable = False <NEW_LINE> self.passable = True <NEW_LINE> self.deathable = False <NEW_LINE> self.moveable = False
Cue object with provides stationary information.
62598fbb0fa83653e46f5072
class TestSimple(MockServerTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestSimple, self).setUp() <NEW_LINE> self.request.access = MagicMock() <NEW_LINE> <DEDENT> def test_upload(self): <NEW_LINE> <INDENT> self.params = { ':action': 'file_upload', } <NEW_LINE> name, version, content = 'foo', 'bar', MagicMock() <NEW_LINE> content.filename = 'foo-1.2.tar.gz' <NEW_LINE> pkg = upload(self.request, name, version, content) <NEW_LINE> self.assertEquals(pkg, self.request.db.packages[content.filename]) <NEW_LINE> <DEDENT> def test_upload_bad_action(self): <NEW_LINE> <INDENT> self.params = { ':action': 'blah', } <NEW_LINE> name, version, content = 'foo', 'bar', 'baz' <NEW_LINE> response = upload(self.request, name, version, content) <NEW_LINE> self.assertEqual(response.status_code, 400) <NEW_LINE> <DEDENT> def test_upload_no_write_permission(self): <NEW_LINE> <INDENT> self.params = { ':action': 'file_upload', } <NEW_LINE> name, version, content = 'foo', 'bar', MagicMock() <NEW_LINE> content.filename = 'foo-1.2.tar.gz' <NEW_LINE> self.request.access.has_permission.return_value = False <NEW_LINE> response = upload(self.request, name, version, content) <NEW_LINE> self.assertEqual(response, self.request.forbid()) <NEW_LINE> <DEDENT> def test_upload_duplicate(self): <NEW_LINE> <INDENT> self.params = { ':action': 'file_upload', } <NEW_LINE> name, version, content = 'foo', '1.2', MagicMock() <NEW_LINE> content.filename = 'foo-1.2.tar.gz' <NEW_LINE> self.db.upload(content.filename, content, name) <NEW_LINE> response = upload(self.request, name, version, content) <NEW_LINE> self.assertEqual(response.status_code, 400) <NEW_LINE> <DEDENT> def test_list(self): <NEW_LINE> <INDENT> self.request.db = MagicMock() <NEW_LINE> self.request.db.distinct.return_value = ['a', 'b', 'c'] <NEW_LINE> self.request.access.has_permission.side_effect = lambda x, _: x == 'b' <NEW_LINE> result = simple(self.request) <NEW_LINE> self.assertEqual(result, {'pkgs': ['b']}) <NEW_LINE> <DEDENT> def test_list_versions(self): <NEW_LINE> <INDENT> self.request.registry.use_fallback = False <NEW_LINE> pkg = Package('mypkg', '1.1', 'mypkg-1.1.tar.gz', datetime.utcnow()) <NEW_LINE> self.request.db.upload(pkg.filename, None) <NEW_LINE> context = SimplePackageResource(self.request, 'mypkg') <NEW_LINE> self.request.app_url = MagicMock() <NEW_LINE> result = package_versions(context, self.request) <NEW_LINE> self.assertEqual(result, {'pkgs': {pkg.filename: self.request.app_url()}}) <NEW_LINE> <DEDENT> def test_list_versions_fallback_redirect(self): <NEW_LINE> <INDENT> self.request.registry.fallback = 'redirect' <NEW_LINE> fb = self.request.registry.fallback_url = 'http://pypi.com' <NEW_LINE> context = SimplePackageResource(self.request, 'mypkg') <NEW_LINE> result = package_versions(context, self.request) <NEW_LINE> url = fb + '/' + context.name + '/' <NEW_LINE> self.assertTrue(isinstance(result, HTTPFound)) <NEW_LINE> self.assertEqual(result.location, url) <NEW_LINE> <DEDENT> def test_list_versions_fallback_none(self): <NEW_LINE> <INDENT> self.request.registry.fallback = 'none' <NEW_LINE> context = SimplePackageResource(self.request, 'mypkg') <NEW_LINE> result = package_versions(context, self.request) <NEW_LINE> self.assertEqual(result.status_code, 404)
Unit tests for the /simple endpoints
62598fbb3346ee7daa33770f
class LengthHist(Graph): <NEW_LINE> <INDENT> short_name = 'length_hist' <NEW_LINE> sep = ('x', 'y') <NEW_LINE> y_grid = True <NEW_LINE> width = 10 <NEW_LINE> height = 6 <NEW_LINE> remove_frame = True <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.path = FilePath(self.parent.prefix_path + '_len_hist.pdf') <NEW_LINE> <DEDENT> def plot(self, bins=80, **kwargs): <NEW_LINE> <INDENT> import numpy <NEW_LINE> counts = list(self.parent.lengths) <NEW_LINE> if 'log' in kwargs.get('x_scale', ''): <NEW_LINE> <INDENT> start, stop = numpy.log10(1), numpy.log10(max(counts)) <NEW_LINE> bins = list(numpy.logspace(start=start, stop=stop, num=bins)) <NEW_LINE> bins.insert(0, 0) <NEW_LINE> <DEDENT> from matplotlib import pyplot <NEW_LINE> fig = pyplot.figure() <NEW_LINE> pyplot.hist(counts, bins=bins, color='gray') <NEW_LINE> axes = pyplot.gca() <NEW_LINE> title = 'Histogram of sequence lengths' <NEW_LINE> axes.set_title(title) <NEW_LINE> axes.set_xlabel('Length of sequence in nucleotides') <NEW_LINE> axes.set_ylabel('Number of sequences with this length') <NEW_LINE> axes.set_xlim(min(counts), axes.get_xlim()[1]) <NEW_LINE> self.save_plot(fig, axes, **kwargs) <NEW_LINE> pyplot.close(fig) <NEW_LINE> return self
The length distribution of the sequences with a histogram.
62598fbbec188e330fdf8a20
class Game: <NEW_LINE> <INDENT> def __init__(self, item): <NEW_LINE> <INDENT> self.item = item <NEW_LINE> self.gameId = item["GameId"] <NEW_LINE> self.hostId = item["HostId"] <NEW_LINE> self.opponent = item["OpponentId"] <NEW_LINE> self.statusDate = item["StatusDate"].split("_") <NEW_LINE> self.o = item["OUser"] <NEW_LINE> self.turn = item["Turn"] <NEW_LINE> <DEDENT> def getStatus(self): <NEW_LINE> <INDENT> status = self.statusDate[0] <NEW_LINE> if len(self.statusDate) > 2: <NEW_LINE> <INDENT> status += "_" + self.statusDate[1] <NEW_LINE> <DEDENT> return status <NEW_LINE> <DEDENT> status = property(getStatus) <NEW_LINE> def getDate(self): <NEW_LINE> <INDENT> index = 1 <NEW_LINE> if len(self.statusDate) > 2: <NEW_LINE> <INDENT> index = 2 <NEW_LINE> <DEDENT> date = datetime.strptime(self.statusDate[index],'%Y-%m-%d %H:%M:%S.%f') <NEW_LINE> return datetime.strftime(date, '%Y-%m-%d %H:%M:%S') <NEW_LINE> <DEDENT> date = property(getDate) <NEW_LINE> def __cmp__(self, otherGame): <NEW_LINE> <INDENT> if otherGame == None: <NEW_LINE> <INDENT> return cmp(self.statusDate[1], None) <NEW_LINE> <DEDENT> return cmp(self.statusDate[1], otherGame.statusDate[1]) <NEW_LINE> <DEDENT> def getOpposingPlayer(self, current_player): <NEW_LINE> <INDENT> if current_player == self.hostId: <NEW_LINE> <INDENT> return self.opponent <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.hostId <NEW_LINE> <DEDENT> <DEDENT> def getResult(self, current_player): <NEW_LINE> <INDENT> if self.item["Result"] == None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if self.item["Result"] == "Tie": <NEW_LINE> <INDENT> return "Tie" <NEW_LINE> <DEDENT> if self.item["Result"] == current_player: <NEW_LINE> <INDENT> return "Win" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Lose"
This Game class acts as a wrapper on top of an item in the Games table. Each of the fields in the table is of a String type. GameId is the primary key. HostId-StatusDate, Opponent-StatusDate are Global Secondary Indexes that are Hash-Range Keys. The other attributes are used to maintain game state.
62598fbb167d2b6e312b7104
class TableScale(PyoObject): <NEW_LINE> <INDENT> def __init__(self, table, outtable, mul=1, add=0): <NEW_LINE> <INDENT> pyoArgsAssert(self, "ttOO", table, outtable, mul, add) <NEW_LINE> PyoObject.__init__(self, mul, add) <NEW_LINE> self._table = table <NEW_LINE> self._outtable = outtable <NEW_LINE> table, outtable, mul, add, lmax = convertArgsToLists(table, outtable, mul, add) <NEW_LINE> self._base_objs = [TableScale_base(wrap(table,i), wrap(outtable,i), wrap(mul,i), wrap(add,i)) for i in range(lmax)] <NEW_LINE> self.play() <NEW_LINE> <DEDENT> def setTable(self, x): <NEW_LINE> <INDENT> pyoArgsAssert(self, "t", x) <NEW_LINE> self._table = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> [obj.setTable(wrap(x,i)) for i, obj in enumerate(self._base_objs)] <NEW_LINE> <DEDENT> def setOuttable(self, x): <NEW_LINE> <INDENT> pyoArgsAssert(self, "t", x) <NEW_LINE> self._outtable = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> [obj.setOuttable(wrap(x,i)) for i, obj in enumerate(self._base_objs)] <NEW_LINE> <DEDENT> def ctrl(self, map_list=None, title=None, wxnoserver=False): <NEW_LINE> <INDENT> self._map_list = [SLMapMul(self._mul), SLMap(0, 1, "lin", "add", self._add)] <NEW_LINE> PyoObject.ctrl(self, map_list, title, wxnoserver) <NEW_LINE> <DEDENT> @property <NEW_LINE> def table(self): <NEW_LINE> <INDENT> return self._table <NEW_LINE> <DEDENT> @table.setter <NEW_LINE> def table(self, x): self.setTable(x) <NEW_LINE> @property <NEW_LINE> def outtable(self): <NEW_LINE> <INDENT> return self._outtable <NEW_LINE> <DEDENT> @outtable.setter <NEW_LINE> def outtable(self, x): self.setOuttable(x)
Scales all the values contained in a PyoTableObject. TableScale scales the values of `table` argument according to `mul` and `add` arguments and writes the new values in `outtable`. :Parent: :py:class:`PyoObject` :Args: table: PyoTableObject Table containing the original values. outtable: PyoTableObject Table where to write the scaled values. >>> s = Server().boot() >>> s.start() >>> t = DataTable(size=12, init=midiToHz(range(48, 72, 2))) >>> t2 = DataTable(size=12) >>> m = Metro(.2).play() >>> c = Counter(m ,min=0, max=12) >>> f1 = TableIndex(t, c) >>> syn1 = SineLoop(f1, feedback=0.08, mul=0.3).out() >>> scl = TableScale(t, t2, mul=1.5) >>> f2 = TableIndex(t2, c) >>> syn2 = SineLoop(f2, feedback=0.08, mul=0.3).out(1)
62598fbbadb09d7d5dc0a70b
class IsServiceOwner(BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = request.user.user_client <NEW_LINE> if user == view.service.user_client: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> logging.info(f'We have a problem that Exception raise {error}')
This permission allow determine if the user is a client, if not permission is denied.
62598fbb7d43ff24874274cb
class Enum(Codec): <NEW_LINE> <INDENT> def __init__(self, values): <NEW_LINE> <INDENT> if not isinstance(values, collections.Iterable): <NEW_LINE> <INDENT> raise TypeError('enum values must be iterable, not ' + repr(values)) <NEW_LINE> <DEDENT> values = frozenset(values) <NEW_LINE> for v in values: <NEW_LINE> <INDENT> if not isinstance(v, string_type): <NEW_LINE> <INDENT> raise TypeError('enum values must be strings, not ' + repr(v)) <NEW_LINE> <DEDENT> <DEDENT> self.values = values <NEW_LINE> <DEDENT> def encode(self, value): <NEW_LINE> <INDENT> if not isinstance(value, string_type): <NEW_LINE> <INDENT> raise EncodeError('expected a string, not ' + repr(value)) <NEW_LINE> <DEDENT> elif value not in self.values: <NEW_LINE> <INDENT> raise EncodeError( '{0!r} is an invalid value; choose one of {1}'.format( value, ', '.join(repr(v) for v in self.values) ) ) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def decode(self, text): <NEW_LINE> <INDENT> if text not in self.values: <NEW_LINE> <INDENT> raise DecodeError('expected one of ' + ', '.join(repr(v) for v in self.values)) <NEW_LINE> <DEDENT> return text
Codec that accepts only predefined fixed types of values:: gender = Enum(['male', 'female']) Actually it doesn't any encoding nor decoding, but it simply *validates* all values from XML and Python both. Note that values have to consist of only strings. :param values: any iterable that yields all possible values :type values: :class:`collections.Iterable`
62598fbb1f5feb6acb162daf
class GeneralizedMeanPooling2d(nn.Module): <NEW_LINE> <INDENT> def __init__(self, p: float = 3, eps=1e-6, flatten=False): <NEW_LINE> <INDENT> super(GeneralizedMeanPooling2d, self).__init__() <NEW_LINE> self.p = nn.Parameter(torch.ones(1) * p) <NEW_LINE> self.eps = eps <NEW_LINE> self.flatten = flatten <NEW_LINE> <DEDENT> def forward(self, x: Tensor) -> Tensor: <NEW_LINE> <INDENT> x = F.adaptive_avg_pool2d(x.clamp_min(self.eps).pow(self.p), output_size=1).pow(1.0 / self.p) <NEW_LINE> if self.flatten: <NEW_LINE> <INDENT> x = x.view(x.size(0), x.size(1)) <NEW_LINE> <DEDENT> return x <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ( self.__class__.__name__ + "(" + "p=" + "{:.4f}".format(self.p.data.item()) + ", " + "eps=" + str(self.eps) + ")" )
https://arxiv.org/pdf/1902.05509v2.pdf https://amaarora.github.io/2020/08/30/gempool.html
62598fbba05bb46b3848a9fa
class Color(str): <NEW_LINE> <INDENT> def __init__(self, s): <NEW_LINE> <INDENT> self.r = None <NEW_LINE> self.g = None <NEW_LINE> self.b = None <NEW_LINE> if s is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.r = int(s[0:2], 16) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.r = 128 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.g = int(s[2:4], 16) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.g = 128 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.b = int(s[4:6], 16) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.b = 128 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.a = int(s[6:8], 16) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.a = 255 <NEW_LINE> <DEDENT> <DEDENT> def to_tuple(self): <NEW_LINE> <INDENT> result = (self.r / 255.0, self.g / 255.0, self.b / 255.0, self.a / 255.0) <NEW_LINE> return result <NEW_LINE> <DEDENT> @property <NEW_LINE> def html(self): <NEW_LINE> <INDENT> if self.r is not None and self.g is not None and self.b is not None: <NEW_LINE> <INDENT> return '#%02x%02x%02x' % (self.r, self.g, self.b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '#ff0000'
Simple color object: r, g, b, a. The object is in fact a string with class variables.
62598fbb283ffb24f3cf3a12
class BoltzmannDiscreteExplorerNode(DiscreteExplorerNode): <NEW_LINE> <INDENT> def __init__(self, n_actions, temperature=50., decay=0.999, dtype=None, numx_rng=None): <NEW_LINE> <INDENT> super(BoltzmannDiscreteExplorerNode, self).__init__(n_actions=n_actions, prob_vec=None, input_dim=None, dtype=dtype, numx_rng=numx_rng) <NEW_LINE> self.temperature = temperature <NEW_LINE> self.decay = float(decay) <NEW_LINE> self._input_dim = n_actions <NEW_LINE> self._output_dim = 1 <NEW_LINE> <DEDENT> def _train(self, x): <NEW_LINE> <INDENT> self.temperature *= self.decay ** x.shape[0] <NEW_LINE> <DEDENT> def _execute(self, x, prob_vec=None): <NEW_LINE> <INDENT> e = mdp.numx.e <NEW_LINE> if self.temperature < 0.01: <NEW_LINE> <INDENT> return self._refcast(mdp.numx.argmax(x, axis=1)[:, None]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _p = x / self.temperature <NEW_LINE> prob_vec = mdp.numx.power(e, _p) / mdp.numx.sum(mdp.numx.power(e, _p), axis=1, keepdims=True) <NEW_LINE> return super(BoltzmannDiscreteExplorerNode, self)._execute(self._refcast(x), prob_vec=prob_vec)
BoltzmannDiscreteExplorerNode is an online explorer node for reinforcement learning that balances exploration (random action) and exploitation (optimal action) modes based on a decaying temperature parameter. The train function of this node only updates the temperature parameter. The input to the node is a action/state value-vector for each action, the output is a softmax-function output weighted by the temperature parameter. For more information on epsilon greedy approach refer Sutton, Richard S., and Andrew G. Barto. Reinforcement learning: An introduction. Vol. 1. No. 1. Cambridge: MIT press, 1998.
62598fbb55399d3f056266a3
class SHA3_256_Hash(object): <NEW_LINE> <INDENT> digest_size = 32 <NEW_LINE> oid = "2.16.840.1.101.3.4.2.8" <NEW_LINE> def __init__(self, data, update_after_digest): <NEW_LINE> <INDENT> self._update_after_digest = update_after_digest <NEW_LINE> self._digest_done = False <NEW_LINE> state = VoidPointer() <NEW_LINE> result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(self.digest_size * 2), 0x06) <NEW_LINE> if result: <NEW_LINE> <INDENT> raise ValueError("Error %d while instantiating SHA-3/256" % result) <NEW_LINE> <DEDENT> self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) <NEW_LINE> if data: <NEW_LINE> <INDENT> self.update(data) <NEW_LINE> <DEDENT> <DEDENT> def update(self, data): <NEW_LINE> <INDENT> if self._digest_done and not self._update_after_digest: <NEW_LINE> <INDENT> raise TypeError("You can only call 'digest' or 'hexdigest' on this object") <NEW_LINE> <DEDENT> expect_byte_string(data) <NEW_LINE> result = _raw_keccak_lib.keccak_absorb(self._state.get(), data, c_size_t(len(data))) <NEW_LINE> if result: <NEW_LINE> <INDENT> raise ValueError("Error %d while updating SHA-3/256" % result) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def digest(self): <NEW_LINE> <INDENT> self._digest_done = True <NEW_LINE> bfr = create_string_buffer(self.digest_size) <NEW_LINE> result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size)) <NEW_LINE> if result: <NEW_LINE> <INDENT> raise ValueError("Error %d while instantiating SHA-3/256" % result) <NEW_LINE> <DEDENT> self._digest_value = get_raw_buffer(bfr) <NEW_LINE> return self._digest_value <NEW_LINE> <DEDENT> def hexdigest(self): <NEW_LINE> <INDENT> return "".join(["%02x" % bord(x) for x in self.digest()]) <NEW_LINE> <DEDENT> def new(self): <NEW_LINE> <INDENT> return type(self)(None, self._update_after_digest)
A SHA3-256 hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer
62598fbb3539df3088ecc43c
class BaseResource(Resource): <NEW_LINE> <INDENT> _is_test_mode = 0 <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> config_name = kwargs['config_name'] <NEW_LINE> if config_name == 'testing': <NEW_LINE> <INDENT> self._is_test_mode = 1
Base class for end points if we want to pass additional parameters when defining end points.
62598fbb67a9b606de546162
class V1Endpoints(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'kind': 'str', 'api_version': 'str', 'metadata': 'V1ObjectMeta', 'subsets': 'list[V1EndpointSubset]' } <NEW_LINE> self.attribute_map = { 'kind': 'kind', 'api_version': 'apiVersion', 'metadata': 'metadata', 'subsets': 'subsets' } <NEW_LINE> self._kind = None <NEW_LINE> self._api_version = None <NEW_LINE> self._metadata = None <NEW_LINE> self._subsets = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def kind(self): <NEW_LINE> <INDENT> return self._kind <NEW_LINE> <DEDENT> @kind.setter <NEW_LINE> def kind(self, kind): <NEW_LINE> <INDENT> self._kind = kind <NEW_LINE> <DEDENT> @property <NEW_LINE> def api_version(self): <NEW_LINE> <INDENT> return self._api_version <NEW_LINE> <DEDENT> @api_version.setter <NEW_LINE> def api_version(self, api_version): <NEW_LINE> <INDENT> self._api_version = api_version <NEW_LINE> <DEDENT> @property <NEW_LINE> def metadata(self): <NEW_LINE> <INDENT> return self._metadata <NEW_LINE> <DEDENT> @metadata.setter <NEW_LINE> def metadata(self, metadata): <NEW_LINE> <INDENT> self._metadata = metadata <NEW_LINE> <DEDENT> @property <NEW_LINE> def subsets(self): <NEW_LINE> <INDENT> return self._subsets <NEW_LINE> <DEDENT> @subsets.setter <NEW_LINE> def subsets(self, subsets): <NEW_LINE> <INDENT> self._subsets = subsets <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in 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> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str()
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fbbf548e778e596b736
class CYXXYPowGate(cirq.EigenGate, cirq.ThreeQubitGate): <NEW_LINE> <INDENT> @deprecation.deprecated( deprecated_in='v0.4.0', removed_in='v0.5.0', details=('Use cirq.ControlledGate and cirq.PhasedISwapPowGate, ' 'instead.')) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CYXXYPowGate, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> Optional[np.ndarray]: <NEW_LINE> <INDENT> return cirq.apply_unitary(cirq.ControlledGate( common_gates.YXXY**self.exponent), args, default=None) <NEW_LINE> <DEDENT> def _eigen_components(self): <NEW_LINE> <INDENT> minus_half_component = cirq.linalg.block_diag( np.diag([0, 0, 0, 0, 0]), np.array([[0.5, -0.5j], [0.5j, 0.5]]), np.diag([0])) <NEW_LINE> plus_half_component = cirq.linalg.block_diag( np.diag([0, 0, 0, 0, 0]), np.array([[0.5, 0.5j], [-0.5j, 0.5]]), np.diag([0])) <NEW_LINE> return [(0, np.diag([1, 1, 1, 1, 1, 0, 0, 1])), (-0.5, minus_half_component), (0.5, plus_half_component)] <NEW_LINE> <DEDENT> def _decompose_(self, qubits): <NEW_LINE> <INDENT> control, a, b = qubits <NEW_LINE> yield cirq.CNOT(a, b) <NEW_LINE> yield cirq.X(a)**0.5 <NEW_LINE> yield cirq.CCZ(control, a, b)**self.exponent <NEW_LINE> yield cirq.CZ(control, b)**(-self.exponent / 2) <NEW_LINE> yield cirq.X(a)**-0.5 <NEW_LINE> yield cirq.CNOT(a, b) <NEW_LINE> <DEDENT> def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs ) -> cirq.CircuitDiagramInfo: <NEW_LINE> <INDENT> return cirq.CircuitDiagramInfo(wire_symbols=('@', 'YXXY', '#2'), exponent=self._diagram_exponent(args)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.exponent == 1: <NEW_LINE> <INDENT> return 'CYXXY' <NEW_LINE> <DEDENT> return 'CYXXY**{!r}'.format(self.exponent)
Controlled YX - XY interaction.
62598fbba8370b77170f056f
class ThrowerAnt(Ant): <NEW_LINE> <INDENT> name = 'Thrower' <NEW_LINE> implemented = True <NEW_LINE> damage = 1 <NEW_LINE> food_cost = 4 <NEW_LINE> min_range = 0 <NEW_LINE> max_range = 10 <NEW_LINE> def nearest_bee(self, hive): <NEW_LINE> <INDENT> if last_element(self.place) not in zero_to_nine and self.place != 'Hive': <NEW_LINE> <INDENT> self.place = self.place.entrance.exit <NEW_LINE> <DEDENT> self_place_int = int(last_element(self.place)) <NEW_LINE> check_place = self.place <NEW_LINE> while check_place != 'Hive': <NEW_LINE> <INDENT> if last_element(check_place) not in zero_to_nine: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> check_place_int = int(last_element(check_place)) <NEW_LINE> difference = abs(check_place_int - self_place_int) <NEW_LINE> if difference >= self.min_range and difference <= self.max_range: <NEW_LINE> <INDENT> if random_or_none(check_place.bees) != None: <NEW_LINE> <INDENT> return random_or_none(check_place.bees) <NEW_LINE> <DEDENT> <DEDENT> check_place = check_place.entrance <NEW_LINE> <DEDENT> <DEDENT> def throw_at(self, target): <NEW_LINE> <INDENT> if target is not None: <NEW_LINE> <INDENT> target.reduce_armor(self.damage) <NEW_LINE> <DEDENT> <DEDENT> def action(self, colony): <NEW_LINE> <INDENT> self.throw_at(self.nearest_bee(colony.hive))
ThrowerAnt throws a leaf each turn at the nearest Bee in its range.
62598fbb4527f215b58ea065
class MetricStatus(_kuber_definitions.Definition): <NEW_LINE> <INDENT> def __init__( self, external: "ExternalMetricStatus" = None, object_: "ObjectMetricStatus" = None, pods: "PodsMetricStatus" = None, resource: "ResourceMetricStatus" = None, type_: str = None, ): <NEW_LINE> <INDENT> super(MetricStatus, self).__init__( api_version="autoscaling/v2beta1", kind="MetricStatus" ) <NEW_LINE> self._properties = { "external": external if external is not None else ExternalMetricStatus(), "object": object_ if object_ is not None else ObjectMetricStatus(), "pods": pods if pods is not None else PodsMetricStatus(), "resource": resource if resource is not None else ResourceMetricStatus(), "type": type_ if type_ is not None else "", } <NEW_LINE> self._types = { "external": (ExternalMetricStatus, None), "object": (ObjectMetricStatus, None), "pods": (PodsMetricStatus, None), "resource": (ResourceMetricStatus, None), "type": (str, None), } <NEW_LINE> <DEDENT> @property <NEW_LINE> def external(self) -> "ExternalMetricStatus": <NEW_LINE> <INDENT> return typing.cast( "ExternalMetricStatus", self._properties.get("external"), ) <NEW_LINE> <DEDENT> @external.setter <NEW_LINE> def external(self, value: typing.Union["ExternalMetricStatus", dict]): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> value = typing.cast( ExternalMetricStatus, ExternalMetricStatus().from_dict(value), ) <NEW_LINE> <DEDENT> self._properties["external"] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def object_(self) -> "ObjectMetricStatus": <NEW_LINE> <INDENT> return typing.cast( "ObjectMetricStatus", self._properties.get("object"), ) <NEW_LINE> <DEDENT> @object_.setter <NEW_LINE> def object_(self, value: typing.Union["ObjectMetricStatus", dict]): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> value = typing.cast( ObjectMetricStatus, ObjectMetricStatus().from_dict(value), ) <NEW_LINE> <DEDENT> self._properties["object"] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def pods(self) -> "PodsMetricStatus": <NEW_LINE> <INDENT> return typing.cast( "PodsMetricStatus", self._properties.get("pods"), ) <NEW_LINE> <DEDENT> @pods.setter <NEW_LINE> def pods(self, value: typing.Union["PodsMetricStatus", dict]): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> value = typing.cast( PodsMetricStatus, PodsMetricStatus().from_dict(value), ) <NEW_LINE> <DEDENT> self._properties["pods"] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def resource(self) -> "ResourceMetricStatus": <NEW_LINE> <INDENT> return typing.cast( "ResourceMetricStatus", self._properties.get("resource"), ) <NEW_LINE> <DEDENT> @resource.setter <NEW_LINE> def resource(self, value: typing.Union["ResourceMetricStatus", dict]): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> value = typing.cast( ResourceMetricStatus, ResourceMetricStatus().from_dict(value), ) <NEW_LINE> <DEDENT> self._properties["resource"] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def type_(self) -> str: <NEW_LINE> <INDENT> return typing.cast( str, self._properties.get("type"), ) <NEW_LINE> <DEDENT> @type_.setter <NEW_LINE> def type_(self, value: str): <NEW_LINE> <INDENT> self._properties["type"] = value <NEW_LINE> <DEDENT> def __enter__(self) -> "MetricStatus": <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> return False
MetricStatus describes the last-read state of a single metric.
62598fbb66673b3332c30561
class WorkflowEvent(models.Model): <NEW_LINE> <INDENT> _name = "crapo.workflow.event" <NEW_LINE> _sql_constraints = [ ( "unique_name_per_trigger_id", "unique(name, trigger_id)", "Trigger event can't have the same name in the same trigger", ) ] <NEW_LINE> name = fields.Char() <NEW_LINE> trigger_id = fields.Many2one("crapo.workflow.trigger") <NEW_LINE> model_id = fields.Many2one("ir.model", required=True) <NEW_LINE> context_event_ids = fields.One2many( "crapo.workflow.context.event", "event_id" ) <NEW_LINE> activity_id = fields.Many2one("crapo.workflow.activity") <NEW_LINE> record_id_context_key = fields.Char() <NEW_LINE> condition = fields.Char( help="""Conditions to be checked before set this event as done.""", ) <NEW_LINE> event_type = fields.Selection( [ ("transition", "transition"), ("record_create", "record_create"), ("record_write", "record_write"), ("record_unlink", "record_unlink"), ("activity_ended", "activity_ended"), ] ) <NEW_LINE> @api.model <NEW_LINE> def create(self, values): <NEW_LINE> <INDENT> rec = super(WorkflowEvent, self).create(values) <NEW_LINE> if not rec.name: <NEW_LINE> <INDENT> rec.name = "_".join((rec.event_type, str(rec.id))) <NEW_LINE> <DEDENT> return rec
Event definition
62598fbbff9c53063f51a7de
class retrieveRequestToken_args: <NEW_LINE> <INDENT> thrift_spec = ( None, None, (2, TType.I32, 'carrier', None, None, ), ) <NEW_LINE> def __init__(self, carrier=None,): <NEW_LINE> <INDENT> self.carrier = carrier <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 2: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.carrier = iprot.readI32() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('retrieveRequestToken_args') <NEW_LINE> if self.carrier is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('carrier', TType.I32, 2) <NEW_LINE> oprot.writeI32(self.carrier) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.carrier) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - carrier
62598fbb8a349b6b436863cd
class RTEllisonStop(RTPhraseMarker): <NEW_LINE> <INDENT> def __init__(self, src=u'*|', container=None): <NEW_LINE> <INDENT> super(RTEllisonStop, self).__init__(src, container) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<RTEllisonStop %r>' % self.src
>>> phrase = romanText.rtObjects.RTEllisonStop('*|') >>> phrase <RTEllisonStop '*|'>
62598fbb656771135c4897fe
class TestWebServer(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._test_app = TestApplication() <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> logging.info("Starting Test Application ...") <NEW_LINE> self._test_app.start()
Wrappered tornado.web.Application
62598fbb56ac1b37e630237e