code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class ChowGroup_degree_class(SageObject): <NEW_LINE> <INDENT> def __init__(self, A, d): <NEW_LINE> <INDENT> self._Chow_group = A <NEW_LINE> self._degree = d <NEW_LINE> toric_variety = A.scheme() <NEW_LINE> fan = toric_variety.fan() <NEW_LINE> gens = [] <NEW_LINE> for cone in fan(codim=d): <NEW_LINE> <INDENT> gen = A._cone_to_V(cone) <NEW_LINE> gens.append(gen) <NEW_LINE> <DEDENT> self._module = A.submodule(gens) <NEW_LINE> self._gens = tuple([ A.element_class(A, a.lift(), False) for a in self._module.gens() ]) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> invariants = self._module.invariants() <NEW_LINE> if len(invariants)==0: <NEW_LINE> <INDENT> return '0' <NEW_LINE> <DEDENT> free = [x for x in invariants if x==0] <NEW_LINE> tors = [x for x in invariants if x> 0] <NEW_LINE> if self._Chow_group.base_ring()==ZZ: <NEW_LINE> <INDENT> ring = 'Z' <NEW_LINE> <DEDENT> elif self._Chow_group.base_ring()==QQ: <NEW_LINE> <INDENT> ring = 'Q' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError('Base ring must be ZZ or QQ.') <NEW_LINE> <DEDENT> s = ['C' + str(x) for x in tors] <NEW_LINE> if len(free)==1: <NEW_LINE> <INDENT> s.append(ring) <NEW_LINE> <DEDENT> if len(free)>1: <NEW_LINE> <INDENT> s.append(ring + '^' + str(len(free))) <NEW_LINE> <DEDENT> return ' x '.join(s) <NEW_LINE> <DEDENT> def module(self): <NEW_LINE> <INDENT> return self._module <NEW_LINE> <DEDENT> def ngens(self): <NEW_LINE> <INDENT> return len(self._gens) <NEW_LINE> <DEDENT> def gen(self, i): <NEW_LINE> <INDENT> return self._gens[i] <NEW_LINE> <DEDENT> def gens(self): <NEW_LINE> <INDENT> return self._gens | A fixed-degree subgroup of the Chow group of a toric variety.
.. WARNING::
Use
:meth:`~sage.schemes.toric.chow_group.ChowGroup_class.degree`
to construct :class:`ChowGroup_degree_class` instances.
EXAMPLES::
sage: P2 = toric_varieties.P2()
sage: A = P2.Chow_group()
sage: A
Chow group of 2-d CPR-Fano toric variety covered by 3 affine patches
sage: A.degree()
(Z, Z, Z)
sage: A.degree(2)
Z
sage: type(_)
<class 'sage.schemes.toric.chow_group.ChowGroup_degree_class'> | 6259908e099cdd3c63676239 |
class SKLearnPerformanceDatasetWrapper(BasePerformanceDatasetWrapper): <NEW_LINE> <INDENT> dataset_map = { SKLearnDatasets.BOSTON: (datasets.load_boston, [FeatureType.CONTINUOUS] * 3 + [FeatureType.NOMINAL] + [FeatureType.CONTINUOUS] * 10), SKLearnDatasets.IRIS: (datasets.load_iris, [FeatureType.CONTINUOUS] * 4 + [FeatureType.NOMINAL]), SKLearnDatasets.DIABETES: (datasets.load_diabetes, [FeatureType.CONTINUOUS] * 11), SKLearnDatasets.DIGITS: (datasets.load_digits, [FeatureType.CONTINUOUS] * 64 + [FeatureType.NOMINAL]), SKLearnDatasets.WINE: (datasets.load_wine, [FeatureType.CONTINUOUS] * 13 + [FeatureType.NOMINAL]), SKLearnDatasets.CANCER: (datasets.load_breast_cancer, [FeatureType.CONTINUOUS] * 30 + [FeatureType.NOMINAL]) } <NEW_LINE> metadata_map = { SKLearnDatasets.BOSTON: (Tasks.REGRESSION, DataTypes.TABULAR, (506, 13)), SKLearnDatasets.IRIS: (Tasks.MULTICLASS, DataTypes.TABULAR, (150, 4)), SKLearnDatasets.DIABETES: (Tasks.REGRESSION, DataTypes.TABULAR, (442, 10)), SKLearnDatasets.DIGITS: (Tasks.MULTICLASS, DataTypes.IMAGE, (1797, 64)), SKLearnDatasets.WINE: (Tasks.MULTICLASS, DataTypes.TABULAR, (178, 13)), SKLearnDatasets.CANCER: (Tasks.BINARY, DataTypes.TABULAR, (569, 30)) } <NEW_LINE> load_function = None <NEW_LINE> feature_type = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> bunch = type(self).load_function() <NEW_LINE> super().__init__(bunch.data, bunch.target, nrows=self._size[0], data_t=self._feature_type) <NEW_LINE> if "feature_names" in bunch: <NEW_LINE> <INDENT> self._features = bunch.feature_names <NEW_LINE> <DEDENT> if "target_names" in bunch: <NEW_LINE> <INDENT> self._target_names = bunch.target_names <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def generate_dataset_class(cls, name, nrows=None): <NEW_LINE> <INDENT> load_function, feature_type = cls.dataset_map[name] <NEW_LINE> task, data_type, size = cls.metadata_map[name] <NEW_LINE> if nrows is not None: <NEW_LINE> <INDENT> size = (nrows, size[1]) <NEW_LINE> <DEDENT> class_name = name.title() + "PerformanceDatasetWrapper" <NEW_LINE> return type(class_name, (cls, ), {ClassVars.LOAD_FUNCTION: load_function, ClassVars.FEATURE_TYPE: feature_type, ClassVars.TASK: task, ClassVars.DATA_TYPE: data_type, ClassVars.SIZE: size}) | sklearn Datasets | 6259908e283ffb24f3cf551f |
class LongRunningActor(ThreadedGeneratorActor): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(LongRunningActor, self).__init__() <NEW_LINE> self.result = 0 <NEW_LINE> <DEDENT> def loop(self): <NEW_LINE> <INDENT> while self.processing: <NEW_LINE> <INDENT> self.result += 1 <NEW_LINE> if self.parent is not None: <NEW_LINE> <INDENT> self.parent.send(self.result) <NEW_LINE> <DEDENT> yield <NEW_LINE> <DEDENT> self.stop() | LongRunningActor
| 6259908e3617ad0b5ee07dd0 |
class ESubsamplingLayerCalculating(cnn.common.ELayerException): <NEW_LINE> <INDENT> def get_base_msg(self): <NEW_LINE> <INDENT> base_msg = 'Outputs of subsampling layer cannot be calculated!' <NEW_LINE> layer_str = self.get_layer_id_as_string() <NEW_LINE> if len(layer_str) > 0: <NEW_LINE> <INDENT> base_msg = 'Outputs of {0} subsampling layer cannot be ' 'calculated!'.format(layer_str) <NEW_LINE> <DEDENT> return base_msg | Ошибка генерируется в случае, если данные (входные карты), поданные на вход слоя
подвыборки, некорректны, т.е. не соответствуют по своей структуре этому слою подвыборки. | 6259908ebe7bc26dc9252c95 |
class Config(BaseConfig): <NEW_LINE> <INDENT> name = "Transformer" <NEW_LINE> embedding_dim = 100 <NEW_LINE> seq_length = 120 <NEW_LINE> num_classes = 10 <NEW_LINE> vocab_size = 8000 <NEW_LINE> num_units = 100 <NEW_LINE> ffn_dim = 2048 <NEW_LINE> num_heads = 4 <NEW_LINE> dropout_keep_prob = 0.8 <NEW_LINE> learning_rate = 1e-3 <NEW_LINE> batch_size = 64 <NEW_LINE> num_epochs = 10 <NEW_LINE> print_per_batch = 100 <NEW_LINE> save_per_batch = 10 <NEW_LINE> pre_training = None <NEW_LINE> clip = 6.0 <NEW_LINE> l2_reg_lambda = 0.01 <NEW_LINE> tensorboard_dir = os.path.join(base_dir, 'result/tensorboard/transformer/') <NEW_LINE> best_model_dir = os.path.join(base_dir, 'result/best_model/transformer/') | Transformer配置文件 | 6259908e283ffb24f3cf5520 |
class TestGeneratingServiceList(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.temp_dir = tempfile.TemporaryDirectory() <NEW_LINE> self.controlfile = join(self.temp_dir.name, 'Controlfile') <NEW_LINE> self.conf = { "services": { "foo": { "image": "busybox", "container": { "name": "foo", "hostname": "foo" } }, "bar": { "image": "busybox", "container": { "name": "bar", "hostname": "bar" } }, "named": { "services": ["bar", "baz"] }, "baz": { "image": "busybox", "required": False, "container": { "name": "baz" } } } } <NEW_LINE> with open(self.controlfile, 'w') as f: <NEW_LINE> <INDENT> f.write(json.dumps(self.conf)) <NEW_LINE> <DEDENT> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.temp_dir.cleanup() <NEW_LINE> <DEDENT> @unittest.skip('erroneous extra metaservice from an older time') <NEW_LINE> def test_generating_service_list(self): <NEW_LINE> <INDENT> ctrlfile = Controlfile(self.controlfile) <NEW_LINE> self.assertEqual( ctrlfile.get_list_of_services(), frozenset([ "foo", "bar", "baz", "required", "all", "optional"])) <NEW_LINE> <DEDENT> def test_optional_services(self): <NEW_LINE> <INDENT> ctrlfile = Controlfile(self.controlfile) <NEW_LINE> self.assertIn( 'baz', ctrlfile.services['all']) <NEW_LINE> self.assertIn( 'baz', ctrlfile.services['optional']) <NEW_LINE> self.assertNotIn( 'baz', ctrlfile.services['required']) | Make sure that the service list is generated correctly, when a
metaservice exists | 6259908ebf627c535bcb3153 |
class CompactTrieClusteringResult(Result): <NEW_LINE> <INDENT> def __init__(self, taskId, chromosome): <NEW_LINE> <INDENT> Result.__init__(self, taskId) <NEW_LINE> self.chromosome = chromosome | Class for giving clustering results and fitness | 6259908e4a966d76dd5f0b66 |
class InstanceTypeField(serializers.Field): <NEW_LINE> <INDENT> def to_representation(self, obj): <NEW_LINE> <INDENT> return obj.name.lower() | Serialize django content type field from a generic relation to string. | 6259908e5fc7496912d490ab |
class QArkClickableLabel( QtGui.QLabel ): <NEW_LINE> <INDENT> clicked = QtCore.pyqtSignal() <NEW_LINE> def __init__( self , parent=None ): <NEW_LINE> <INDENT> super( QArkClickableLabel, self).__init__( parent ) <NEW_LINE> <DEDENT> def mouseReleaseEvent(self, ev): <NEW_LINE> <INDENT> print( 'clicked' ) <NEW_LINE> self.clicked.emit() | A clickable label widget | 6259908ebf627c535bcb3155 |
class MultiMap(Dict): <NEW_LINE> <INDENT> def update(self, other=None, **kwargs): <NEW_LINE> <INDENT> if other is not None and hasattr(other, 'keys'): <NEW_LINE> <INDENT> for key in other: <NEW_LINE> <INDENT> self[key] = other[key] <NEW_LINE> <DEDENT> <DEDENT> elif other is not None and hasattr(other, '__iter__'): <NEW_LINE> <INDENT> for key, val in other: <NEW_LINE> <INDENT> self[key] = val <NEW_LINE> <DEDENT> <DEDENT> for key, val in kwargs.items(): <NEW_LINE> <INDENT> self[key] = val <NEW_LINE> <DEDENT> <DEDENT> def setdefault(self, k, d=None): <NEW_LINE> <INDENT> if k not in self: <NEW_LINE> <INDENT> self[k] = d <NEW_LINE> <DEDENT> return self[k] <NEW_LINE> <DEDENT> def _append_key(self, key, value): <NEW_LINE> <INDENT> if isinstance(self[key], list): <NEW_LINE> <INDENT> self[key].append(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(MultiMap, self).__setitem__(key, [self.get(key), value]) <NEW_LINE> <DEDENT> <DEDENT> def __iadd__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, dict): <NEW_LINE> <INDENT> msg = 'Can not concatenate Dict and {}'.format(type(other)) <NEW_LINE> raise TypeError(msg) <NEW_LINE> <DEDENT> for key, val in other.items(): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> self._append_key(key, val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self[key] = val <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> self._append_key(key, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(MultiMap, self).__setitem__(key, value) | A :class:`MultiMap` is a generalization of a :const:`dict` type in which
more than one value may be associated with and returned for a given key | 6259908eec188e330fdfa532 |
class EmailIdentity(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.IdentityName = None <NEW_LINE> self.IdentityType = None <NEW_LINE> self.SendingEnabled = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.IdentityName = params.get("IdentityName") <NEW_LINE> self.IdentityType = params.get("IdentityType") <NEW_LINE> self.SendingEnabled = params.get("SendingEnabled") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | 发信域名验证列表结构体
| 6259908ebe7bc26dc9252c97 |
class WidgetsListener: <NEW_LINE> <INDENT> def on_get(self, req, res): <NEW_LINE> <INDENT> name = req.get_param("name") <NEW_LINE> widget_type = req.get_param("type") <NEW_LINE> size = req.get_param("size") <NEW_LINE> limit = req.get_param_as_int("limit") or 10 <NEW_LINE> skip = req.get_param_as_int("skip") or 0 <NEW_LINE> regex = req.get_param_as_bool("regex") or True <NEW_LINE> query = [] <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> if regex: <NEW_LINE> <INDENT> query.append({"name": re.compile(name, re.IGNORECASE)}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query.append({"name": name}) <NEW_LINE> <DEDENT> <DEDENT> if widget_type is not None: <NEW_LINE> <INDENT> widget_type = widget_type.lower() <NEW_LINE> query.append({"type": widget_type}) <NEW_LINE> <DEDENT> if size is not None: <NEW_LINE> <INDENT> size = size.lower() <NEW_LINE> query.append({"size": size}) <NEW_LINE> <DEDENT> helper = DatabaseHelper() <NEW_LINE> helper.dbase = "tokosumatra" <NEW_LINE> helper.collection = "widget" <NEW_LINE> widgets = [] <NEW_LINE> try: <NEW_LINE> <INDENT> if len(query) == 0: <NEW_LINE> <INDENT> documents = helper.find({}).skip(skip).limit(limit) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> documents = helper.find({"$and": query}).skip(skip).limit(limit) <NEW_LINE> <DEDENT> widgets = [Widget(**document).to_dict(with_id=True) for document in documents] <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> helper.close() <NEW_LINE> <DEDENT> result = { "data": widgets, "status": {"code": 200, "message": "success"} } <NEW_LINE> if len(widgets) == limit: <NEW_LINE> <INDENT> result.update({"pagination": {"next": skip + limit}}) <NEW_LINE> <DEDENT> req.context["result"] = result <NEW_LINE> res.status = falcon.HTTP_200 <NEW_LINE> <DEDENT> def on_post(self, req, res): <NEW_LINE> <INDENT> helper = RequirementsHelper() <NEW_LINE> helper.check("doc", req.context) <NEW_LINE> data = copy.deepcopy(req.context["doc"]) <NEW_LINE> helper.check("type", data) <NEW_LINE> helper.check("value", data) <NEW_LINE> helper.check("name", data) <NEW_LINE> helper.check("size", data) <NEW_LINE> helper.check_type(data["type"], str) <NEW_LINE> helper.check_type(data["name"], str) <NEW_LINE> helper.check_type(data["size"], str) <NEW_LINE> widget = Widget( widget_type=data["type"], name=data["name"], size=data["size"], value=data["value"] ) <NEW_LINE> inserted_id = widget.save() <NEW_LINE> req.context["result"] = { "data": {"id": inserted_id}, "status": {"code": 200, "message": "success"} } <NEW_LINE> res.status = falcon.HTTP_200 <NEW_LINE> <DEDENT> def on_delete(self, req, res): <NEW_LINE> <INDENT> pass | A `widgets` listener | 6259908e8a349b6b43687ee3 |
class Session(object): <NEW_LINE> <INDENT> def __init__(self, url, uid, pwd, verify_ssl=False): <NEW_LINE> <INDENT> if 'https://' in url: <NEW_LINE> <INDENT> self.ipaddr = url[len('https://'):] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ipaddr = url[len('http://'):] <NEW_LINE> <DEDENT> self.uid = uid <NEW_LINE> self.pwd = pwd <NEW_LINE> self.api = url <NEW_LINE> self.session = None <NEW_LINE> self.verify_ssl = verify_ssl <NEW_LINE> self.token = None <NEW_LINE> self.login_thread = Login(self) <NEW_LINE> self.subscription_thread = Subscriber(self) <NEW_LINE> self.subscription_thread.daemon = True <NEW_LINE> self.subscription_thread.start() <NEW_LINE> <DEDENT> def _send_login(self): <NEW_LINE> <INDENT> login_url = self.api + '/api/aaaLogin.json' <NEW_LINE> name_pwd = {'aaaUser': {'attributes': {'name': self.uid, 'pwd': self.pwd}}} <NEW_LINE> jcred = json.dumps(name_pwd) <NEW_LINE> self.session = requests.Session() <NEW_LINE> ret = self.session.post(login_url, data=jcred, verify=self.verify_ssl) <NEW_LINE> ret_data = json.loads(ret.text)['imdata'][0] <NEW_LINE> timeout = ret_data['aaaLogin']['attributes']['refreshTimeoutSeconds'] <NEW_LINE> self.token = str(ret_data['aaaLogin']['attributes']['token']) <NEW_LINE> self.subscription_thread._open_web_socket('https://' in self.api) <NEW_LINE> timeout = int(timeout) <NEW_LINE> if (timeout - TIMEOUT_GRACE_SECONDS) > 0: <NEW_LINE> <INDENT> timeout = timeout - TIMEOUT_GRACE_SECONDS <NEW_LINE> <DEDENT> self.login_thread._login_timeout = timeout <NEW_LINE> return ret <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> logging.info('Initializing connection to the APIC') <NEW_LINE> resp = self._send_login() <NEW_LINE> self.login_thread.daemon = True <NEW_LINE> self.login_thread.start() <NEW_LINE> return resp <NEW_LINE> <DEDENT> def subscribe(self, url): <NEW_LINE> <INDENT> self.subscription_thread.subscribe(url) <NEW_LINE> <DEDENT> def has_events(self, url): <NEW_LINE> <INDENT> return self.subscription_thread.has_events(url) <NEW_LINE> <DEDENT> def get_event(self, url): <NEW_LINE> <INDENT> return self.subscription_thread.get_event(url) <NEW_LINE> <DEDENT> def unsubscribe(self, url): <NEW_LINE> <INDENT> self.subscription_thread.unsubscribe(url) <NEW_LINE> <DEDENT> def push_to_apic(self, url, data): <NEW_LINE> <INDENT> post_url = self.api + url <NEW_LINE> logging.debug('Posting url: %s data: %s', post_url, data) <NEW_LINE> resp = self.session.post(post_url, data=json.dumps(data)) <NEW_LINE> logging.debug('Response: %s %s', resp, resp.text) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def get(self, url): <NEW_LINE> <INDENT> get_url = self.api + url <NEW_LINE> logging.debug(get_url) <NEW_LINE> resp = self.session.get(get_url) <NEW_LINE> logging.debug(resp) <NEW_LINE> logging.debug(resp.text) <NEW_LINE> return resp | Session class
This class is responsible for all communication with the APIC. | 6259908ef9cc0f698b1c610d |
class PostProcess(nn.Module): <NEW_LINE> <INDENT> @torch.no_grad() <NEW_LINE> def forward(self, outputs, target_sizes): <NEW_LINE> <INDENT> out_logits, out_bbox = outputs["pred_logits"], outputs["pred_boxes"] <NEW_LINE> assert len(out_logits) == len(target_sizes) <NEW_LINE> assert target_sizes.shape[1] == 2 <NEW_LINE> prob = out_logits.sigmoid() <NEW_LINE> topk_values, topk_indexes = torch.topk( prob.view(out_logits.shape[0], -1), 100, dim=1 ) <NEW_LINE> scores = topk_values <NEW_LINE> topk_boxes = topk_indexes // out_logits.shape[2] <NEW_LINE> labels = topk_indexes % out_logits.shape[2] <NEW_LINE> boxes = box_ops.box_cxcywh_to_xyxy(out_bbox) <NEW_LINE> boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4)) <NEW_LINE> img_h, img_w = target_sizes.unbind(1) <NEW_LINE> scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1) <NEW_LINE> boxes = boxes * scale_fct[:, None, :] <NEW_LINE> results = [ {"scores": s, "labels": l, "boxes": b} for s, l, b in zip(scores, labels, boxes) ] <NEW_LINE> return results | This module converts the model's output into the format expected by the coco api | 6259908e4c3428357761bf3f |
class MnemonicsManeuverTable(SelfControlManeuverTable): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> trace.entry() <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> self.weeks_past = IntVar() <NEW_LINE> self.carefully_learned = IntVar() <NEW_LINE> self.pc_impact = IntVar() <NEW_LINE> trace.exit() <NEW_LINE> <DEDENT> def setup_maneuver_skill_frames(self, parent_frame): <NEW_LINE> <INDENT> def setup_weeks_past_frame(): <NEW_LINE> <INDENT> trace.entry() <NEW_LINE> frame_utils.setup_entry_frame(parent_frame, WEEKS_PAST_TEXT, self.weeks_past) <NEW_LINE> trace.exit() <NEW_LINE> <DEDENT> def setup_carefully_learned_frame(): <NEW_LINE> <INDENT> trace.entry() <NEW_LINE> frame_utils.setup_checkbox_frame( parent_frame, CAREFULLY_LEARNED_TEXT, self.carefully_learned) <NEW_LINE> trace.exit() <NEW_LINE> <DEDENT> def setup_pc_impact_frame(): <NEW_LINE> <INDENT> trace.entry() <NEW_LINE> frame_utils.setup_entry_frame(parent_frame, PC_IMPACT_TEXT, self.pc_impact) <NEW_LINE> trace.exit() <NEW_LINE> <DEDENT> trace.entry() <NEW_LINE> frame_utils.destroy_frame_objects(parent_frame) <NEW_LINE> setup_carefully_learned_frame() <NEW_LINE> setup_weeks_past_frame() <NEW_LINE> setup_pc_impact_frame() <NEW_LINE> self.weeks_past.set(0) <NEW_LINE> self.pc_impact.set(0) <NEW_LINE> trace.exit() <NEW_LINE> <DEDENT> def skill_type_bonus(self): <NEW_LINE> <INDENT> trace.entry() <NEW_LINE> bonus = 0 <NEW_LINE> weeks_past = self.weeks_past.get() <NEW_LINE> trace.detail("%d weeks in past, %d bonus" % (weeks_past, weeks_past * WEEKS_PAST_BONUS)) <NEW_LINE> bonus += weeks_past * WEEKS_PAST_BONUS <NEW_LINE> if self.carefully_learned.get() == 1: <NEW_LINE> <INDENT> trace.flow("Carefully learned: +30") <NEW_LINE> bonus += CAREFULLY_LEARNED_BONUS <NEW_LINE> <DEDENT> trace.detail("Impact on PC: %d" % self.pc_impact.get()) <NEW_LINE> bonus += self.pc_impact.get() | Mnemonics static maneuver table.
Methods:
setup_maneuver_skill_frames(self, parent_frame)
skill_type_bonus(self) | 6259908ead47b63b2c5a94d5 |
class CjdnsClientPublicKeySerializer(JsonObjectSerializer): <NEW_LINE> <INDENT> model = CjdnsClientPublicKey <NEW_LINE> properties = [ 'client_public_key', ] | Serialize a Person. | 6259908ebf627c535bcb3157 |
class Solver(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._constraints = [] <NEW_LINE> self._deps = {} <NEW_LINE> <DEDENT> def add(self, c): <NEW_LINE> <INDENT> self._constraints.append(c) <NEW_LINE> for d in c.variables: <NEW_LINE> <INDENT> if d in self._deps: <NEW_LINE> <INDENT> deps = self._deps[d] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> deps = self._deps[d] = set() <NEW_LINE> <DEDENT> deps.add(c) <NEW_LINE> <DEDENT> <DEDENT> def get(self, *variables): <NEW_LINE> <INDENT> return {c for v in variables for c in self._deps[v] if tuple(variables) == tuple(c.variables)} <NEW_LINE> <DEDENT> def solve(self): <NEW_LINE> <INDENT> unsolved = deque(self._constraints) <NEW_LINE> inque = set(self._constraints) <NEW_LINE> t1 = time.time() <NEW_LINE> self.count = 0 <NEW_LINE> kill = len(self._constraints) ** 2 <NEW_LINE> while unsolved: <NEW_LINE> <INDENT> c = unsolved.popleft() <NEW_LINE> inque.remove(c) <NEW_LINE> variables = c() <NEW_LINE> for v in variables: <NEW_LINE> <INDENT> deps = self._deps.get(v, set()) <NEW_LINE> to_solve = deps - inque <NEW_LINE> unsolved.extend(to_solve) <NEW_LINE> inque.update(to_solve) <NEW_LINE> <DEDENT> self.count += 1 <NEW_LINE> if self.count > kill: <NEW_LINE> <INDENT> if __debug__: <NEW_LINE> <INDENT> log.debug('Remaining constraints: {}'.format(inque)) <NEW_LINE> log.debug('Constraints status queue:\n{}' .format('\n'.join(' {}: {}'.format(c, c()) for c in inque))) <NEW_LINE> <DEDENT> raise SolverError('Could not find a solution;' ' unsolved={0} after {1} iterations' .format(len(unsolved), self.count)) <NEW_LINE> <DEDENT> <DEDENT> assert len(unsolved) == 0 <NEW_LINE> t2 = time.time() <NEW_LINE> k = len(self._constraints) <NEW_LINE> if __debug__: <NEW_LINE> <INDENT> fmt = 'k=constraints: {k}, steps: {c}, O(k log k)={O}, time: {t:.3f}' <NEW_LINE> log.debug(fmt.format(k=k, c=self.count, O=int(math.log(k, 2) * k), t=t2 -t1)) | Constraint solver.
:Attributes:
_constraints
List of constraints.
_dep
Dependencies between constraints. | 6259908ed8ef3951e32c8c9f |
class ResolutionError(RuntimeError): <NEW_LINE> <INDENT> pass | Raised when crawling resulted in unexpected results.
e.g. multiple titles, empty bodies, etc. | 6259908e97e22403b383cb7c |
class MeasureFiberProfileConfig(Config): <NEW_LINE> <INDENT> buildFiberTraces = ConfigurableField(target=BuildFiberTracesTask, doc="Build fiber traces") <NEW_LINE> rejIter = Field(dtype=int, default=3, doc="Number of rejection iterations for collapsing the profile") <NEW_LINE> rejThresh = Field(dtype=float, default=3.0, doc="Rejection threshold (sigma) for collapsing the profile") | Configuration for MeasureFiberProfileTask | 6259908e26068e7796d4e5c8 |
class LambdaQuoter(Quoter): <NEW_LINE> <INDENT> options = Quoter.options.add( func = None, prefix = Prohibited, suffix = Prohibited, pair = Prohibited, ) <NEW_LINE> def _interpret_args(self, args): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> self.options.addflat(args, ['func']) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, value, **kwargs): <NEW_LINE> <INDENT> opts = self.options.push(kwargs) <NEW_LINE> pstr, mstr = self._whitespace(opts) <NEW_LINE> prefix, value, suffix = opts.func(value) <NEW_LINE> parts = [mstr, prefix, pstr, stringify(value), pstr, suffix, mstr] <NEW_LINE> return self._output(parts, opts) | A Quoter that uses code to decide what quotes to use, based on the value. | 6259908ebf627c535bcb3159 |
class LazyWavelet(tfp.bijectors.Bijector): <NEW_LINE> <INDENT> def __init__(self, validate_args=False, name="lazy_wavelet"): <NEW_LINE> <INDENT> super().__init__( validate_args=validate_args, forward_min_event_ndims=1, name=name) <NEW_LINE> <DEDENT> def _forward(self, x): <NEW_LINE> <INDENT> x_evens = x[0::2] <NEW_LINE> x_odds = x[1::2] <NEW_LINE> return tf.stack([x_evens, x_odds]) <NEW_LINE> <DEDENT> def _inverse(self, y): <NEW_LINE> <INDENT> x_evens = y[0,:] <NEW_LINE> x_odds = y[1,:] <NEW_LINE> x = tf.reshape(tf.stack([x_evens, x_odds], axis=1), shape=[-1]) <NEW_LINE> return x <NEW_LINE> <DEDENT> def _inverse_log_det_jacobian(self, y): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def _forward_log_det_jacobian(self, x): <NEW_LINE> <INDENT> return 0 | This layer corresponds to the downsampling step of a single-step wavelet transform.
Input to _forward: 1D tensor of even length.
Output of _forward: Two stacked 1D tensors of the form [[even x componenents], [odd x components]]
See https://uk.mathworks.com/help/wavelet/ug/lifting-method-for-constructing-wavelets.html
for notation. | 6259908e50812a4eaa621a09 |
class Vector(ValuePacket): <NEW_LINE> <INDENT> _fields_ = ("scalar_count","value") <NEW_LINE> @classmethod <NEW_LINE> def from_stream(cls, stream, scalar_type, offset=None, decoder=None): <NEW_LINE> <INDENT> if offset is not None: <NEW_LINE> <INDENT> stream.seek(offset, SEEK_SET) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> offset = stream.tell() <NEW_LINE> <DEDENT> count = uint32_le.from_buffer_copy(stream.read(4)).value <NEW_LINE> seq = Sequence.from_stream( stream, scalar_type, count, offset + 4, decoder ) <NEW_LINE> return cls((seq.size + 4, count, seq.value)) | Represents the value from a VT_VECTOR packet.
.. attribute:: scalar_count
The number of elements in the vector.
.. attribute:: value
A list of elements in the vector. | 6259908e3346ee7daa3384a5 |
class MakeRecord(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.players = [] <NEW_LINE> self.game_history = [] <NEW_LINE> <DEDENT> def add_player(self, player_obj): <NEW_LINE> <INDENT> if player_obj.choose_pawn_delegate is None: <NEW_LINE> <INDENT> is_computer = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> is_computer = False <NEW_LINE> <DEDENT> self.players.append((player_obj.colour, player_obj.name, is_computer)) <NEW_LINE> <DEDENT> def add_game_turn(self, rolled_value, index): <NEW_LINE> <INDENT> self.game_history.append((rolled_value, index)) <NEW_LINE> <DEDENT> def save(self, file_obj): <NEW_LINE> <INDENT> pickle.dump([self.players, self.game_history], file_obj) | save game data
as a nested list which is
saved with pickle | 6259908e60cbc95b06365bab |
class Net: <NEW_LINE> <INDENT> def __init__(self, source: Cell = None, sinks: Cell = None, num=-1): <NEW_LINE> <INDENT> if sinks is None: <NEW_LINE> <INDENT> sinks = [] <NEW_LINE> <DEDENT> self.source = source <NEW_LINE> self.sinks = sinks <NEW_LINE> self.wireCells = [] <NEW_LINE> self.congestedCells = [] <NEW_LINE> self.num = num <NEW_LINE> self.sinksRemaining = len(self.sinks) <NEW_LINE> self.initRouteComplete = False <NEW_LINE> if self.num == -1: <NEW_LINE> <INDENT> print("ERROR: assign a net number to the newly-created net!") | A collection of cells | 6259908e3617ad0b5ee07dd8 |
class AjaxItemPasteHandler(BaseHandler): <NEW_LINE> <INDENT> @addslash <NEW_LINE> @session <NEW_LINE> @authenticated <NEW_LINE> def post(self, eid): <NEW_LINE> <INDENT> uid = self.SESSION['uid'] <NEW_LINE> vid = self.get_argument('vid', None) <NEW_LINE> e = Item() <NEW_LINE> r = e._api.copy(eid, **{'vid':vid, 'vtype':u'project', 'nick':self.SESSION['nick'], 'owner':uid}) <NEW_LINE> p = Project() <NEW_LINE> rp = p._api.get(vid) <NEW_LINE> l = rp[1]['works'] <NEW_LINE> if isinstance(l, list): <NEW_LINE> <INDENT> l.append(r[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> l = [r[1]] <NEW_LINE> <DEDENT> p._api.edit(vid, works=l, isOverWrite=True) <NEW_LINE> if r[0]:return self.write(json.dumps({'rep':'ok'})) | ajax方式粘贴作品
| 6259908e3617ad0b5ee07dda |
class EtatTelefrag(Etat): <NEW_LINE> <INDENT> def __init__(self, nom, debDans, duree, nomSort, lanceur=None, desc=""): <NEW_LINE> <INDENT> self.nomSort = nomSort <NEW_LINE> super().__init__(nom, debDans, duree, lanceur, desc) <NEW_LINE> <DEDENT> def __deepcopy__(self, memo): <NEW_LINE> <INDENT> return EtatTelefrag(self.nom, self.debuteDans, self.duree, self.nomSort, self.lanceur, self.desc) | @summary: Classe décrivant un état Téléfrag. | 6259908ef9cc0f698b1c6110 |
class TestStr(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.board = Board(2, 2) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.board = None <NEW_LINE> <DEDENT> def testStr(self): <NEW_LINE> <INDENT> result = self.board.__str__() <NEW_LINE> self.assertEqual(result, '(0 )(1 )\n|__||__|(0)\n|__||__|(1)') | Test behaviour of __str__ function. | 6259908ed8ef3951e32c8ca2 |
class D_Dt_Fast_numpy: <NEW_LINE> <INDENT> def __init__(self, tSym, dimSyms, dimAxes, eqD, t_dep_FD, state_dep_FD, bForceStateDimensions = False, dtype=np.complex128): <NEW_LINE> <INDENT> state_dep_syms = list(state_dep_FD.keys()) <NEW_LINE> t_dep_syms = list(t_dep_FD.keys()) <NEW_LINE> indep_syms = t_dep_syms + state_dep_syms <NEW_LINE> state_syms = list(eqD.keys()) <NEW_LINE> rhs = list(eqD.values()) <NEW_LINE> dim_shape = tuple([len(ax) for ax in dimAxes]) <NEW_LINE> state_shape = tuple([len(eqD), *dim_shape]) <NEW_LINE> input_syms = [tSym] + dimSyms + state_syms + t_dep_syms + state_dep_syms <NEW_LINE> self.eq = Munch(lhs=input_syms, rhs=rhs) <NEW_LINE> d_dt_lam = sm.lambdify(input_syms, rhs, modules="numpy") <NEW_LINE> if bForceStateDimensions: <NEW_LINE> <INDENT> d_dtF0 = d_dt_lam <NEW_LINE> d_dt_lam = lambda *args: [np.broadcast_to(out, dim_shape) for out in d_dtF0(*args)] <NEW_LINE> <DEDENT> self.d_dt_lam = d_dt_lam <NEW_LINE> self.d_dt_prealloc=np.zeros( state_shape, dtype= dtype) <NEW_LINE> self.dimAxes = [dAx.reshape(*(k * [1] + [dAx.size] + (len(dimAxes) - k - 1) * [1])) for k, dAx in enumerate(dimAxes)] <NEW_LINE> self.dtype = dtype <NEW_LINE> self.state_dep_f = list(state_dep_FD.values()) <NEW_LINE> self.t_dep_f = list(t_dep_FD.values()) <NEW_LINE> self.state_shape = state_shape <NEW_LINE> <DEDENT> def _d_dt(self, t, state, driving_vals, state_dep_vals): <NEW_LINE> <INDENT> return self.d_dt_lam(t, *self.dimAxes, *state, *driving_vals, *state_dep_vals) <NEW_LINE> <DEDENT> def _calc_driving_vals(self, t): <NEW_LINE> <INDENT> driving_vals = [f(t) for f in self.t_dep_f] <NEW_LINE> return driving_vals <NEW_LINE> <DEDENT> def _calc_state_dep_vals(self, t, state, driving_vals): <NEW_LINE> <INDENT> state_dep_vals = [f(t, self.dimAxes, state, driving_vals) for f in self.state_dep_f] <NEW_LINE> return state_dep_vals <NEW_LINE> <DEDENT> def __call__(self, t, cur_state_flat): <NEW_LINE> <INDENT> state = self._unflatten_state(cur_state_flat) <NEW_LINE> driving_vals = self._calc_driving_vals(t) <NEW_LINE> state_dep_vals = self._calc_state_dep_vals(t, state, driving_vals) <NEW_LINE> self.d_dt_prealloc[:] = self._d_dt(t, state, driving_vals, state_dep_vals) <NEW_LINE> return self._flatten_state(self.d_dt_prealloc) <NEW_LINE> <DEDENT> def _flatten_state(self, state): <NEW_LINE> <INDENT> return state.reshape(-1) <NEW_LINE> <DEDENT> def _unflatten_state(self, flat_state): <NEW_LINE> <INDENT> return flat_state.reshape(*self.state_shape) | attributes:
* dimAxes
* state_shape
* Npars
* flatten
* unflatten
* d_dt | 6259908e099cdd3c6367623f |
class GoldenRatioStrategy(DiscoveryStrategy): <NEW_LINE> <INDENT> def __init__(self, overlay, golden_ratio=9 / 16, target_peers=23): <NEW_LINE> <INDENT> super().__init__(overlay) <NEW_LINE> self.golden_ratio = golden_ratio <NEW_LINE> self.target_peers = target_peers <NEW_LINE> self.intro_sent = {} <NEW_LINE> assert target_peers > 0 <NEW_LINE> assert 0.0 <= golden_ratio <= 1.0 <NEW_LINE> <DEDENT> def take_step(self): <NEW_LINE> <INDENT> with self.walk_lock: <NEW_LINE> <INDENT> peers = self.overlay.get_peers() <NEW_LINE> for peer in list(self.intro_sent.keys()): <NEW_LINE> <INDENT> if peer not in peers: <NEW_LINE> <INDENT> self.intro_sent.pop(peer, None) <NEW_LINE> <DEDENT> <DEDENT> now = time.time() <NEW_LINE> for peer in peers: <NEW_LINE> <INDENT> if peer not in self.overlay.candidates and now > self.intro_sent.get(peer, 0) + 300: <NEW_LINE> <INDENT> self.overlay.send_introduction_request(peer) <NEW_LINE> self.intro_sent[peer] = now <NEW_LINE> <DEDENT> <DEDENT> peer_count = len(peers) <NEW_LINE> if peer_count > self.target_peers: <NEW_LINE> <INDENT> exit_peers = set(self.overlay.get_candidates(PEER_FLAG_EXIT_BT)) <NEW_LINE> exit_count = len(exit_peers) <NEW_LINE> ratio = 1.0 - exit_count / peer_count <NEW_LINE> if ratio < self.golden_ratio: <NEW_LINE> <INDENT> self.overlay.network.remove_peer(sample(exit_peers, 1)[0]) <NEW_LINE> <DEDENT> elif ratio > self.golden_ratio: <NEW_LINE> <INDENT> self.overlay.network.remove_peer(sample(set(self.overlay.get_peers()) - exit_peers, 1)[0]) | Strategy for removing peers once we have too many in the TunnelCommunity.
This strategy will remove a "normal" peer if the current ratio of "normal" peers to exit node peers is larger
than the set golden ratio.
This strategy will remove an exit peer if the current ratio of "normal" peers to exit node peers is smaller than
the set golden ratio. | 6259908e656771135c48ae76 |
class AnacondaDoc(sublime_plugin.TextCommand): <NEW_LINE> <INDENT> documentation = None <NEW_LINE> def run(self, edit): <NEW_LINE> <INDENT> if self.documentation is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> location = self.view.rowcol(self.view.sel()[0].begin()) <NEW_LINE> if self.view.substr(self.view.sel()[0].begin()) in ['(', ')']: <NEW_LINE> <INDENT> location = (location[0], location[1] - 1) <NEW_LINE> <DEDENT> data = prepare_send_data(location, 'doc', 'jedi') <NEW_LINE> if int(sublime.version()) >= 3070: <NEW_LINE> <INDENT> data['html'] = get_settings( self.view, 'enable_docstrings_tooltip', False) <NEW_LINE> <DEDENT> Worker().execute( Callback(on_success=self.prepare_data), **data ) <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> print(error) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if (get_settings(self.view, 'enable_docstrings_tooltip', False) and int(sublime.version()) >= 3070): <NEW_LINE> <INDENT> self.print_popup(edit) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.print_doc(edit) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def is_enabled(self): <NEW_LINE> <INDENT> return is_python(self.view) <NEW_LINE> <DEDENT> def prepare_data(self, data): <NEW_LINE> <INDENT> if data['success']: <NEW_LINE> <INDENT> self.documentation = data['doc'] <NEW_LINE> if self.documentation is None or self.documentation == '': <NEW_LINE> <INDENT> self._show_status() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sublime.active_window().run_command(self.name()) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._show_status() <NEW_LINE> <DEDENT> <DEDENT> def print_doc(self, edit): <NEW_LINE> <INDENT> doc_panel = self.view.window().create_output_panel( 'anaconda_documentation' ) <NEW_LINE> doc_panel.set_read_only(False) <NEW_LINE> region = sublime.Region(0, doc_panel.size()) <NEW_LINE> doc_panel.erase(edit, region) <NEW_LINE> doc_panel.insert(edit, 0, self.documentation) <NEW_LINE> self.documentation = None <NEW_LINE> doc_panel.set_read_only(True) <NEW_LINE> doc_panel.show(0) <NEW_LINE> self.view.window().run_command( 'show_panel', {'panel': 'output.anaconda_documentation'} ) <NEW_LINE> <DEDENT> def print_popup(self, edit): <NEW_LINE> <INDENT> dlines = self.documentation.splitlines() <NEW_LINE> name = dlines[0] <NEW_LINE> docstring = ''.join(dlines[1:]) <NEW_LINE> content = {'name': name, 'content': docstring} <NEW_LINE> self.documentation = None <NEW_LINE> css = get_settings(self.view, 'anaconda_tooltip_theme', 'dark') <NEW_LINE> Tooltip(css).show_tooltip( self.view, 'doc', content, partial(self.print_doc, edit)) <NEW_LINE> <DEDENT> def _show_status(self): <NEW_LINE> <INDENT> self.view.set_status( 'anaconda_doc', 'Anaconda: No documentation found' ) <NEW_LINE> sublime.set_timeout_async( lambda: self.view.erase_status('anaconda_doc'), 5000 ) | Jedi get documentation string for Sublime Text
| 6259908e283ffb24f3cf552b |
class PiopioUserManager(BaseUserManager): <NEW_LINE> <INDENT> def create(self, email, username, password, profile, **extra_fields): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError('Email address is required.') <NEW_LINE> <DEDENT> if not username: <NEW_LINE> <INDENT> raise ValueError('Username is required.') <NEW_LINE> <DEDENT> if not profile: <NEW_LINE> <INDENT> raise ValueError('Profile is required.') <NEW_LINE> <DEDENT> user = self.model( email=self.normalize_email(email), username=username, ) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> profile = models.Profile( first_name=profile.get('first_name'), last_name=profile.get('last_name'), user=user ) <NEW_LINE> profile.save() <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_superuser(self, email, username, password, **extra_fields): <NEW_LINE> <INDENT> extra_fields.setdefault('is_staff', True) <NEW_LINE> extra_fields.setdefault('is_superuser', True) <NEW_LINE> extra_fields.setdefault('is_active', True) <NEW_LINE> if extra_fields.get('is_staff') is not True: <NEW_LINE> <INDENT> raise ValueError(_('Superuser must have is_staff=True.')) <NEW_LINE> <DEDENT> if extra_fields.get('is_superuser') is not True: <NEW_LINE> <INDENT> raise ValueError(_('Superuser must have is_superuser=True.')) <NEW_LINE> <DEDENT> return self.create(email, username, password, **extra_fields) | Custom user model manager where email is the unique identifiers
for authentication instead of usernames. | 6259908eec188e330fdfa53a |
class PingChecker(threading.Thread): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.setDaemon(True) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> message = {'type': RequestTypes.PING} <NEW_LINE> error_manager = ErrorManager(__name__, 10) <NEW_LINE> while True: <NEW_LINE> <INDENT> confirm = send_message(message) <NEW_LINE> if not confirm: <NEW_LINE> <INDENT> inError = True <NEW_LINE> error_manager.warning("Error while sending ping to RPI", "RPIPing") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inError = False <NEW_LINE> error_manager.resolve("Ping sent successfully to RPI", "RPIPing", False) <NEW_LINE> <DEDENT> if not inError: <NEW_LINE> <INDENT> time.sleep(10) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time.sleep(1) | Continuously sends pings to the RPI. If the RPI cannot be reached
for some reasons, alert the user. The goal is to catch network problems
as soon as possible. | 6259908e55399d3f0562819f |
class triangle(): <NEW_LINE> <INDENT> def __init__(self,angle1,angle2,angle3): <NEW_LINE> <INDENT> self.angle_1 = angle1 <NEW_LINE> self.angle_2 = angle2 <NEW_LINE> self.angle_3 = angle3 <NEW_LINE> self.number_of_sides = 3 <NEW_LINE> <DEDENT> def check_angles(self): <NEW_LINE> <INDENT> print("no_of sides required:",self.number_of_sides) <NEW_LINE> if((self.angle_1+self.angle_2+self.angle_3) == 180): <NEW_LINE> <INDENT> print("True,Valid Triangle. angles entered are:",self.angle_1,self.angle_2,self.angle_3) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("False, invalid traingle.angles entered are:",self.angle_1,self.angle_2,self.angle_3) | The triangle class checks angles to verify it. | 6259908e8a349b6b43687eeb |
class AutoscalingPolicyQueueBasedScalingCloudPubSub(_messages.Message): <NEW_LINE> <INDENT> subscription = _messages.StringField(1) <NEW_LINE> topic = _messages.StringField(2) | Configuration parameters for scaling based on Cloud Pub/Sub subscription
queue.
Fields:
subscription: Cloud Pub/Sub subscription used for scaling. Provide the
partial URL (starting with projects/) or just the subscription name. The
subscription must be assigned to the topic specified in topicName and
must be in a pull configuration. The subscription must belong to the
same project as the Autoscaler.
topic: Cloud Pub/Sub topic used for scaling. Provide the partial URL or
partial URL (starting with projects/) or just the topic name. The topic
must belong to the same project as the Autoscaler resource. | 6259908e26068e7796d4e5ce |
class MAVLink_nav_filter_bias_message(MAVLink_message): <NEW_LINE> <INDENT> id = MAVLINK_MSG_ID_NAV_FILTER_BIAS <NEW_LINE> name = 'NAV_FILTER_BIAS' <NEW_LINE> fieldnames = ['usec', 'accel_0', 'accel_1', 'accel_2', 'gyro_0', 'gyro_1', 'gyro_2'] <NEW_LINE> ordered_fieldnames = [ 'usec', 'accel_0', 'accel_1', 'accel_2', 'gyro_0', 'gyro_1', 'gyro_2' ] <NEW_LINE> format = '>Qffffff' <NEW_LINE> native_format = bytearray('>Qffffff', 'ascii') <NEW_LINE> orders = [0, 1, 2, 3, 4, 5, 6] <NEW_LINE> lengths = [1, 1, 1, 1, 1, 1, 1] <NEW_LINE> array_lengths = [0, 0, 0, 0, 0, 0, 0] <NEW_LINE> crc_extra = 34 <NEW_LINE> def __init__(self, usec, accel_0, accel_1, accel_2, gyro_0, gyro_1, gyro_2): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLink_nav_filter_bias_message.id, MAVLink_nav_filter_bias_message.name) <NEW_LINE> self._fieldnames = MAVLink_nav_filter_bias_message.fieldnames <NEW_LINE> self.usec = usec <NEW_LINE> self.accel_0 = accel_0 <NEW_LINE> self.accel_1 = accel_1 <NEW_LINE> self.accel_2 = accel_2 <NEW_LINE> self.gyro_0 = gyro_0 <NEW_LINE> self.gyro_1 = gyro_1 <NEW_LINE> self.gyro_2 = gyro_2 <NEW_LINE> <DEDENT> def pack(self, mav): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 34, struct.pack('>Qffffff', self.usec, self.accel_0, self.accel_1, self.accel_2, self.gyro_0, self.gyro_1, self.gyro_2)) | Accelerometer and Gyro biases from the navigation filter | 6259908e5fc7496912d490b1 |
class Config(object): <NEW_LINE> <INDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return app.config.get(name) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return getattr(eve, name) | Helper class used trorough the code to access configuration settings.
If the main flaskapp object is not instantiated yet, returns the default
setting in the eve __init__.py module, otherwise returns the flaskapp
config value (which value might override the static defaults). | 6259908e5fdd1c0f98e5fc04 |
class TestLiuEtAl2006NSRC(unittest.TestCase): <NEW_LINE> <INDENT> pass | #TODO: implement test | 6259908e8a349b6b43687eed |
class BMUFParamServer(BaseParamServer): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(BMUFParamServer, self).__init__() <NEW_LINE> self._grad_momentum = None <NEW_LINE> <DEDENT> def update(self, local_params): <NEW_LINE> <INDENT> params = list() <NEW_LINE> for local in local_params: <NEW_LINE> <INDENT> params.append(encode(local)) <NEW_LINE> <DEDENT> average_params = np.mean(params, axis=0) <NEW_LINE> grads = average_params - encode(self.get_params()) <NEW_LINE> if self._grad_momentum is None: <NEW_LINE> <INDENT> updates = grads <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> updates = 0.5 * self._grad_momentum + 0.5 * grads <NEW_LINE> <DEDENT> self._grad_momentum = updates <NEW_LINE> params = updates + encode(self.get_params()) <NEW_LINE> self.set_params(params) | Block-wise Model Update Filtering ParamServer
see https://www.microsoft.com/en-us/research/wp-content/uploads/2016/08/0005880.pdf | 6259908e283ffb24f3cf552e |
class CompositionConfig(VegaLiteSchema): <NEW_LINE> <INDENT> _schema = {'$ref': '#/definitions/CompositionConfig'} <NEW_LINE> def __init__(self, columns=Undefined, spacing=Undefined, **kwds): <NEW_LINE> <INDENT> super(CompositionConfig, self).__init__(columns=columns, spacing=spacing, **kwds) | CompositionConfig schema wrapper
Mapping(required=[])
Attributes
----------
columns : float
The number of columns to include in the view composition layout.
**Default value** : ``undefined`` -- An infinite number of columns (a single row)
will be assumed. This is equivalent to ``hconcat`` (for ``concat`` ) and to using
the ``column`` channel (for ``facet`` and ``repeat`` ).
**Note** :
1) This property is only for:
* the general (wrappable) ``concat`` operator (not ``hconcat`` / ``vconcat`` )
* the ``facet`` and ``repeat`` operator with one field/repetition definition
(without row/column nesting)
2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat`` )
and to using the ``row`` channel (for ``facet`` and ``repeat`` ).
spacing : float
The default spacing in pixels between composed sub-views.
**Default value** : ``20`` | 6259908e7cff6e4e811b76d0 |
@pytest.mark.slow <NEW_LINE> @pytest.mark.contract <NEW_LINE> class TestBigmap: <NEW_LINE> <INDENT> def test_bigmap(self, client): <NEW_LINE> <INDENT> contract = path.join(MACROS_CONTRACT_PATH, 'big_map_mem.tz') <NEW_LINE> init_with_transfer( client, contract, '(Pair { Elt 1 Unit ; Elt 2 Unit ; Elt 3 Unit } Unit)', 100, 'bootstrap1') <NEW_LINE> client.transfer(1, 'bootstrap1', 'big_map_mem', ['-arg', '(Pair 0 False)', '--burn-cap', '10']) <NEW_LINE> bake(client) <NEW_LINE> assert_transfer_failwith( client, 0, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 0 True)', '--burn-cap', '10']) <NEW_LINE> client.transfer(1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 0 False)', '--burn-cap', '10']) <NEW_LINE> bake(client) <NEW_LINE> assert_transfer_failwith( client, 1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 0 True)', '--burn-cap', '10']) <NEW_LINE> client.transfer(1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 1 True)', '--burn-cap', '10']) <NEW_LINE> bake(client) <NEW_LINE> assert_transfer_failwith( client, 1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 1 False)', '--burn-cap', '10']) <NEW_LINE> client.transfer(1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 2 True)', '--burn-cap', '10']) <NEW_LINE> bake(client) <NEW_LINE> assert_transfer_failwith( client, 1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 2 False)', '--burn-cap', '10']) <NEW_LINE> client.transfer(1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 3 True)', '--burn-cap', '10']) <NEW_LINE> bake(client) <NEW_LINE> assert_transfer_failwith( client, 1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 3 False)', '--burn-cap', '10']) <NEW_LINE> client.transfer(1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 4 False)', '--burn-cap', '10']) <NEW_LINE> bake(client) <NEW_LINE> assert_transfer_failwith( client, 1, 'bootstrap1', 'big_map_mem', ['--arg', '(Pair 4 True)', '--burn-cap', '10']) | Tests on the big_map_mem contract. | 6259908ed8ef3951e32c8ca4 |
class CheckCollections(Application): <NEW_LINE> <INDENT> def __init__(self, paramdict = None): <NEW_LINE> <INDENT> self.collections = [] <NEW_LINE> super(CheckCollections, self).__init__( paramdict ) <NEW_LINE> if not self.version: <NEW_LINE> <INDENT> self.version = 'HEAD' <NEW_LINE> <DEDENT> self._modulename = "CheckCollections" <NEW_LINE> self.appname = 'lcio' <NEW_LINE> self._moduledescription = 'Helper call to define Overlay processor/driver inputs' <NEW_LINE> <DEDENT> def setCollections(self, CollectionList): <NEW_LINE> <INDENT> self._checkArgs( { 'CollectionList' : types.ListType } ) <NEW_LINE> self.collections = CollectionList <NEW_LINE> return S_OK() <NEW_LINE> <DEDENT> def _applicationModule(self): <NEW_LINE> <INDENT> m1 = self._createModuleDefinition() <NEW_LINE> m1.addParameter( Parameter( "collections", [], "list", "", "", False, False, "Collections to check for" ) ) <NEW_LINE> m1.addParameter( Parameter( "debug", False, "bool", "", "", False, False, "debug mode")) <NEW_LINE> return m1 <NEW_LINE> <DEDENT> def _applicationModuleValues(self, moduleinstance): <NEW_LINE> <INDENT> moduleinstance.setValue('collections', self.collections) <NEW_LINE> moduleinstance.setValue('debug', self.debug) <NEW_LINE> <DEDENT> def _userjobmodules(self, stepdefinition): <NEW_LINE> <INDENT> res1 = self._setApplicationModuleAndParameters(stepdefinition) <NEW_LINE> res2 = self._setUserJobFinalization(stepdefinition) <NEW_LINE> if not res1["OK"] or not res2["OK"] : <NEW_LINE> <INDENT> return S_ERROR('userjobmodules failed') <NEW_LINE> <DEDENT> return S_OK() <NEW_LINE> <DEDENT> def _prodjobmodules(self, stepdefinition): <NEW_LINE> <INDENT> res1 = self._setApplicationModuleAndParameters(stepdefinition) <NEW_LINE> res2 = self._setOutputComputeDataList(stepdefinition) <NEW_LINE> if not res1["OK"] or not res2["OK"] : <NEW_LINE> <INDENT> return S_ERROR('prodjobmodules failed') <NEW_LINE> <DEDENT> return S_OK() <NEW_LINE> <DEDENT> def _checkConsistency(self): <NEW_LINE> <INDENT> if not self.collections : <NEW_LINE> <INDENT> return S_ERROR('No collections to check') <NEW_LINE> <DEDENT> res = self._checkRequiredApp() <NEW_LINE> if not res['OK']: <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> return S_OK() <NEW_LINE> <DEDENT> def _resolveLinkedStepParameters(self, stepinstance): <NEW_LINE> <INDENT> if type(self._linkedidx) == types.IntType: <NEW_LINE> <INDENT> self._inputappstep = self._jobsteps[self._linkedidx] <NEW_LINE> <DEDENT> if self._inputappstep: <NEW_LINE> <INDENT> stepinstance.setLink("InputFile", self._inputappstep.getType(), "OutputFile") <NEW_LINE> <DEDENT> return S_OK() | Helper to check collection
Example:
>>> check = OverlayInput()
>>> check.setInputFile( [slcioFile_1.slcio , slcioFile_2.slcio , slcioFile_3.slcio] )
>>> check.setCollections( ["some_collection_name"] ) | 6259908e7cff6e4e811b76d2 |
class FullNameGenerator(generators.FirstNameGenerator, generators.LastNameGenerator): <NEW_LINE> <INDENT> def __init__(self, gender=None): <NEW_LINE> <INDENT> self.gender = gender <NEW_LINE> self.all = self.male + self.female <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> if self.gender == 'm': <NEW_LINE> <INDENT> first_name = random.choice(self.male) <NEW_LINE> <DEDENT> elif self.gender == 'f': <NEW_LINE> <INDENT> first_name = random.choice(self.female) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> first_name = random.choice(self.all) <NEW_LINE> <DEDENT> last_name = random.choice(self.surname) <NEW_LINE> return "%s %s" % (first_name, last_name) | Generates a full_name of the form 'fname lname' | 6259908ead47b63b2c5a94e1 |
@dataclass <NEW_LINE> class Account: <NEW_LINE> <INDENT> id: str <NEW_LINE> name: str <NEW_LINE> type: str <NEW_LINE> on_budget: bool <NEW_LINE> closed: bool <NEW_LINE> note: str <NEW_LINE> balance: int <NEW_LINE> cleared_balance: int <NEW_LINE> uncleared_balance: int <NEW_LINE> transfer_payee_id: str <NEW_LINE> deleted: bool | Data Class to represent Account data returned by YNAB API | 6259908ed8ef3951e32c8ca5 |
class UserViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = User.objects.all().order_by('-date_joined') <NEW_LINE> serializer_class = UserSerializer | API endpoint that allows users tobe viewed or edited. | 6259908e099cdd3c63676242 |
class TestCal(): <NEW_LINE> <INDENT> @pytest.mark.parametrize(('a'), cfg['add']) <NEW_LINE> @pytest.mark.dependency() <NEW_LINE> def test_add(self, a, start_message): <NEW_LINE> <INDENT> assert a[2] == cal.add(a[0], a[1]) <NEW_LINE> <DEDENT> '''减法用例''' <NEW_LINE> @pytest.mark.parametrize(('a'), cfg['cut']) <NEW_LINE> @pytest.mark.dependency(depends=["test_add"]) <NEW_LINE> def test_cut(self, a, start_message): <NEW_LINE> <INDENT> assert a[2] == cal.cut(a[0], a[1]) <NEW_LINE> <DEDENT> '''乘法''' <NEW_LINE> @pytest.mark.parametrize(('a'), cfg['ride']) <NEW_LINE> @pytest.mark.dependency() <NEW_LINE> def test_ride(self, a, start_message): <NEW_LINE> <INDENT> assert a[2] == cal.ride(a[0], a[1]) <NEW_LINE> <DEDENT> '''除法''' <NEW_LINE> @pytest.mark.parametrize(('a'), cfg['div']) <NEW_LINE> @pytest.mark.dependency(depends=["test_ride"]) <NEW_LINE> def test_div(self, a, start_message): <NEW_LINE> <INDENT> assert a[2] == cal.div(a[0], a[1]) | 加法用例 | 6259908e55399d3f056281a5 |
class JSONComponentView(AbstractIssuerAPIEndpoint): <NEW_LINE> <INDENT> permission_classes = (permissions.AllowAny,) <NEW_LINE> def get(self, request, slug): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> current_object = self.model.objects.get(slug=slug) <NEW_LINE> <DEDENT> except self.model.DoesNotExist: <NEW_LINE> <INDENT> return Response(status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response(current_object.json) | Abstract Component Class | 6259908e8a349b6b43687ef1 |
class Alert(Html): <NEW_LINE> <INDENT> INFO = 'info' <NEW_LINE> SUCCESS = 'success' <NEW_LINE> WARNING = 'warning' <NEW_LINE> DANGER = 'danger' <NEW_LINE> tag = 'div' <NEW_LINE> color_class = 'alert alert-{color}' <NEW_LINE> def __init__(self, html, alert='success', no_margin=False, **options): <NEW_LINE> <INDENT> options.pop('color', None) <NEW_LINE> super().__init__(html, color=alert, **options) <NEW_LINE> if no_margin: <NEW_LINE> <INDENT> self.attr['class'] += ' no-margin' | Bootstrap alert | 6259908ef9cc0f698b1c6114 |
class ClientHandler(SocketListener): <NEW_LINE> <INDENT> def __init__(self, server, socket, id, encoder): <NEW_LINE> <INDENT> SocketListener.__init__(self, encoder) <NEW_LINE> self.server = server <NEW_LINE> self.id = id <NEW_LINE> lockable_attrs(self, socket = socket ) <NEW_LINE> socket.setblocking(False) <NEW_LINE> <DEDENT> def get_socket(self): <NEW_LINE> <INDENT> return self.socket <NEW_LINE> <DEDENT> def get_socket_lock(self): <NEW_LINE> <INDENT> return self.socket_lock <NEW_LINE> <DEDENT> def get_connected_to(self): <NEW_LINE> <INDENT> return self.id <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.server.client_arrived(self.id) <NEW_LINE> SocketListener.start(self) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.listen_on_socket() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.server.client_departed(self.id) <NEW_LINE> <DEDENT> <DEDENT> def received(self, message): <NEW_LINE> <INDENT> message.sender = self.id <NEW_LINE> self.server.send(message) <NEW_LINE> <DEDENT> def handle_network_error(self, error_info): <NEW_LINE> <INDENT> self.server.event_queue.put(EvtConnectionError(*error_info)) <NEW_LINE> <DEDENT> def handle_unexpected_error(self, error_info): <NEW_LINE> <INDENT> self.server.event_queue.put(EvtFatalError(*error_info)) | A client handler which handles messages from a single client
on the server. After constructing, "start" method should be invoked
to begin ClientHandler running in its own thread. | 6259908f5fdd1c0f98e5fc0a |
class INumericCounter(INumericValue): <NEW_LINE> <INDENT> pass | A counter that can be incremented. Conflicts are resolved by
merging the numeric value of the difference in magnitude of
changes. Intended to be used for monotonically increasing
counters, typically integers. | 6259908fd8ef3951e32c8ca7 |
class IC_7410(Base_14pin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pins = [None, 0, 0, 0, 0, 0, None, 0, None, 0, 0, 0, None, 0, 0] <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> output[12] = NAND(self.pins[1], self.pins[2], self.pins[13]).output() <NEW_LINE> output[6] = NAND(self.pins[3], self.pins[4], self.pins[5]).output() <NEW_LINE> output[8] = NAND(self.pins[9], self.pins[10], self.pins[11]).output() <NEW_LINE> if self.pins[7] == 0 and self.pins[14] == 1: <NEW_LINE> <INDENT> self.setIC(output) <NEW_LINE> for i in self.outputConnector: <NEW_LINE> <INDENT> self.outputConnector[i].state = output[i] <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Ground and VCC pins have not been configured correctly.") | This is a Triple 3 input NAND gate IC
Pin Number Description
1 A Input Gate 1
2 B Input Gate 1
3 A Input Gate 2
4 B Input Gate 2
5 C Input gate 2
6 Y Output Gate 2
7 Ground
8 Y Output Gate 3
9 A Input Case 3
10 B Input Case 3
11 C Input Case 3
12 Y Output Gate 1
13 C Input Gate 1
14 Positive Supply
This class needs 14 parameters. Each parameter being the pin value. The input has to be defined as a dictionary
with pin number as the key and its value being either 1 or 0
To initialise the ic 7410:
1. set pin 7:0
2. set pin 14:1
How to use:
>>> ic = IC_7410()
>>> pin_config = {1: 1, 2: 0, 3: 0, 4: 0, 5: 0, 7: 0, 9: 1, 10: 1, 11: 1, 13: 0, 14: 1}
>>> ic.setIC(pin_cofig)
>>> ic.drawIC()
>>> ic.run()
>>> ic.setIC(ic.run())
>>> ic.drawIC()
Default pins:
pins = [None,0,0,0,0,0,None,0,None,0,0,0,None,0,0] | 6259908fa05bb46b3848bf6f |
class Line(Shape): <NEW_LINE> <INDENT> DEFAULTS = LINE_DEFAULTS <NEW_LINE> def __init__(self, start, end): <NEW_LINE> <INDENT> self.start = start <NEW_LINE> self.end = end <NEW_LINE> self.color = Line.DEFAULTS['color'] <NEW_LINE> self.thicknesss = Line.DEFAULTS['thickness'] <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> string = 'Line from ({}, {}) to ({}, {}))' <NEW_LINE> return string.format(self.start.x, self.start.y, self.end.x, self.end.y) <NEW_LINE> <DEDENT> def move_by(self, delta_x, delta_y): <NEW_LINE> <INDENT> self.start.move_by(delta_x, delta_y) <NEW_LINE> self.end.move_by(delta_x, delta_y) <NEW_LINE> self._move_representations_by(delta_x, delta_y) <NEW_LINE> <DEDENT> @property <NEW_LINE> def midpoint(self): <NEW_LINE> <INDENT> return Point((self.start.x + self.end.x) // 2, (self.start.y + self.end.y) // 2) <NEW_LINE> <DEDENT> def _get_coordinates_for_drawing(self): <NEW_LINE> <INDENT> return [self.start.x, self.start.y, self.end.x, self.end.y] <NEW_LINE> <DEDENT> doc_string = 'Coordinates tkinter needs to draw this Shape' <NEW_LINE> _coordinates_for_drawing = property(_get_coordinates_for_drawing, doc=doc_string) <NEW_LINE> def _get_options_for_drawing(self): <NEW_LINE> <INDENT> options = {'fill': self.color, 'width': self.thickness} <NEW_LINE> return options <NEW_LINE> <DEDENT> doc_string = 'Some of the options (like fill_color) that tkinter uses to draw this Shape' <NEW_LINE> _options_for_drawing = property(_get_options_for_drawing, doc=doc_string) | A Line has Points for its start and end.
Options allow it to have: xxx. | 6259908f656771135c48ae7b |
class Conotate(Annotate): <NEW_LINE> <INDENT> def __init__(self, definition, *args, **kws): <NEW_LINE> <INDENT> definition = coroutine(definition) <NEW_LINE> super().__init__(definition, *args, **kws) | annotation that is defined as a coroutine | 6259908f3346ee7daa3384ac |
class ContactView(FormView): <NEW_LINE> <INDENT> SUCCESS_MESSAGE = "Votre question a bien été transmise à l'administrateur du site." <NEW_LINE> form_class = ContactForm <NEW_LINE> success_url = '/contact' <NEW_LINE> template_name = 'referendum/contact.html' <NEW_LINE> def get_form(self, form_class=None): <NEW_LINE> <INDENT> form = super().get_form(form_class) <NEW_LINE> if settings.DESACTIVATE_RECAPTCHA: <NEW_LINE> <INDENT> del form.fields['captcha'] <NEW_LINE> <DEDENT> return form <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> form.send_mail() <NEW_LINE> messages.add_message( self.request, messages.INFO, self.SUCCESS_MESSAGE ) <NEW_LINE> return super().form_valid(form) | A contact form view | 6259908fec188e330fdfa544 |
class HTTPConfiguration(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'method': {'key': 'method', 'type': 'str'}, 'headers': {'key': 'headers', 'type': '[HTTPHeader]'}, 'valid_status_codes': {'key': 'validStatusCodes', 'type': '[int]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(HTTPConfiguration, self).__init__(**kwargs) <NEW_LINE> self.method = kwargs.get('method', None) <NEW_LINE> self.headers = kwargs.get('headers', None) <NEW_LINE> self.valid_status_codes = kwargs.get('valid_status_codes', None) | HTTP configuration of the connectivity check.
:param method: HTTP method. Possible values include: "Get".
:type method: str or ~azure.mgmt.network.v2021_02_01.models.HTTPMethod
:param headers: List of HTTP headers.
:type headers: list[~azure.mgmt.network.v2021_02_01.models.HTTPHeader]
:param valid_status_codes: Valid status codes.
:type valid_status_codes: list[int] | 6259908ff9cc0f698b1c6116 |
class CallbackMap(EventMap): <NEW_LINE> <INDENT> def get_callbacks(self, event_key): <NEW_LINE> <INDENT> if event_key not in self._callback_lut: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return self._callback_lut[event_key] | An event decorator that maps events to callbacks.
Example use:
>>> class Foo(object):
>>> cmap = CallbackMap()
>>> @emap('foo', 'bar')
>>> def foo_or_bar(*args):
>>> print 'foo_or_bar called with args', repr(args)
>>> def handle(self, event_name):
>>> for cb in self.cmap.get_callbacks(event_name)
>>> cb(self, 1, 2, 3)
>>> Foo().handle('foo') | 6259908f283ffb24f3cf5536 |
class _TensorSpecCodec(object): <NEW_LINE> <INDENT> def can_encode(self, pyobj): <NEW_LINE> <INDENT> return isinstance(pyobj, tensor_spec.TensorSpec) <NEW_LINE> <DEDENT> def do_encode(self, tensor_spec_value, encode_fn): <NEW_LINE> <INDENT> encoded_tensor_spec = struct_pb2.StructuredValue() <NEW_LINE> encoded_tensor_spec.tensor_spec_value.CopyFrom( struct_pb2.TensorSpecProto( shape=encode_fn(tensor_spec_value.shape).tensor_shape_value, dtype=encode_fn(tensor_spec_value.dtype).tensor_dtype_value, name=tensor_spec_value.name)) <NEW_LINE> return encoded_tensor_spec <NEW_LINE> <DEDENT> def can_decode(self, value): <NEW_LINE> <INDENT> return value.HasField("tensor_spec_value") <NEW_LINE> <DEDENT> def do_decode(self, value, decode_fn): <NEW_LINE> <INDENT> return tensor_spec.TensorSpec( shape=decode_fn( struct_pb2.StructuredValue( tensor_shape_value=value.tensor_spec_value.shape)), dtype=decode_fn( struct_pb2.StructuredValue( tensor_dtype_value=value.tensor_spec_value.dtype)), name=value.tensor_spec_value.name) | Codec for `TensorSpec`. | 6259908fad47b63b2c5a94e7 |
class Function: <NEW_LINE> <INDENT> def __init__(self, args, body): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def evaluate(self, scope): <NEW_LINE> <INDENT> raise NotImplementedError | Function - представляет функцию в программе.
Функция - второй тип поддерживаемый языком.
Функции можно передавать в другие функции,
и возвращать из функций.
Функция состоит из тела и списка имен аргументов.
Тело функции это список выражений,
т. е. у каждого из них есть метод evaluate.
Во время вычисления функции (метод evaluate),
все объекты тела функции вычисляются последовательно,
и результат вычисления последнего из них
является результатом вычисления функции.
Список имен аргументов - список имен
формальных параметров функции. | 6259908f50812a4eaa621a11 |
class IMEXSerializer(object): <NEW_LINE> <INDENT> type_name = None <NEW_LINE> type_slug = None <NEW_LINE> type_mime = None <NEW_LINE> type_ext = None | (De)Serialize base class for import/export modules
Each serializer must implement at least one of the following methods:
- `serialize(self, **kwargs)`
- `deserialize(self, **kwargs)` | 6259908fa05bb46b3848bf70 |
class PlaneTracker(Tracker): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> p1 = Draft.get3DView().getPoint((100,100)) <NEW_LINE> p2 = Draft.get3DView().getPoint((110,100)) <NEW_LINE> bl = (p2.sub(p1)).Length * (Draft.getParam("snapRange")/2) <NEW_LINE> pick = coin.SoPickStyle() <NEW_LINE> pick.style.setValue(coin.SoPickStyle.UNPICKABLE) <NEW_LINE> self.trans = coin.SoTransform() <NEW_LINE> self.trans.translation.setValue([0,0,0]) <NEW_LINE> m1 = coin.SoMaterial() <NEW_LINE> m1.transparency.setValue(0.8) <NEW_LINE> m1.diffuseColor.setValue([0.4,0.4,0.6]) <NEW_LINE> c1 = coin.SoCoordinate3() <NEW_LINE> c1.point.setValues([[-bl,-bl,0],[bl,-bl,0],[bl,bl,0],[-bl,bl,0]]) <NEW_LINE> f = coin.SoIndexedFaceSet() <NEW_LINE> f.coordIndex.setValues([0,1,2,3]) <NEW_LINE> m2 = coin.SoMaterial() <NEW_LINE> m2.transparency.setValue(0.7) <NEW_LINE> m2.diffuseColor.setValue([0.2,0.2,0.3]) <NEW_LINE> c2 = coin.SoCoordinate3() <NEW_LINE> c2.point.setValues([[0,bl,0],[0,0,0],[bl,0,0],[-.05*bl,.95*bl,0],[0,bl,0], [.05*bl,.95*bl,0],[.95*bl,.05*bl,0],[bl,0,0],[.95*bl,-.05*bl,0]]) <NEW_LINE> l = coin.SoLineSet() <NEW_LINE> l.numVertices.setValues([3,3,3]) <NEW_LINE> s = coin.SoSeparator() <NEW_LINE> s.addChild(pick) <NEW_LINE> s.addChild(self.trans) <NEW_LINE> s.addChild(m1) <NEW_LINE> s.addChild(c1) <NEW_LINE> s.addChild(f) <NEW_LINE> s.addChild(m2) <NEW_LINE> s.addChild(c2) <NEW_LINE> s.addChild(l) <NEW_LINE> Tracker.__init__(self,children=[s]) <NEW_LINE> <DEDENT> def set(self,pos=None): <NEW_LINE> <INDENT> if pos: <NEW_LINE> <INDENT> Q = FreeCAD.DraftWorkingPlane.getRotation().Rotation.Q <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> plm = FreeCAD.DraftWorkingPlane.getPlacement() <NEW_LINE> Q = plm.Rotation.Q <NEW_LINE> pos = plm.Base <NEW_LINE> <DEDENT> self.trans.translation.setValue([pos.x,pos.y,pos.z]) <NEW_LINE> self.trans.rotation.setValue([Q[0],Q[1],Q[2],Q[3]]) <NEW_LINE> self.on() | A working plane tracker | 6259908f283ffb24f3cf5537 |
class OrganizationField(DummyField): <NEW_LINE> <INDENT> replacements = { '_name': (models.CharField, {'max_length':255, 'null':True}), '_adr': (AddressField, {}), } | A field for representing an organization.
Creating an OrganizationField named 'organization', for example, will (under the hood) create two fields:
* ``pharmacy_name``, the name of the organization
* ``organization_adr``, the address at which the organization is located (an :py:class:`~indivo.fields.AddressField`)
When describing instances of your model (either when defining a
:ref:`transform output <transform-output-types>` or when referencing fields using
:ref:`the Indivo Query API <queryable-fields>`), you must refer to these field names, not the original
``organization`` field name. | 6259908f3617ad0b5ee07de8 |
class AddMemberAction(BaseRequestHandler): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> slide_set = SlideSet.get(self.request.get('list')) <NEW_LINE> email = self.request.get('email') <NEW_LINE> if not slide_set or not email: <NEW_LINE> <INDENT> self.error(403) <NEW_LINE> return <NEW_LINE> <DEDENT> if not slide_set.current_user_has_access(): <NEW_LINE> <INDENT> self.error(403) <NEW_LINE> return <NEW_LINE> <DEDENT> user = users.User(email) <NEW_LINE> if not slide_set.user_has_access(user): <NEW_LINE> <INDENT> member = SlideSetMember(user=user, slide_set=slide_set) <NEW_LINE> member.put() <NEW_LINE> <DEDENT> self.redirect(self.request.get('next')) | Adds a new User to a SlideSet ACL. | 6259908f8a349b6b43687ef7 |
class DecimatePro(FilterBase): <NEW_LINE> <INDENT> __version__ = 0 <NEW_LINE> filter = Instance(tvtk.DecimatePro, args=(), allow_none=False, record=True) <NEW_LINE> input_info = PipelineInfo(datasets=['poly_data'], attribute_types=['any'], attributes=['any']) <NEW_LINE> output_info = PipelineInfo(datasets=['poly_data'], attribute_types=['any'], attributes=['any']) | Reduces the number of triangles in a mesh using the
tvtk.DecimatePro class. | 6259908f283ffb24f3cf5538 |
class PreAuthSecondaryTransactionAllOf(object): <NEW_LINE> <INDENT> openapi_types = { 'transaction_amount': 'Amount', 'decremental_flag': 'bool' } <NEW_LINE> attribute_map = { 'transaction_amount': 'transactionAmount', 'decremental_flag': 'decrementalFlag' } <NEW_LINE> def __init__(self, transaction_amount=None, decremental_flag=False): <NEW_LINE> <INDENT> self._transaction_amount = None <NEW_LINE> self._decremental_flag = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.transaction_amount = transaction_amount <NEW_LINE> if decremental_flag is not None: <NEW_LINE> <INDENT> self.decremental_flag = decremental_flag <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def transaction_amount(self): <NEW_LINE> <INDENT> return self._transaction_amount <NEW_LINE> <DEDENT> @transaction_amount.setter <NEW_LINE> def transaction_amount(self, transaction_amount): <NEW_LINE> <INDENT> if transaction_amount is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `transaction_amount`, must not be `None`") <NEW_LINE> <DEDENT> self._transaction_amount = transaction_amount <NEW_LINE> <DEDENT> @property <NEW_LINE> def decremental_flag(self): <NEW_LINE> <INDENT> return self._decremental_flag <NEW_LINE> <DEDENT> @decremental_flag.setter <NEW_LINE> def decremental_flag(self, decremental_flag): <NEW_LINE> <INDENT> self._decremental_flag = decremental_flag <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PreAuthSecondaryTransactionAllOf): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 6259908f4c3428357761bf53 |
class AdminBuildTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.version_info = 'Python 2.7.8' <NEW_LINE> self.version_prefix = 'Python' <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_decode_version(self): <NEW_LINE> <INDENT> v = build.decode_version(self.version_info, self.version_prefix) <NEW_LINE> self.assertIsInstance(v, build.Version) <NEW_LINE> self.assertEqual(v.major, 2) <NEW_LINE> self.assertEqual(v.minor, 7) <NEW_LINE> self.assertEqual(v.patch, 8) <NEW_LINE> <DEDENT> def test_match(self): <NEW_LINE> <INDENT> v = build.decode_version(self.version_info, self.version_prefix) <NEW_LINE> self.assertTrue(build.match_version(v, '2.7.8')) <NEW_LINE> self.assertTrue(build.match_version(v, '2.7.6')) <NEW_LINE> self.assertFalse(build.match_version(v, '2.7.9')) <NEW_LINE> self.assertTrue(build.match_version(v, '2.6.8')) <NEW_LINE> self.assertTrue(build.match_version(v, '2.6.6')) <NEW_LINE> self.assertTrue(build.match_version(v, '2.6.9')) <NEW_LINE> self.assertFalse(build.match_version(v, '2.8.8')) <NEW_LINE> self.assertFalse(build.match_version(v, '2.8.6')) <NEW_LINE> self.assertFalse(build.match_version(v, '2.8.9')) <NEW_LINE> self.assertTrue(build.match_version(v, '1.7.8')) <NEW_LINE> self.assertTrue(build.match_version(v, '1.8.8')) <NEW_LINE> self.assertTrue(build.match_version(v, '1.6.8')) <NEW_LINE> self.assertTrue(build.match_version(v, '1.7.6')) <NEW_LINE> self.assertTrue(build.match_version(v, '1.7.9')) <NEW_LINE> self.assertFalse(build.match_version(v, '3.7.8')) <NEW_LINE> self.assertFalse(build.match_version(v, '3.8.8')) <NEW_LINE> self.assertFalse(build.match_version(v, '3.6.8')) <NEW_LINE> self.assertFalse(build.match_version(v, '3.7.6')) <NEW_LINE> self.assertFalse(build.match_version(v, '3.7.9')) | Test Case of admin.build module.
| 6259908fbf627c535bcb316b |
class GecosAccessData(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.url = '' <NEW_LINE> self.login = '' <NEW_LINE> self.password = '' <NEW_LINE> <DEDENT> def get_url(self): <NEW_LINE> <INDENT> return self.__url <NEW_LINE> <DEDENT> def get_login(self): <NEW_LINE> <INDENT> return self.__login <NEW_LINE> <DEDENT> def get_password(self): <NEW_LINE> <INDENT> return self.__password <NEW_LINE> <DEDENT> def set_url(self, value): <NEW_LINE> <INDENT> self.__url = value <NEW_LINE> <DEDENT> def set_login(self, value): <NEW_LINE> <INDENT> self.__login = value <NEW_LINE> <DEDENT> def set_password(self, value): <NEW_LINE> <INDENT> self.__password = value <NEW_LINE> <DEDENT> url = property( get_url, set_url, None, None ) <NEW_LINE> login = property( get_login, set_login, None, None ) <NEW_LINE> password = property( get_password, set_password, None, None ) | DTO object that represents the data to access a GECOS CC. | 6259908fdc8b845886d55251 |
class GrandLodgeDeposit(users.Model): <NEW_LINE> <INDENT> payer = models.ForeignKey( users.Affiliation, verbose_name=_('payer'), related_name='grand_lodge_deposits', related_query_name='grand_lodge_deposit', on_delete=models.PROTECT, db_index=True ) <NEW_LINE> amount = models.DecimalField( _('amount'), max_digits=12, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))] ) <NEW_LINE> description = models.CharField( _('description'), max_length=300, default="", blank=True, help_text=_("Optional description.") ) <NEW_LINE> receipt = models.FileField( _('receipt'), upload_to='receipts', blank=True, null=True ) <NEW_LINE> status = models.CharField( _('status'), max_length=1, choices=GRANDLODGEDEPOSIT_STATUSES, default=GRANDLODGEDEPOSIT_PENDING, blank=True ) <NEW_LINE> account_movement = GenericRelation( AccountMovement, related_query_name='treasure_account_grandlodgedeposit', content_type_field='object_ct', object_id_field='object_id' ) <NEW_LINE> send_email = models.BooleanField( _('send email'), default=False ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.payer) + ' -> GL + $ ' + str(self.amount) + ( ' (#' + str(self.id) + ')' ) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse( 'treasure:grandlodgedeposit-detail', kwargs={'pk': self.pk} ) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _('grand lodge deposit') <NEW_LINE> verbose_name_plural = _('grand lodge deposits') <NEW_LINE> default_permissions = ('add', 'change', 'delete', 'view') <NEW_LINE> ordering = ['-created_on'] | A `payer` deposits money directly to the Grand Lodge's bank account.
Need to confirm it has been properly accredited by both the bank and the GL. | 6259908f7cff6e4e811b76dc |
class OperationListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[Operation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["Operation"]] = None, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(OperationListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link | Result of the request to list Microsoft.Resources operations. It contains a list of operations and a URL link to get the next set of results.
:ivar value: List of Microsoft.Resources operations.
:vartype value: list[~azure.mgmt.resource.resources.v2021_01_01.models.Operation]
:ivar next_link: URL to get the next set of operation list results if there are any.
:vartype next_link: str | 6259908f099cdd3c63676247 |
class BlogView(APIView): <NEW_LINE> <INDENT> def get(self,request): <NEW_LINE> <INDENT> blogs = Blog.objects.all() <NEW_LINE> serializer = BlogSerializer(blogs, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self,request): <NEW_LINE> <INDENT> request.data['slug'] = slugify(request.data['title']) <NEW_LINE> serializers = BlogSerializer(data=request.data) <NEW_LINE> try: <NEW_LINE> <INDENT> if serializers.is_valid(): <NEW_LINE> <INDENT> serializers.save() <NEW_LINE> return Response(serializers.data, status = status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> <DEDENT> except IntegrityError: <NEW_LINE> <INDENT> print("Please submit a new Blog. Blog already exists with this TITLE.") <NEW_LINE> return Response({"StatusMessage":"Please submit a new Blog. Blog already exists with this TITLE."},status = status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> return Response(serializers.errors, status = status.HTTP_400_BAD_REQUEST) | API to list all the blogs saved in the application and to create a new blog. | 6259908f656771135c48ae7e |
class InstanciaAdministrativa(models.Model): <NEW_LINE> <INDENT> nombre = models.CharField(max_length=100) <NEW_LINE> publicar = models.BooleanField(default=False) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.nombre <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['nombre', ] <NEW_LINE> db_table = 'oeu\".\"instancia_administrativa' <NEW_LINE> verbose_name = "Instancia Administrativa" <NEW_LINE> verbose_name_plural = "Instancias Administrativas" | Este modelo controla las instancias administrativas para luego poder
referenciar los teléfonos, correos, etc. de las localidades de las IEU | 6259908f5fdd1c0f98e5fc12 |
class ArithmeticError(Exception): <NEW_LINE> <INDENT> pass | Raised by arithmetic_eval() on errors in the evaluated expression. | 6259908f97e22403b383cb92 |
class HasCouplingVars(object): <NEW_LINE> <INDENT> def __init__(self,parent): <NEW_LINE> <INDENT> self._parent = parent <NEW_LINE> self._couples = ordereddict.OrderedDict() <NEW_LINE> <DEDENT> def add_coupling_var(self,indep_dep,name=None,start=None): <NEW_LINE> <INDENT> indep,dep = indep_dep <NEW_LINE> expr_indep = CouplingVar(indep,self._parent) <NEW_LINE> if not expr_indep.check_resolve() or not expr_indep.is_valid_assignee(): <NEW_LINE> <INDENT> self._parent.raise_exception("Can't add coupling variable with indep '%s' " "because is not a valid variable."%indep, ValueError) <NEW_LINE> <DEDENT> expr_dep = CouplingVar(dep,self._parent) <NEW_LINE> if not expr_indep.check_resolve() or not expr_indep.is_valid_assignee(): <NEW_LINE> <INDENT> self._parent.raise_exception("Can't add coupling variable with dep '%s' " "because is not a valid variable."%dep, ValueError) <NEW_LINE> <DEDENT> if self._couples: <NEW_LINE> <INDENT> if indep in [c[0] for c in self._couples]: <NEW_LINE> <INDENT> self._parent.raise_exception("Coupling variable with indep '%s' already " "exists in assembly."%indep,ValueError) <NEW_LINE> <DEDENT> <DEDENT> if name is None: <NEW_LINE> <INDENT> name = indep_dep <NEW_LINE> <DEDENT> c = Couple(expr_indep,expr_dep,name,start) <NEW_LINE> if start is not None: <NEW_LINE> <INDENT> expr_indep.set(start) <NEW_LINE> <DEDENT> if name is not None: <NEW_LINE> <INDENT> self._couples[name] = c <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._couples[indep_dep] = c <NEW_LINE> <DEDENT> return c <NEW_LINE> <DEDENT> def remove_coupling_var(self,indep_dep): <NEW_LINE> <INDENT> if indep_dep not in self._couples: <NEW_LINE> <INDENT> self._parent.raise_exception("No coupling variable of ('%s','%s') exists " "in assembly."%indep_dep,ValueError) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c = self._couples[indep_dep] <NEW_LINE> del self._couples[indep_dep] <NEW_LINE> return c <NEW_LINE> <DEDENT> <DEDENT> def list_coupling_vars(self): <NEW_LINE> <INDENT> return self._couples <NEW_LINE> <DEDENT> def clear_coupling_vars(self): <NEW_LINE> <INDENT> self._couples = [] <NEW_LINE> <DEDENT> def init_coupling_vars(self): <NEW_LINE> <INDENT> for indep_dep,couple in self._couples.iteritems(): <NEW_LINE> <INDENT> if couple.start is not None: <NEW_LINE> <INDENT> couple.indep.set(couple.start,self._parent.get_expr_scope()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def mimic(self, target): <NEW_LINE> <INDENT> self._couples = ordereddict.OrderedDict() <NEW_LINE> for key,val in target._couples.items(): <NEW_LINE> <INDENT> self._couples[key] = val.copy() | This class provides an implementation of the IHasCouplingVar interface.
parent: Assembly
Assembly object that this object belongs to. | 6259908f55399d3f056281af |
class BackAction(Action): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(BackAction, self).__init__("system::back") <NEW_LINE> <DEDENT> def call(self, context): <NEW_LINE> <INDENT> context.popStack() <NEW_LINE> context.popStack() | BACK | 6259908f26068e7796d4e5de |
class PerfilResponse(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'id': 'int', 'nome': 'str' } <NEW_LINE> self.attribute_map = { 'id': 'id', 'nome': 'nome' } <NEW_LINE> self._id = None <NEW_LINE> self._nome = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def nome(self): <NEW_LINE> <INDENT> return self._nome <NEW_LINE> <DEDENT> @nome.setter <NEW_LINE> def nome(self, nome): <NEW_LINE> <INDENT> self._nome = nome <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> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259908fbf627c535bcb316f |
class SailtrailSitemap(Sitemap): <NEW_LINE> <INDENT> priority = 0.5 <NEW_LINE> protocol = 'https' | Base sitemap settings | 6259908fd8ef3951e32c8cab |
class ApiViewsTest(APITestCase): <NEW_LINE> <INDENT> fixtures = ["trek"] <NEW_LINE> def build_random_url(self, query_params=None): <NEW_LINE> <INDENT> url = f'http://testserver{reverse("website:random")}' <NEW_LINE> if query_params: <NEW_LINE> <INDENT> url = ( url + "?" + "&".join([f"{key}={value}" for key, value in query_params.items()]) ) <NEW_LINE> <DEDENT> return url <NEW_LINE> <DEDENT> def test_get_speaker_detail(self): <NEW_LINE> <INDENT> speaker_id = 2 <NEW_LINE> clique_id = 1 <NEW_LINE> url = reverse("api:speaker-detail", args=[speaker_id]) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, http.HTTPStatus.OK) <NEW_LINE> response_json = response.json() <NEW_LINE> self.assertEqual(response_json["id"], speaker_id) <NEW_LINE> self.assertEqual(response_json["name"], "William Riker") <NEW_LINE> self.assertEqual(response_json["cliques"][0]["id"], clique_id) <NEW_LINE> self.assertEqual(response_json["cliques"][0]["slug"], "tng") <NEW_LINE> self.assertEqual( response_json["random_url"], self.build_random_url({"speaker_id": speaker_id}), ) <NEW_LINE> <DEDENT> def test_get_clique_detail(self): <NEW_LINE> <INDENT> url = reverse("api:clique-detail", args=[1]) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, http.HTTPStatus.OK) <NEW_LINE> response_json = response.json() <NEW_LINE> self.assertEqual(response_json["id"], 1) <NEW_LINE> self.assertEqual(response_json["slug"], "tng") <NEW_LINE> self.assertIn({"id": 1, "name": "Jean-Luc Picard"}, response_json["speakers"]) <NEW_LINE> <DEDENT> def test_get_stats_list(self): <NEW_LINE> <INDENT> url = reverse("api:stats-list") <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, http.HTTPStatus.OK) <NEW_LINE> response_json = response.json() <NEW_LINE> self.assertEqual(response_json["clique_count"], 3) <NEW_LINE> self.assertEqual(response_json["quip_count"], 6) <NEW_LINE> self.assertEqual(response_json["quote_count"], 13) <NEW_LINE> self.assertEqual(response_json["speaker_count"], 6) <NEW_LINE> self.assertIn( {"id": 1, "name": "Jean-Luc Picard", "quip_count": 4, "quote_count": 5}, response_json["top_speakers"], ) | API views test case. | 6259908f97e22403b383cb94 |
class ParameterGroupingPostOptionalParameters(Model): <NEW_LINE> <INDENT> def __init__(self, custom_header=None, query=30, **kwargs): <NEW_LINE> <INDENT> self.custom_header = custom_header <NEW_LINE> self.query = query | Additional parameters for the postOptional operation.
:param custom_header:
:type custom_header: str
:param query: Query parameter with default. Default value: 30 .
:type query: int | 6259908fbe7bc26dc9252ca4 |
class ComparativeIssues(Comparison): <NEW_LINE> <INDENT> def gather_items_by_key(self, items): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for ai in items: <NEW_LINE> <INDENT> text = ai.message.text <NEW_LINE> m = re.match('^(.+) at (.+):[0-9]+$', text) <NEW_LINE> if m: <NEW_LINE> <INDENT> text = m.group(1) <NEW_LINE> <DEDENT> key = (ai.generator.name, ai.testid, ai.internal_filename, ai.function, text) <NEW_LINE> if key in result: <NEW_LINE> <INDENT> result[key].add(ai) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[key] = set([ai]) <NEW_LINE> <DEDENT> <DEDENT> return result | Comparison of a pair of lists of AnalysisIssue : what's new, what's
fixed, etc | 6259908f7cff6e4e811b76e0 |
class df_Imputer(TransformerMixin): <NEW_LINE> <INDENT> def __init__(self, strategy='mean', missing_values=np.NaN, fill_value=None): <NEW_LINE> <INDENT> self.strategy = strategy <NEW_LINE> self.missing_values = missing_values <NEW_LINE> self.fill_value = fill_value <NEW_LINE> self.imp = None <NEW_LINE> self.statistics_ = None <NEW_LINE> <DEDENT> def fit(self, X, y=None): <NEW_LINE> <INDENT> self.imp = SimpleImputer(strategy=self.strategy, missing_values=self.missing_values, fill_value=self.fill_value) <NEW_LINE> self.imp.fit(X) <NEW_LINE> self.statistics_ = pd.Series(self.imp.statistics_, index=X.columns) <NEW_LINE> return self <NEW_LINE> <DEDENT> def transform(self, X): <NEW_LINE> <INDENT> Ximp = self.imp.transform(X) <NEW_LINE> Xfilled = pd.DataFrame(Ximp, index=X.index, columns=X.columns) <NEW_LINE> return Xfilled | Imputation transformer for completing missing values
Parameters
----------
strategy: str (default='mean')
-- 'mean'
-- 'median'
-- 'most_frequent'
-- 'constant'
fill_value: str of num (default=None)
missing_values: number, string, np.nan (default) or None
---------- | 6259908fbf627c535bcb3171 |
class change_simulation_line(models.TransientModel): <NEW_LINE> <INDENT> _name = 'change.simulation.line' <NEW_LINE> _description = 'Change product and quantity of a simulation line' <NEW_LINE> def _get_product_id(self): <NEW_LINE> <INDENT> line_id = self.env['simulation.line'].browse(self.env.context['active_id']) <NEW_LINE> return line_id.product_id <NEW_LINE> <DEDENT> def _get_quantity(self): <NEW_LINE> <INDENT> line_id = self.env['simulation.line'].browse(self.env.context['active_id']) <NEW_LINE> return line_id.quantity <NEW_LINE> <DEDENT> def _get_supplier_id(self): <NEW_LINE> <INDENT> line_id = self.env['simulation.line'].browse(self.env.context['active_id']) <NEW_LINE> return line_id.supplier_id <NEW_LINE> <DEDENT> simulation_line_id = fields.Many2one('simulation.line', string='Line', required=True, default=lambda self:self.env.context['active_id'], ondelete='cascade') <NEW_LINE> product_id = fields.Many2one('product.product', string='Product', required=True, domain=[('supply_method', '=', 'buy')], default=_get_product_id) <NEW_LINE> quantity = fields.Float(string='Quantity', digits=dp.get_precision('Product quantity'), required=True, default=_get_quantity) <NEW_LINE> unit_price = fields.Float(string='Unit price', digits=dp.get_precision('Account'), required=False) <NEW_LINE> supplier_id = fields.Many2one('res.partner', string='Supplier', required=False, ondelete='restrict', domain="[('is_supplier', '=', True), ('supplierinfo_product_search', '=', product_id)]", default=_get_supplier_id) <NEW_LINE> @api.multi <NEW_LINE> def update_line(self): <NEW_LINE> <INDENT> for line in self: <NEW_LINE> <INDENT> change_supplier = self.supplier_id != line.simulation_line_id.supplier_id <NEW_LINE> line.simulation_line_id.write({ 'product_id': self.product_id.id, 'quantity': self.quantity, 'unit_price':self.unit_price, 'total_price':self.unit_price * self.quantity, 'supplier_id':self.supplier_id.id, }) <NEW_LINE> if change_supplier: <NEW_LINE> <INDENT> line.simulation_line_id._onchange_supplier_id() <NEW_LINE> <DEDENT> specific_offer_id = line.simulation_line_id.specific_offer_id <NEW_LINE> total_price = sum([x['total_price'] for x in specific_offer_id.simulation_line_ids]) <NEW_LINE> specific_offer_id.write({'total_price':total_price, 'unit_price':total_price / specific_offer_id.quantity}) <NEW_LINE> line.simulation_line_id.update_parents() <NEW_LINE> specific_offer_id.compute_critical_path() <NEW_LINE> <DEDENT> return {'type': 'ir.actions.client', 'tag': 'reload', } <NEW_LINE> <DEDENT> @api.onchange('product_id') <NEW_LINE> def _onchange_product_id(self): <NEW_LINE> <INDENT> bom_obj = self.env['mrp.bom'] <NEW_LINE> self.unit_price = bom_obj.compute_price_component_buy(self.product_id, self.quantity, self.product_id.uom_id, self.env.user.company_id.currency_id) | Change product and quantity of a simulation line | 6259908fd8ef3951e32c8cac |
class EntryCreate(generics.CreateAPIView): <NEW_LINE> <INDENT> serializer_class = EntrySerializer | Create entry | 6259908f283ffb24f3cf553f |
class INV401KBAL(Aggregate): <NEW_LINE> <INDENT> cashbal = Decimal() <NEW_LINE> pretax = Decimal() <NEW_LINE> aftertax = Decimal() <NEW_LINE> match = Decimal() <NEW_LINE> profitsharing = Decimal() <NEW_LINE> rollover = Decimal() <NEW_LINE> othervest = Decimal() <NEW_LINE> othernonvest = Decimal() <NEW_LINE> total = Decimal(required=True) <NEW_LINE> ballist = SubAggregate(BALLIST) | OFX section 13.9.2.9 | 6259908fec188e330fdfa550 |
class Sun2PointInTimeSensor(Sun2Sensor): <NEW_LINE> <INDENT> def __init__(self, hass, sensor_type, icon): <NEW_LINE> <INDENT> super().__init__(hass, sensor_type, icon, 'civil') <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_class(self): <NEW_LINE> <INDENT> return DEVICE_CLASS_TIMESTAMP <NEW_LINE> <DEDENT> def _update(self): <NEW_LINE> <INDENT> super()._update() <NEW_LINE> if self._state != 'none': <NEW_LINE> <INDENT> self._state = self._state.isoformat() | Sun2 Point in Time Sensor. | 6259908f97e22403b383cb99 |
class AddTag(TagCommand): <NEW_LINE> <INDENT> SYNOPSIS = (None, 'tag/add', 'tag/add', '<tag>') <NEW_LINE> ORDER = ('Tagging', 0) <NEW_LINE> SPLIT_ARG = False <NEW_LINE> HTTP_CALLABLE = ('POST', ) <NEW_LINE> HTTP_POST_VARS = { 'name': 'tag name', 'slug': 'tag slug', 'icon': 'tag icon', 'label': 'display as label in search results, or not', 'label_color': 'label color', 'display': 'tag display type', 'template': 'tag template type', 'search_terms': 'magic search terms associated with this tag', 'parent': 'parent tag ID', } <NEW_LINE> OPTIONAL_VARS = ['icon', 'label', 'label_color', 'display', 'template', 'search_terms', 'parent'] <NEW_LINE> class CommandResult(TagCommand.CommandResult): <NEW_LINE> <INDENT> def as_text(self): <NEW_LINE> <INDENT> if not self.result: <NEW_LINE> <INDENT> return 'Failed' <NEW_LINE> <DEDENT> if not self.result['added']: <NEW_LINE> <INDENT> return 'Nothing happened' <NEW_LINE> <DEDENT> return ('Added tags: ' + ', '.join([k['name'] for k in self.result['added']])) <NEW_LINE> <DEDENT> <DEDENT> def command(self): <NEW_LINE> <INDENT> config = self.session.config <NEW_LINE> slugs = self.data.get('slug', []) <NEW_LINE> names = self.data.get('name', []) <NEW_LINE> if slugs and len(names) != len(slugs): <NEW_LINE> <INDENT> return self._error('Name/slug pairs do not match') <NEW_LINE> <DEDENT> elif names and not slugs: <NEW_LINE> <INDENT> slugs = [self.slugify(n) for n in names] <NEW_LINE> <DEDENT> slugs.extend([self.slugify(s) for s in self.args]) <NEW_LINE> names.extend(self.args) <NEW_LINE> for slug in slugs: <NEW_LINE> <INDENT> if slug != self.slugify(slug): <NEW_LINE> <INDENT> return self._error('Invalid tag slug: %s' % slug) <NEW_LINE> <DEDENT> <DEDENT> for tag in config.tags.values(): <NEW_LINE> <INDENT> if tag.slug in slugs: <NEW_LINE> <INDENT> return self._error('Tag already exists: %s/%s' % (tag.slug, tag.name)) <NEW_LINE> <DEDENT> <DEDENT> tags = [{'name': n, 'slug': s} for (n, s) in zip(names, slugs)] <NEW_LINE> for v in self.OPTIONAL_VARS: <NEW_LINE> <INDENT> for i in range(0, len(tags)): <NEW_LINE> <INDENT> vlist = self.data.get(v, []) <NEW_LINE> if len(vlist) > i and vlist[i]: <NEW_LINE> <INDENT> tags[i][v] = vlist[i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if tags: <NEW_LINE> <INDENT> config.tags.extend(tags) <NEW_LINE> self.finish(save=True) <NEW_LINE> <DEDENT> return {'added': tags} | Create a new tag | 6259908fbf627c535bcb3175 |
class GLADEncoder_global_local_no_rnn_v2(nn.Module): <NEW_LINE> <INDENT> def __init__(self, din, dhid, slots, dropout=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.dropout = dropout or {} <NEW_LINE> self.global_selfattn = SelfAttention_transformer_v2(2 * dhid, dropout=self.dropout.get('selfattn', 0.)) <NEW_LINE> for s in slots: <NEW_LINE> <INDENT> setattr(self, '{}_selfattn'.format(s), SelfAttention(din, dropout=self.dropout.get('selfattn', 0.))) <NEW_LINE> <DEDENT> self.slots = slots <NEW_LINE> self.beta_raw = nn.Parameter(torch.Tensor(len(slots))) <NEW_LINE> nn.init.uniform_(self.beta_raw, -0.01, 0.01) <NEW_LINE> <DEDENT> def beta(self, slot): <NEW_LINE> <INDENT> return F.sigmoid(self.beta_raw[self.slots.index(slot)]) <NEW_LINE> <DEDENT> def forward(self, x, x_len, slot, default_dropout=0.2): <NEW_LINE> <INDENT> local_selfattn = getattr(self, '{}_selfattn'.format(slot)) <NEW_LINE> beta = self.beta(slot) <NEW_LINE> local_h = x <NEW_LINE> global_h = x <NEW_LINE> h = x <NEW_LINE> c = F.dropout(local_selfattn(h, x_len), self.dropout.get('local', default_dropout), self.training) * beta + F.dropout(self.global_selfattn(h, x_len), self.dropout.get('global', default_dropout), self.training) * (1-beta) <NEW_LINE> return h, c | the GLAD encoder described in https://arxiv.org/abs/1805.09655. | 6259908fd8ef3951e32c8cae |
class SlimtaError(Exception): <NEW_LINE> <INDENT> pass | The base exception for all custom errors in :mod:`slimta`. | 6259908f656771135c48ae82 |
class TestTxtStatussMessages(unittest.TestCase): <NEW_LINE> <INDENT> def test_valid_messages(self): <NEW_LINE> <INDENT> for message_file in glob.glob("../status/*-OK-*.txt"): <NEW_LINE> <INDENT> with open(message_file) as message: <NEW_LINE> <INDENT> for header in message.readlines(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logging.info("Test : %s ...", message_file) <NEW_LINE> self.assertTrue(is_header_valid(header)) <NEW_LINE> logging.info("Test : %s OK", message_file) <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> logging.error("Test : %s KO", message_file) <NEW_LINE> raise type(error)(error.message + " %s" % message_file) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def test_invalid_messages(self): <NEW_LINE> <INDENT> for message_file in glob.glob("../status/*-KO-*.txt"): <NEW_LINE> <INDENT> with open(message_file) as message: <NEW_LINE> <INDENT> for header in message.readlines(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logging.info("Test : %s ...", message_file) <NEW_LINE> self.assertFalse(is_header_valid(header)) <NEW_LINE> logging.info("Test : %s OK", message_file) <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> logging.error("Test : %s KO", message_file) <NEW_LINE> raise type(error)(error.message + " %s" % message_file) | Test the conformance of Status message test vectors. | 6259908f7cff6e4e811b76e7 |
class DataGenerator(keras.utils.Sequence): <NEW_LINE> <INDENT> def __init__(self, list_IDs, labels, filepaths, cache=True, shuffle=True): <NEW_LINE> <INDENT> self.labels = labels <NEW_LINE> self.filepaths = filepaths <NEW_LINE> self.list_IDs = list_IDs <NEW_LINE> self.shuffle = shuffle <NEW_LINE> self.cache = cache <NEW_LINE> self.cached = np.empty(len(self.filepaths), dtype=object) <NEW_LINE> self.on_epoch_end() <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.list_IDs) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> ID = self.indexes[index] <NEW_LINE> X = [] <NEW_LINE> if self.cached[ID] is not None: <NEW_LINE> <INDENT> X = self.cached[ID] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> X = self.load_file(ID) <NEW_LINE> if self.cache: <NEW_LINE> <INDENT> self.cached[ID] = X <NEW_LINE> <DEDENT> <DEDENT> y = self.labels[ID] <NEW_LINE> return np.array([X]), np.array([y]) <NEW_LINE> <DEDENT> def load_file(self, ID): <NEW_LINE> <INDENT> xx = np.load(self.filepaths[ID])["clip"] <NEW_LINE> XX = np.empty((len(xx),) + IMG_DIMS) <NEW_LINE> for i in range(len(xx)): <NEW_LINE> <INDENT> XX[i] = resize(xx[i], IMG_SIZE).astype("float16") <NEW_LINE> <DEDENT> return XX <NEW_LINE> <DEDENT> def extend_clip(self, clip): <NEW_LINE> <INDENT> clip_shape = clip.shape <NEW_LINE> extended_len = MAX_LEN <NEW_LINE> if clip_shape[0] >= extended_len: <NEW_LINE> <INDENT> return clip[:extended_len] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if clip_shape[0] != 0: <NEW_LINE> <INDENT> extension = clip[clip_shape[0] - 1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> extension = np.zeros(IMG_DIMS) <NEW_LINE> <DEDENT> return np.concatenate([clip, np.tile(extension, (MAX_LEN - clip_shape[0],1,1,1))]) <NEW_LINE> <DEDENT> <DEDENT> def on_epoch_end(self): <NEW_LINE> <INDENT> self.indexes = np.copy(self.list_IDs) <NEW_LINE> if self.shuffle: <NEW_LINE> <INDENT> np.random.shuffle(self.indexes) | Generates data for Keras | 6259908fad47b63b2c5a94f5 |
class UserCreate(generics.CreateAPIView): <NEW_LINE> <INDENT> serializer_class = UserSerializer <NEW_LINE> authentication_classes = () <NEW_LINE> permission_classes = () | Create a User | 6259908f099cdd3c6367624c |
class Arrangement: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> async def async_save(connection: iterm2.connection.Connection, name: str): <NEW_LINE> <INDENT> result = await iterm2.rpc.async_save_arrangement(connection, name) <NEW_LINE> status = result.saved_arrangement_response.status <NEW_LINE> if status != iterm2.api_pb2.CreateTabResponse.Status.Value("OK"): <NEW_LINE> <INDENT> raise SavedArrangementException( iterm2.api_pb2.SavedArrangementResponse.Status.Name( result.saved_arrangement_response.status)) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> async def async_restore( connection: iterm2.connection.Connection, name: str, window_id: typing.Optional[str] = None): <NEW_LINE> <INDENT> result = await iterm2.rpc.async_restore_arrangement(connection, name, window_id) <NEW_LINE> status = result.saved_arrangement_response.status <NEW_LINE> if status != iterm2.api_pb2.CreateTabResponse.Status.Value("OK"): <NEW_LINE> <INDENT> raise SavedArrangementException( iterm2.api_pb2.SavedArrangementResponse.Status.Name( result.saved_arrangement_response.status)) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> async def async_list( connection: iterm2.connection.Connection) -> typing.List[str]: <NEW_LINE> <INDENT> iterm2.capabilities.check_supports_list_saved_arrangements(connection) <NEW_LINE> result = await iterm2.rpc.async_list_arrangements(connection) <NEW_LINE> status = result.saved_arrangement_response.status <NEW_LINE> if status != iterm2.api_pb2.CreateTabResponse.Status.Value("OK"): <NEW_LINE> <INDENT> raise SavedArrangementException( iterm2.api_pb2.SavedArrangementResponse.Status.Name( result.saved_arrangement_response.status)) <NEW_LINE> <DEDENT> return result.saved_arrangement_response.names | Provides access to saved arrangements. | 6259908f5fdd1c0f98e5fc1e |
class Room(BaseModel): <NEW_LINE> <INDENT> schema = RoomSchema() <NEW_LINE> fields = ( ('_id', None), ('room_name', None), ('members', []), ('created', BaseModel.default_current_time), ('is_active', True), ) <NEW_LINE> def __str__(self) -> str: <NEW_LINE> <INDENT> instance_id = None <NEW_LINE> if hasattr(self, "_id"): <NEW_LINE> <INDENT> instance_id = self.id <NEW_LINE> <DEDENT> return f'id:{instance_id}, room name:{self.room_name}' <NEW_LINE> <DEDENT> async def save(self) -> None: <NEW_LINE> <INDENT> if not hasattr(self, 'errors'): <NEW_LINE> <INDENT> raise RuntimeError('you must call is_valid() before save instance') <NEW_LINE> <DEDENT> if self.errors: <NEW_LINE> <INDENT> raise RoomValidationError(self.errors) <NEW_LINE> <DEDENT> if hasattr(self, '_id'): <NEW_LINE> <INDENT> data = self.loads() <NEW_LINE> room_id = data.pop('_id') <NEW_LINE> await room_collection.replace_one({'_id': room_id}, data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = await room_collection.insert_one(self.loads()) <NEW_LINE> self._id = result.inserted_id <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> async def get_rooms(cls, user) -> List['Room']: <NEW_LINE> <INDENT> rooms = [] <NEW_LINE> schema = RoomSchema() <NEW_LINE> async for document in room_collection.find({'members': user.id}): <NEW_LINE> <INDENT> document['_id'] = str(document['_id']) <NEW_LINE> rooms.append(cls(**schema.load(document).data)) <NEW_LINE> <DEDENT> return rooms <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def get_room(cls, **filters) -> 'Room': <NEW_LINE> <INDENT> data = await room_collection.find_one(filters) <NEW_LINE> schema = RoomSchema() <NEW_LINE> if schema.load(data).data is None: <NEW_LINE> <INDENT> raise RoomDoesNotExists <NEW_LINE> <DEDENT> data['_id'] = str(data['_id']) <NEW_LINE> return cls(**schema.load(data).data) <NEW_LINE> <DEDENT> async def get_messages(self) -> List['Message']: <NEW_LINE> <INDENT> return await Message.get_messages(self._id) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def get_json_rooms(cls, user) -> List[Dict]: <NEW_LINE> <INDENT> data = await cls.get_rooms(user) <NEW_LINE> result = [] <NEW_LINE> for room in data: <NEW_LINE> <INDENT> result.append(room.loads()) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> async def get_last_message(room_id) -> 'Message': <NEW_LINE> <INDENT> schema = MessageSchema() <NEW_LINE> document = await message_collection.find_one({'room_id': room_id}, sort=[('created', -1)]) <NEW_LINE> instance = Message(**schema.load(document).data) <NEW_LINE> return instance | Room for manipulation in code | 6259908f4a966d76dd5f0b8c |
class UserChangeForm(forms.ModelForm): <NEW_LINE> <INDENT> password = ReadOnlyPasswordHashField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = MyUser <NEW_LINE> fields = ('email', 'password', 'nick_name','real_name','work','sex','height','weight','phone_num', 'is_active', 'is_admin') <NEW_LINE> <DEDENT> def clean_password(self): <NEW_LINE> <INDENT> return self.initial["password"] | A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field. | 6259908fd8ef3951e32c8cb1 |
class TotalUUXSlayer(tf.keras.layers.Layer): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TotalUUXSlayer, self).__init__(dtype='float64') <NEW_LINE> self.F = BHDVCS() <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> return self.F.TotalUUXS(inputs[:, :8], inputs[:, 8], inputs[:, 9], inputs[:, 10]) | class for incorporating TotalUUXS function into tensorflow layer | 6259908f656771135c48ae85 |
class loggedException(Exception): <NEW_LINE> <INDENT> pass | Raised after an exception has been caught and logged in a checking class, allowing execution to fall back to the loop over files. | 6259908ff9cc0f698b1c6120 |
class WeChatButtonError(Exception): <NEW_LINE> <INDENT> pass | An wechat button error occurred. | 6259908f656771135c48ae86 |
class Not(object): <NEW_LINE> <INDENT> def __init__(self, argument): <NEW_LINE> <INDENT> self.argument = argument | Negation | 6259908fadb09d7d5dc0c205 |
class Backlight(enum.Enum): <NEW_LINE> <INDENT> ON = 'on' <NEW_LINE> OFF = 'off' <NEW_LINE> TOGGLE = 'toggle' <NEW_LINE> OPEN = 'open' <NEW_LINE> BLINK = 'blink' <NEW_LINE> FLASH = 'flash' | Enumeration listing all possible backlight settings that can be
set as an value for the -backlight argument | 6259908f283ffb24f3cf554b |
class NumArray: <NEW_LINE> <INDENT> def __init__(self, nums: List[int]): <NEW_LINE> <INDENT> self.nums = [0]*len(nums) <NEW_LINE> self.tree = [0]*(len(nums)+1) <NEW_LINE> for i, num in enumerate(nums): <NEW_LINE> <INDENT> self.update(i, num) <NEW_LINE> <DEDENT> <DEDENT> def update(self, i: int, val: int) -> None: <NEW_LINE> <INDENT> def helper(x, delta): <NEW_LINE> <INDENT> while x < len(self.tree): <NEW_LINE> <INDENT> self.tree[x] += delta <NEW_LINE> x += x & -x <NEW_LINE> <DEDENT> <DEDENT> helper(i+1, val-self.nums[i]) <NEW_LINE> self.nums[i] = val <NEW_LINE> <DEDENT> def sumRange(self, i: int, j: int) -> int: <NEW_LINE> <INDENT> def helper(x): <NEW_LINE> <INDENT> s = 0 <NEW_LINE> while x > 0: <NEW_LINE> <INDENT> s += self.tree[x] <NEW_LINE> x -= x & -x <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> return helper(j+1) - helper(i+1-1) | Binary Index Tree | 6259908f97e22403b383cba3 |
class Package: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> assert isinstance(name, str) <NEW_LINE> for tag in _tags: <NEW_LINE> <INDENT> if tag.attr_type is list and tag.name in ["build_requires", "requires", "conflicts", "obsoletes", "provides"]: <NEW_LINE> <INDENT> setattr(self, tag.name, tag.attr_type()) <NEW_LINE> <DEDENT> <DEDENT> self.name = name <NEW_LINE> self.is_subpackage = False <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Package('{}')".format(self.name) | Represents a single package in a RPM spec file.
Each spec file describes at least one package and can contain one or more subpackages (described
by the %package directive). For example, consider following spec file::
Name: foo
Version: 0.1
%description
%{name} is the library that everyone needs.
%package devel
Summary: Header files, libraries and development documentation for %{name}
Group: Development/Libraries
Requires: %{name}%{?_isa} = %{version}-%{release}
%description devel
This package contains the header files, static libraries, and development
documentation for %{name}. If you like to develop programs using %{name}, you
will need to install %{name}-devel.
%package -n bar
Summary: A command line client for foo.
License: GPLv2+
%description -n bar
This package contains a command line client for foo.
This spec file will create three packages:
* A package named foo, the base package.
* A package named foo-devel, a subpackage.
* A package named bar, also a subpackage, but without the foo- prefix.
As you can see above, the name of a subpackage normally includes the main package name. When the
-n option is added to the %package directive, the prefix of the base package name is omitted and
a completely new name is used. | 6259908f8a349b6b43687f0b |
class Max(nn.Module): <NEW_LINE> <INDENT> def __init__(self, axis=-1, keepdims=False): <NEW_LINE> <INDENT> self.axis = axis <NEW_LINE> self.keepdims = keepdims <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def __call__(self, x, seq_len=None): <NEW_LINE> <INDENT> if seq_len is not None: <NEW_LINE> <INDENT> mask = compute_mask(x, seq_len, 0, self.axis) <NEW_LINE> x = (x + torch.log(mask)) <NEW_LINE> <DEDENT> x = x.max(self.axis, keepdim=self.keepdims) <NEW_LINE> return x | >>> seq_axis = 1
>>> x = torch.cumsum(torch.ones((3,7,4)), dim=seq_axis)
>>> Max(axis=seq_axis)(x, seq_len=[4,5,6]) | 6259908fa05bb46b3848bf7b |
class sale_confirm(osv.osv_memory): <NEW_LINE> <INDENT> _name = "sale.confirm" <NEW_LINE> _description = "Confirm the selected quotations" <NEW_LINE> def sale_confirm(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> wf_service = netsvc.LocalService('workflow') <NEW_LINE> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> pool_obj = pooler.get_pool(cr.dbname) <NEW_LINE> data_inv = pool_obj.get('sale.order').read(cr, uid, context['active_ids'], ['state'], context=context) <NEW_LINE> for record in data_inv: <NEW_LINE> <INDENT> if record['state'] not in ('draft'): <NEW_LINE> <INDENT> raise osv.except_osv(_('Warning!'), _("Selected quotation(s) cannot be confirmed as they are not in 'Draft'.")) <NEW_LINE> <DEDENT> wf_service.trg_validate(uid, 'sale.order', record['id'], 'order_confirm', cr) <NEW_LINE> <DEDENT> return {'type': 'ir.actions.act_window_close'} | This wizard will confirm the all the selected draft quotation | 6259908f3617ad0b5ee07dfe |
Subsets and Splits