code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class CSV(FormattedStats): <NEW_LINE> <INDENT> def __init__(self, stats: dtypes.Stats): <NEW_LINE> <INDENT> super().__init__(stats) <NEW_LINE> self._metadata_header = _METDATA_MAPPING.keys() <NEW_LINE> self._metadata_row = [getattr(stats, v) for v in _METDATA_MAPPING.values()] <NEW_LINE> self._data_header = _STATS_MAPPING.keys() <NEW_LINE> self._data_row = [getattr(stats, v) for v in _STATS_MAPPING.values()] <NEW_LINE> <DEDENT> def resource(self, append: bool = False) -> str: <NEW_LINE> <INDENT> csv_str = io.StringIO(newline="") <NEW_LINE> writer = csv.writer(csv_str) <NEW_LINE> if not append: <NEW_LINE> <INDENT> writer.writerow(list(self._metadata_header) + list(self._data_header)) <NEW_LINE> <DEDENT> writer.writerow(list(self._metadata_row) + list(self._data_row)) <NEW_LINE> return csv_str.getvalue() <NEW_LINE> <DEDENT> def save(self, file: Union[str, pathlib.Path], append: bool = True) -> None: <NEW_LINE> <INDENT> if not append and os.path.exists(file): <NEW_LINE> <INDENT> raise FileExistsError( f"{file} already exists but 'append' is set to False." ) <NEW_LINE> <DEDENT> mode = "a" if append else "w" <NEW_LINE> if append and not os.path.exists(file): <NEW_LINE> <INDENT> mode = "w" <NEW_LINE> append = False <NEW_LINE> <DEDENT> with open(file, mode, newline="") as f: <NEW_LINE> <INDENT> f.write(self.resource(append))
Formats `dtypes.Stats` to CSV. Args: stats (dtypes.Stats): A benchmarking result. Raises: TypeError: If `stats` is not of type `dtypes.Stats`.
62599047711fe17d825e165f
class AdamaxOptimizer(optimizer.Optimizer): <NEW_LINE> <INDENT> def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, use_locking=False, name="Adamax"): <NEW_LINE> <INDENT> super(AdamaxOptimizer, self).__init__(use_locking, name) <NEW_LINE> self._lr = learning_rate <NEW_LINE> self._beta1 = beta1 <NEW_LINE> self._beta2 = beta2 <NEW_LINE> self._lr_t = None <NEW_LINE> self._beta1_t = None <NEW_LINE> self._beta2_t = None <NEW_LINE> <DEDENT> def _prepare(self): <NEW_LINE> <INDENT> self._lr_t = ops.convert_to_tensor(self._lr, name="learning_rate") <NEW_LINE> self._beta1_t = ops.convert_to_tensor(self._beta1, name="beta1") <NEW_LINE> self._beta2_t = ops.convert_to_tensor(self._beta2, name="beta2") <NEW_LINE> <DEDENT> def _create_slots(self, var_list): <NEW_LINE> <INDENT> for v in var_list: <NEW_LINE> <INDENT> self._zeros_slot(v, "m", self._name) <NEW_LINE> self._zeros_slot(v, "v", self._name) <NEW_LINE> <DEDENT> <DEDENT> def _apply_dense(self, grad, var): <NEW_LINE> <INDENT> lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype) <NEW_LINE> beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype) <NEW_LINE> beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype) <NEW_LINE> if var.dtype.base_dtype == tf.float16: <NEW_LINE> <INDENT> eps = 1e-7 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> eps = 1e-8 <NEW_LINE> <DEDENT> v = self.get_slot(var, "v") <NEW_LINE> v_t = v.assign(beta1_t * v + (1. - beta1_t) * grad) <NEW_LINE> m = self.get_slot(var, "m") <NEW_LINE> m_t = m.assign(tf.maximum(beta2_t * m + eps, tf.abs(grad))) <NEW_LINE> g_t = v_t / m_t <NEW_LINE> var_update = state_ops.assign_sub(var, lr_t * g_t) <NEW_LINE> return control_flow_ops.group(*[var_update, m_t, v_t]) <NEW_LINE> <DEDENT> def _apply_sparse(self, grad, var): <NEW_LINE> <INDENT> raise NotImplementedError("Sparse gradient updates are not supported.")
Optimizer that implements the Adamax algorithm. See [Kingma et. al., 2014](http://arxiv.org/abs/1412.6980) ([pdf](http://arxiv.org/pdf/1412.6980.pdf)). @@__init__
62599047a79ad1619776b403
class TestInvest: <NEW_LINE> <INDENT> @pytest.mark.parametrize('case', InvestData.error_data) <NEW_LINE> def test_invest_error_info_btn(self, case, invest_fixture): <NEW_LINE> <INDENT> invest_page = invest_fixture[0] <NEW_LINE> invest_page.input_invest_amount(case['money']) <NEW_LINE> res = invest_page.get_invest_btn_error_info() <NEW_LINE> expected = case['expected'] <NEW_LINE> assert res == expected <NEW_LINE> <DEDENT> @pytest.mark.parametrize('case', InvestData.error_popup_data) <NEW_LINE> def test_invest_error_window_info(self, case, invest_fixture): <NEW_LINE> <INDENT> invest_page = invest_fixture[0] <NEW_LINE> invest_page.input_invest_amount(case['money']) <NEW_LINE> invest_page.click_invest() <NEW_LINE> res = invest_page.get_window_error_info() <NEW_LINE> invest_page.click_close_error_window() <NEW_LINE> expected = case['expected'] <NEW_LINE> assert res == expected <NEW_LINE> <DEDENT> @pytest.mark.parametrize('case', InvestData.success_data) <NEW_LINE> def test_invest_success(self, case, invest_fixture): <NEW_LINE> <INDENT> invest_page, user_page = invest_fixture <NEW_LINE> start_amount = invest_page.get_invest_input_amount() <NEW_LINE> invest_page.input_invest_amount(case['money']) <NEW_LINE> invest_page.click_invest() <NEW_LINE> res = invest_page.get_window_success_info() <NEW_LINE> expected = case['expected'] <NEW_LINE> assert res == expected <NEW_LINE> invest_page.click_window_active() <NEW_LINE> end_amount = user_page.get_user_amount() <NEW_LINE> res_change_amount = float(start_amount) - float(end_amount) <NEW_LINE> assert res_change_amount == case['money']
测试投资用例类
6259904716aa5153ce401870
class GeneralizedMeanPooling(nn.Module): <NEW_LINE> <INDENT> def __init__(self, norm_type, output_size): <NEW_LINE> <INDENT> super(GeneralizedMeanPooling, self).__init__() <NEW_LINE> self.output_size = output_size <NEW_LINE> self.norm_type = norm_type <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> out = F.adaptive_avg_pool2d(input.pow(self.norm_type), self.output_size) <NEW_LINE> return out.pow(1. / self.norm_type) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ + '(' + str(self.norm_type) + ', ' + 'output_size=' + str(self.output_size) + ')'
Applies a 2D power-average adaptive pooling over an input signal composed of several input planes. The function computed is: :math:`f(X) = pow(sum(pow(X, p)), 1/p)` - At p = infinity, one gets Max Pooling - At p = 1, one gets Average Pooling The output is of size H x W, for any input size. The number of output features is equal to the number of input planes. Args: output_size: the target output size of the image of the form H x W. Can be a tuple (H, W) or a single H for a square image H x H H and W can be either a ``int``, or ``None`` which means the size will be the same as that of the input.
62599047462c4b4f79dbcd82
class Users(object): <NEW_LINE> <INDENT> def configure_admin(self): <NEW_LINE> <INDENT> hookenv.log("Configuring user for jenkins") <NEW_LINE> admin = self._admin_data() <NEW_LINE> api = Api() <NEW_LINE> api.update_password(admin.username, admin.password) <NEW_LINE> host.write_file( paths.ADMIN_PASSWORD, admin.password.encode("utf-8"), owner="root", group="root", perms=0o0600) <NEW_LINE> if not os.path.exists(paths.LAST_EXEC): <NEW_LINE> <INDENT> host.write_file( paths.LAST_EXEC, "{}\n".format(api.version()).encode("utf-8"), owner="jenkins", group="nogroup") <NEW_LINE> <DEDENT> <DEDENT> def _admin_data(self): <NEW_LINE> <INDENT> config = hookenv.config() <NEW_LINE> username = config["username"] <NEW_LINE> password = config["password"] <NEW_LINE> if not password: <NEW_LINE> <INDENT> password = host.pwgen(length=15) <NEW_LINE> config["_generated-password"] = password <NEW_LINE> <DEDENT> return _User(username, password)
Manage Jenkins users.
625990471f5feb6acb163f79
class PresentationModel(qc.QObject): <NEW_LINE> <INDENT> combo_symbol_text: Dict[str, Sequence[SymbolText]] <NEW_LINE> edited = qc.Signal() <NEW_LINE> def __init__(self, cfg: DumpableAttrs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.cfg = cfg <NEW_LINE> self.update_widget: Dict[str, List[WidgetUpdater]] = defaultdict(list) <NEW_LINE> <DEDENT> def __getitem__(self, item: str) -> Any: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return getattr(self, item) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return rgetattr(self.cfg, item) <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.edited.emit() <NEW_LINE> if hasattr(type(self), key): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> elif rhasattr(self.cfg, key): <NEW_LINE> <INDENT> rsetattr(self.cfg, key, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError(f"cannot set attribute {key} on {obj_name(self)}()") <NEW_LINE> <DEDENT> <DEDENT> def set_cfg(self, cfg: DumpableAttrs): <NEW_LINE> <INDENT> self.cfg = cfg <NEW_LINE> for updater_list in self.update_widget.values(): <NEW_LINE> <INDENT> _call_all(updater_list) <NEW_LINE> <DEDENT> <DEDENT> def update_all_bound(self, key: str): <NEW_LINE> <INDENT> _call_all(self.update_widget[key])
Key-value MVP presentation-model. Qt's built-in model-view framework expects all models to take the form of a database-style numbered [row, column] structure, whereas my model takes the form of a key-value struct exposed as a form. Each GUI BoundWidget generally reads/writes `widget.pmodel[widget.path]`. To access cfg.foo.bar, set BoundWidget's path to read/write pmodel["foo.bar"] or pmodel["foo__bar"]. To create a GUI field not directly mapping to `cfg`, define a property named "foo__baz", then set BoundWidget's path to read/write pmodel["foo.baz"] or pmodel["foo__baz"].
6259904710dbd63aa1c71f5e
class RoomMaster(): <NEW_LINE> <INDENT> def __init__(self, rid, title, url, mrt, publishtime): <NEW_LINE> <INDENT> self.rid = rid; <NEW_LINE> self.title = title; <NEW_LINE> self.url = url; <NEW_LINE> self.mrt = mrt; <NEW_LINE> self.publishtime = publishtime;
classdocs
625990473c8af77a43b688ff
class Methods(Helper): <NEW_LINE> <INDENT> mode = HelperMode.lowerCamelCase <NEW_LINE> GET_UPDATES = Item() <NEW_LINE> SET_WEBHOOK = Item() <NEW_LINE> DELETE_WEBHOOK = Item() <NEW_LINE> GET_WEBHOOK_INFO = Item() <NEW_LINE> GET_ME = Item() <NEW_LINE> SEND_MESSAGE = Item() <NEW_LINE> FORWARD_MESSAGE = Item() <NEW_LINE> SEND_PHOTO = Item() <NEW_LINE> SEND_AUDIO = Item() <NEW_LINE> SEND_DOCUMENT = Item() <NEW_LINE> SEND_VIDEO = Item() <NEW_LINE> SEND_VOICE = Item() <NEW_LINE> SEND_VIDEO_NOTE = Item() <NEW_LINE> SEND_MEDIA_GROUP = Item() <NEW_LINE> SEND_LOCATION = Item() <NEW_LINE> EDIT_MESSAGE_LIVE_LOCATION = Item() <NEW_LINE> STOP_MESSAGE_LIVE_LOCATION = Item() <NEW_LINE> SEND_VENUE = Item() <NEW_LINE> SEND_CONTACT = Item() <NEW_LINE> SEND_CHAT_ACTION = Item() <NEW_LINE> GET_USER_PROFILE_PHOTOS = Item() <NEW_LINE> GET_FILE = Item() <NEW_LINE> KICK_CHAT_MEMBER = Item() <NEW_LINE> UNBAN_CHAT_MEMBER = Item() <NEW_LINE> RESTRICT_CHAT_MEMBER = Item() <NEW_LINE> PROMOTE_CHAT_MEMBER = Item() <NEW_LINE> EXPORT_CHAT_INVITE_LINK = Item() <NEW_LINE> SET_CHAT_PHOTO = Item() <NEW_LINE> DELETE_CHAT_PHOTO = Item() <NEW_LINE> SET_CHAT_TITLE = Item() <NEW_LINE> SET_CHAT_DESCRIPTION = Item() <NEW_LINE> PIN_CHAT_MESSAGE = Item() <NEW_LINE> UNPIN_CHAT_MESSAGE = Item() <NEW_LINE> LEAVE_CHAT = Item() <NEW_LINE> GET_CHAT = Item() <NEW_LINE> GET_CHAT_ADMINISTRATORS = Item() <NEW_LINE> GET_CHAT_MEMBERS_COUNT = Item() <NEW_LINE> GET_CHAT_MEMBER = Item() <NEW_LINE> SET_CHAT_STICKER_SET = Item() <NEW_LINE> DELETE_CHAT_STICKER_SET = Item() <NEW_LINE> ANSWER_CALLBACK_QUERY = Item() <NEW_LINE> EDIT_MESSAGE_TEXT = Item() <NEW_LINE> EDIT_MESSAGE_CAPTION = Item() <NEW_LINE> EDIT_MESSAGE_REPLY_MARKUP = Item() <NEW_LINE> DELETE_MESSAGE = Item() <NEW_LINE> SEND_STICKER = Item() <NEW_LINE> GET_STICKER_SET = Item() <NEW_LINE> UPLOAD_STICKER_FILE = Item() <NEW_LINE> CREATE_NEW_STICKER_SET = Item() <NEW_LINE> ADD_STICKER_TO_SET = Item() <NEW_LINE> SET_STICKER_POSITION_IN_SET = Item() <NEW_LINE> DELETE_STICKER_FROM_SET = Item() <NEW_LINE> ANSWER_INLINE_QUERY = Item() <NEW_LINE> SEND_INVOICE = Item() <NEW_LINE> ANSWER_SHIPPING_QUERY = Item() <NEW_LINE> ANSWER_PRE_CHECKOUT_QUERY = Item() <NEW_LINE> SEND_GAME = Item() <NEW_LINE> SET_GAME_SCORE = Item() <NEW_LINE> GET_GAME_HIGH_SCORES = Item() <NEW_LINE> @staticmethod <NEW_LINE> def api_url(token, method): <NEW_LINE> <INDENT> return API_URL.format(token=token, method=method) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def file_url(token, path): <NEW_LINE> <INDENT> return FILE_URL.format(token=token, path=path)
Helper for Telegram API Methods listed on https://core.telegram.org/bots/api List is updated to Bot API 3.6
6259904707d97122c4218025
class ReaderError(Exception): <NEW_LINE> <INDENT> pass
Exception class for Readers
6259904707f4c71912bb07b6
class LemonldapAuthenticationMiddleware(object): <NEW_LINE> <INDENT> headers = [ ('username', 'HTTP_AUTH_USER', True), ('firstname', 'HTTP_AUTH_FIRSTNAME', False, None), ('lastname', 'HTTP_AUTH_LASTNAME', False, None), ('mail', 'HTTP_AUTH_MAIL', False, None), ('is_superuser', 'HTTP_AUTH_SUPERUSER', False, 'false'), ('is_staff', 'HTTP_AUTH_STAFF', False, 'false'), ] <NEW_LINE> def __init__(self, get_response): <NEW_LINE> <INDENT> self.get_response = get_response <NEW_LINE> <DEDENT> def __call__(self, request): <NEW_LINE> <INDENT> response = self.get_response(request) <NEW_LINE> self.process_request(request) <NEW_LINE> return response <NEW_LINE> <DEDENT> def process_request(self, request): <NEW_LINE> <INDENT> if not hasattr(request, 'user'): <NEW_LINE> <INDENT> raise ImproperlyConfigured( "The Django LemonLDAP auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE_CLASSES setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the LemonLDAPMiddleware class.") <NEW_LINE> <DEDENT> user_infos = {} <NEW_LINE> for header in self.headers: <NEW_LINE> <INDENT> if header[2]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_infos[header[0]] = request.META[header[1]] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> user_infos[header[0]] = request.META.get(header[1], header[3] if 4 == len(header) else None) <NEW_LINE> <DEDENT> <DEDENT> if request.user.is_authenticated: <NEW_LINE> <INDENT> if request.user.username == self.clean_username(user_infos['username'], request): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> user = auth.authenticate(request, lemonldap_user=user_infos) <NEW_LINE> if user: <NEW_LINE> <INDENT> request.user = user <NEW_LINE> auth.login(request, user) <NEW_LINE> <DEDENT> <DEDENT> def clean_username(self, username, request): <NEW_LINE> <INDENT> backend_str = request.session[auth.BACKEND_SESSION_KEY] <NEW_LINE> backend = auth.load_backend(backend_str) <NEW_LINE> try: <NEW_LINE> <INDENT> username = backend.clean_username(username) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return username
HTTP headers used : - user_infos key name - header key name - is required - default value if not provided
62599047d99f1b3c44d06a24
class ImageList(object): <NEW_LINE> <INDENT> def __init__(self, path_to_dir=None): <NEW_LINE> <INDENT> self.path_to_dir = path_to_dir <NEW_LINE> self.updateFileList() <NEW_LINE> <DEDENT> def updateFileList(self, path_to_new_dir=None): <NEW_LINE> <INDENT> if path_to_new_dir is not None: <NEW_LINE> <INDENT> self.path_to_dir = path_to_new_dir <NEW_LINE> <DEDENT> if self.path_to_dir is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.files = sorted([f for f in os.listdir(self.path_to_dir) if (os.path.isfile(os.path.join(self.path_to_dir, f)) and f[-4:] == '.tif')]) <NEW_LINE> if len(self.files) is 0: <NEW_LINE> <INDENT> raise ImageListError('No .tif files in this directory.') <NEW_LINE> <DEDENT> abs2_files = [f for f in self.files if f[-11:]=='Frame-3.tif'] <NEW_LINE> if(len(abs2_files) > 0): <NEW_LINE> <INDENT> if len(self.files) % 3 is not 0: <NEW_LINE> <INDENT> raise ImageListError('2 Aborption files per ref detected.' ' Yet total number of files is not' ' divisible by 3. Something is wrong.') <NEW_LINE> <DEDENT> self.abs0 = [os.path.join(self.path_to_dir, f) for f in self.files[::3]] <NEW_LINE> self.abs1 = [os.path.join(self.path_to_dir, f) for f in self.files[1:][::3]] <NEW_LINE> self.ref = [os.path.join(self.path_to_dir, f) for f in self.files[2:][::3]] <NEW_LINE> self.absorption_files = [x for t in zip(self.abs0, self.abs1) for x in t] <NEW_LINE> self.reference_files = [x for t in zip(self.ref, self.ref) for x in t] <NEW_LINE> short_names1 = [f[:-6]+' 1' for f in self.files[::3]] <NEW_LINE> short_names2 = [f[:-6]+' 2' for f in self.files[1:][::3]] <NEW_LINE> self.short_names = [x for t in zip(short_names1, short_names2) for x in t] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(self.files) % 2 is not 0: <NEW_LINE> <INDENT> raise ImageListError('Odd number of files in the directory.' ' Something is wrong.') <NEW_LINE> <DEDENT> self.absorption_files = [os.path.join(self.path_to_dir, f) for f in self.files[::2]] <NEW_LINE> self.reference_files = [os.path.join(self.path_to_dir, f) for f in self.files[1:][::2]] <NEW_LINE> self.short_names = [f[:-11] for f in self.files[::2]] <NEW_LINE> for a, r in zip(self.absorption_files, self.reference_files): <NEW_LINE> <INDENT> abs_name = re.split('Frame-1.tif', a)[0] <NEW_LINE> ref_name = re.split('Frame-2.tif', r)[0] <NEW_LINE> if abs_name != ref_name: <NEW_LINE> <INDENT> raise ImageListError('Absorption and Reference image names do' 'not match. Check for missing files.') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.n_images = len(self.absorption_files)
Lists absorption and reference images in a directory
62599047d6c5a102081e34a0
class Role: <NEW_LINE> <INDENT> class RoleState: <NEW_LINE> <INDENT> def __init__(self, hp, mp): <NEW_LINE> <INDENT> self.hp = hp <NEW_LINE> self.mp = mp <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, role_state): <NEW_LINE> <INDENT> self.role_state = role_state <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> print('HP:', self.role_state.hp) <NEW_LINE> print('MP:', self.role_state.mp) <NEW_LINE> <DEDENT> def save_status(self): <NEW_LINE> <INDENT> return Record(deepcopy(self.role_state)) <NEW_LINE> <DEDENT> def load_status(self, backup): <NEW_LINE> <INDENT> self.role_state = backup
Originator class. Here is a game role for saving the role state.
6259904791af0d3eaad3b1a9
class ShoptoolsTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_sample(self): <NEW_LINE> <INDENT> self.assertEqual(1, 1)
Integration tests for shoptools apps.
6259904726068e7796d4dccb
class AdjudicatorForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Adjudicator <NEW_LINE> fields = ('ccid', 'first_name', 'last_name', 'email', 'lang_pref') <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(AdjudicatorForm, self).__init__(*args, **kwargs)
Unrestricted Adjudicator form containing all fields
6259904763b5f9789fe864f1
class EndMessage(StanzaMessage): <NEW_LINE> <INDENT> pass
Ending message and a stanza
62599047a79ad1619776b405
class TestTransactionStamp(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.stamp = transactions.TransactionStamp(30, "master_id", 1) <NEW_LINE> <DEDENT> def test_to_json_returns_valid_json(self): <NEW_LINE> <INDENT> self.assertEqual( self.stamp.to_json(), '{"processing_time": 1, "fees": 30, ' '"master_id": "master_id"}' ) <NEW_LINE> <DEDENT> def test_from_json_returns_original(self): <NEW_LINE> <INDENT> stamp_2 = transactions.TransactionStamp.from_json(self.stamp.to_json()) <NEW_LINE> self.assertDictEqual(self.stamp.__dict__, stamp_2.__dict__) <NEW_LINE> <DEDENT> def test_from_json_returns_none_in_case_of_invalid_json(self): <NEW_LINE> <INDENT> self.assertIsNone(transactions.TransactionStamp.from_json("")) <NEW_LINE> self.assertIsNone(transactions.TransactionStamp.from_json(None)) <NEW_LINE> self.assertIsNone(transactions.TransactionStamp.from_json("qdsfdhgrh")) <NEW_LINE> <DEDENT> def test_from_dict_returns_none_if_missing_attribute(self): <NEW_LINE> <INDENT> self.assertIsNone(transactions.TransactionStamp.from_dict({ 'fees': 30, "master_id": "master" })) <NEW_LINE> <DEDENT> def test_str_is_implemented(self): <NEW_LINE> <INDENT> str(self.stamp)
Tests the TransactionStamp class.
6259904745492302aabfd857
class CPFPHookScriptTemplate(ScriptTemplate): <NEW_LINE> <INDENT> script_template = "OP_1" <NEW_LINE> witness_template_map = {} <NEW_LINE> witness_templates = {}
OP_TRUE -- a simple script for anyone-can-spend.
625990478e05c05ec3f6f81d
@admin.register(Contenido) <NEW_LINE> class ContenidoAdmin(ImportExportModelAdmin): <NEW_LINE> <INDENT> pass
Docstring
62599047b57a9660fecd2e02
class OWLObjectMaxCardinality(OWLObjectCardinalityRestriction): <NEW_LINE> <INDENT> __slots__ = '_cardinality', '_filler', '_property' <NEW_LINE> type_index: Final = 3010 <NEW_LINE> def __init__(self, cardinality: int, property: OWLObjectPropertyExpression, filler: OWLClassExpression): <NEW_LINE> <INDENT> super().__init__(cardinality, property, filler)
Represents a ObjectMaxCardinality restriction in the OWL 2 Specification.
6259904729b78933be26aa85
class Bower(Configurable): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Configurable.__init__(self) <NEW_LINE> Configurable.load(self) <NEW_LINE> self.__web_path = os.path.expanduser("~") + '/.smartrcs/web' <NEW_LINE> <DEDENT> def check_installed(self): <NEW_LINE> <INDENT> return self._config['installed'] <NEW_LINE> <DEDENT> def install_dependencies(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> bower_version = subprocess.check_output(['bower', '--version']) <NEW_LINE> print('Using bower version: %s' % bower_version) <NEW_LINE> os.system('cd %s && bower install' % self.__web_path) <NEW_LINE> self.mark_installed() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> logging.error('Bower is not installed. Web UI won\'t work. Please install it using `npm install -g bower`.') <NEW_LINE> <DEDENT> <DEDENT> def mark_installed(self): <NEW_LINE> <INDENT> self._config['installed'] = True <NEW_LINE> self.save()
The :class:`Bower <Bower>` class. Bower dependency checker and installer
625990478a349b6b436875d1
class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> verbose_name = _("Additional Entity Characteristic or Mark") <NEW_LINE> verbose_name_plural = _("Additional Entity Characteristics or Marks")
RUS: Метаданные класса.
6259904710dbd63aa1c71f60
@dbus_interface(USER_INTERFACE.interface_name) <NEW_LINE> class UIInterface(KickstartModuleInterfaceTemplate): <NEW_LINE> <INDENT> def connect_signals(self): <NEW_LINE> <INDENT> super().connect_signals() <NEW_LINE> self.watch_property("PasswordPolicies", self.implementation.password_policies_changed) <NEW_LINE> <DEDENT> @property <NEW_LINE> def PasswordPolicies(self) -> Dict[Str, Structure]: <NEW_LINE> <INDENT> return PasswordPolicy.to_structure_dict( self.implementation.password_policies ) <NEW_LINE> <DEDENT> @emits_properties_changed <NEW_LINE> def SetPasswordPolicies(self, policies: Dict[Str, Structure]): <NEW_LINE> <INDENT> self.implementation.set_password_policies( PasswordPolicy.from_structure_dict(policies) )
DBus interface for the user interface module.
62599047009cb60464d028ba
class ParseError(Exception): <NEW_LINE> <INDENT> def __init__(self, message: str): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.message <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"ParseError({self.message!r})"
Parsing failure converted to an exception. Raised when ``or_die`` method on ``Failure`` is called. Attributes: message (str): A human-readable error message
6259904707f4c71912bb07b8
class Order(models.Model): <NEW_LINE> <INDENT> WAITING = 'WA' <NEW_LINE> PREPARE = 'PR' <NEW_LINE> READY = 'RE' <NEW_LINE> DELIVER = 'DE' <NEW_LINE> CANCELED = 'CA' <NEW_LINE> ORDER_STATUS_CHOICES = [ (WAITING, 'Waiting'), (PREPARE, 'Prepare'), (READY, 'Ready'), (DELIVER, 'Deliver'), (CANCELED, 'Canceled'), ] <NEW_LINE> product = models.ForeignKey( to=Product, on_delete=models.CASCADE, ) <NEW_LINE> option_value = models.ForeignKey( to=OptionValue, on_delete=models.CASCADE, ) <NEW_LINE> count = models.IntegerField(null=False) <NEW_LINE> status = models.CharField( max_length=2, choices=ORDER_STATUS_CHOICES, default=WAITING, )
model for user orders
6259904763b5f9789fe864f3
class UpdateAuditResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.IsSuccess = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.IsSuccess = params.get("IsSuccess") <NEW_LINE> self.RequestId = params.get("RequestId")
`UpdateAudit` response parameters structure
62599047ec188e330fdf9c23
class RconClient(object): <NEW_LINE> <INDENT> def __init__(self, host, port, timeout=1.0): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.timeout = timeout <NEW_LINE> self.packet_id = itertools.count(1) <NEW_LINE> self.socket = None <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.socket = socket.create_connection((self.host, self.port), self.timeout) <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> self.socket.close() <NEW_LINE> <DEDENT> def send(self, packet): <NEW_LINE> <INDENT> packet.send_to_socket(self.socket) <NEW_LINE> <DEDENT> def recieve(self): <NEW_LINE> <INDENT> response_packet = RconPacket().recieve_from_socket(self.socket) <NEW_LINE> if not response_packet: <NEW_LINE> <INDENT> raise RconClientError("Remote server disconnected") <NEW_LINE> <DEDENT> return response_packet <NEW_LINE> <DEDENT> def authenticate(self, password): <NEW_LINE> <INDENT> auth_packet = RconPacket(next(self.packet_id), SERVERDATA_AUTH, password) <NEW_LINE> self.send(auth_packet) <NEW_LINE> auth_response = self.recieve() <NEW_LINE> if auth_response.packet_type == SERVERDATA_RESPONSE_VALUE: <NEW_LINE> <INDENT> auth_response = self.recieve() <NEW_LINE> <DEDENT> if auth_response.packet_type != SERVERDATA_AUTH_RESPONSE: <NEW_LINE> <INDENT> raise RconClientError('Invalid authentication response type: %s' % auth_response.packet_type) <NEW_LINE> <DEDENT> if auth_response.packet_id == -1: <NEW_LINE> <INDENT> raise RconClientError('Server Response: Invalid Password') <NEW_LINE> <DEDENT> <DEDENT> def exec_command(self, command): <NEW_LINE> <INDENT> command_packet = RconPacket(next(self.packet_id), SERVERDATA_EXECCOMMAND, command) <NEW_LINE> check_packet = RconPacket(next(self.packet_id), SERVERDATA_EXECCOMMAND, "") <NEW_LINE> self.send(command_packet) <NEW_LINE> self.send(check_packet) <NEW_LINE> response_buffer = "" <NEW_LINE> while True: <NEW_LINE> <INDENT> response = self.recieve() <NEW_LINE> if response.packet_id == command_packet.packet_id: <NEW_LINE> <INDENT> response_buffer += response.body <NEW_LINE> <DEDENT> elif response.packet_id == check_packet.packet_id: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RconClientError('Packet response ID: %s does not match request ID: %s' % (response.packet_id, command_packet.packet_id)) <NEW_LINE> <DEDENT> <DEDENT> return response_buffer
A client implementation for the Source RCON Protocol.
6259904723849d37ff852443
class test(compare_db_errors.test): <NEW_LINE> <INDENT> server0 = None <NEW_LINE> server1 = None <NEW_LINE> server2 = None <NEW_LINE> def setup(self, spawn_servers=True): <NEW_LINE> <INDENT> self.server0 = self.servers.get_server(0) <NEW_LINE> if not self.server0.check_version_compat(5, 6, 5): <NEW_LINE> <INDENT> raise MUTLibError("Test requires server version 5.6.5 and later.") <NEW_LINE> <DEDENT> mysqld = _DEFAULT_MYSQL_OPTS.format(self.servers.view_next_port()) <NEW_LINE> self.server1 = self.servers.spawn_server("compare_db_srv1_ansi_quotes", mysqld, True) <NEW_LINE> mysqld = _DEFAULT_MYSQL_OPTS.format(self.servers.view_next_port()) <NEW_LINE> self.server2 = self.servers.spawn_server("compare_db_srv2_ansi_quotes", mysqld, True) <NEW_LINE> if self.server1.select_variable("SQL_MODE") != "ANSI_QUOTES": <NEW_LINE> <INDENT> raise MUTLibError("Failed to set SQL_MODE=ANSI_QUOTES to server" " {0}:{1}".format(self.server1.host, self.server1.port)) <NEW_LINE> <DEDENT> if self.server2.select_variable("SQL_MODE") != "ANSI_QUOTES": <NEW_LINE> <INDENT> raise MUTLibError("Failed to set SQL_MODE=ANSI_QUOTES to server" " {0}:{1}".format(self.server2.host, self.server2.port)) <NEW_LINE> <DEDENT> self.drop_all() <NEW_LINE> return True <NEW_LINE> <DEDENT> def get_result(self): <NEW_LINE> <INDENT> return self.compare(__name__, self.results) <NEW_LINE> <DEDENT> def record(self): <NEW_LINE> <INDENT> return self.save_result_file(__name__, self.results) <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> if not self.server1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> kill_list = ["compare_db_srv1_ansi_quotes", "compare_db_srv2_ansi_quotes"] <NEW_LINE> return (compare_db_errors.test.cleanup(self) and self.kill_server_list(kill_list))
check errors for dbcompare This test executes a series of error conditions for the check database utility. It uses the compare_db test as a parent for setup and teardown methods.
6259904794891a1f408ba0b9
class ImageManager: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_image_by_id(image_id: int, related_fields: tuple = ()): <NEW_LINE> <INDENT> if not isinstance(image_id, int) or image_id < 0: <NEW_LINE> <INDENT> raise ImageError(msg='镜像ID参数有误') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if related_fields: <NEW_LINE> <INDENT> return Image.objects.select_related(*related_fields).filter(id=image_id).first() <NEW_LINE> <DEDENT> return Image.objects.filter(id=image_id).first() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise ImageError(msg=f'查询镜像时错误,{str(e)}') <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get_image_type_queryset(): <NEW_LINE> <INDENT> return ImageType.objects.all() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_image_queryset(): <NEW_LINE> <INDENT> return Image.objects.filter(enable=True).all() <NEW_LINE> <DEDENT> def get_image_queryset_by_center(self, center_or_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pool_ids = CenterManager().get_pool_ids_by_center(center_or_id) <NEW_LINE> <DEDENT> except ComputeError as e: <NEW_LINE> <INDENT> raise ImageError(msg=str(e)) <NEW_LINE> <DEDENT> return self.get_image_queryset().filter(ceph_pool__in=pool_ids).all() <NEW_LINE> <DEDENT> def get_image_queryset_by_type(self, type_or_id): <NEW_LINE> <INDENT> return self.get_image_queryset().filter(type=type_or_id).all() <NEW_LINE> <DEDENT> def get_image_queryset_by_systype(self, sys_type: int): <NEW_LINE> <INDENT> return self.get_image_queryset().filter(sys_type=sys_type).all() <NEW_LINE> <DEDENT> def get_image_queryset_by_tag(self, tag: int): <NEW_LINE> <INDENT> return self.get_image_queryset().filter(tag=tag).all() <NEW_LINE> <DEDENT> def filter_image_queryset(self, center_id: int, sys_type: int, tag: int, search: str, all_no_filters: bool = False, related_fields: tuple = ()): <NEW_LINE> <INDENT> if center_id <= 0 and sys_type <= 0 and tag <= 0 and not search: <NEW_LINE> <INDENT> if not all_no_filters: <NEW_LINE> <INDENT> raise ImageError(msg='查询条件无效') <NEW_LINE> <DEDENT> return self.get_image_queryset().select_related(*related_fields).all() <NEW_LINE> <DEDENT> queryset = None <NEW_LINE> if center_id > 0: <NEW_LINE> <INDENT> queryset = self.get_image_queryset_by_center(center_id) <NEW_LINE> <DEDENT> if sys_type > 0: <NEW_LINE> <INDENT> if queryset is not None: <NEW_LINE> <INDENT> queryset = queryset.filter(sys_type=sys_type).all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> queryset = self.get_image_queryset_by_systype(sys_type) <NEW_LINE> <DEDENT> <DEDENT> if tag > 0: <NEW_LINE> <INDENT> if queryset is not None: <NEW_LINE> <INDENT> queryset = queryset.filter(tag=tag).all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> queryset = self.get_image_queryset_by_tag(tag) <NEW_LINE> <DEDENT> <DEDENT> if search: <NEW_LINE> <INDENT> if queryset is not None: <NEW_LINE> <INDENT> queryset = queryset.filter(Q(desc__icontains=search) | Q(name__icontains=search)).all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> queryset = self.get_image_queryset().filter(Q(desc__icontains=search) | Q(name__icontains=search)).all() <NEW_LINE> <DEDENT> <DEDENT> return queryset.select_related(*related_fields).all()
镜像管理器
62599047baa26c4b54d50631
class cached_property(default_property): <NEW_LINE> <INDENT> def __get__(self, obj, objtype=None): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> ret = super(cached_property, self).__get__(obj, objtype) <NEW_LINE> setattr(obj, self.func.__name__, ret) <NEW_LINE> return ret
Non-data descriptor. Delegates to func only the first time a property is accessed. Usage example: >>> class C(object): ... @cached_property ... def cached(self): ... print("Accessing {cls.__name__}.cached".format(cls=type(self))) ... return 17 ... >>> x = C() >>> x.cached Accessing C.cached 17 >>> x.cached 17 >>> x.cached = 42 >>> x.cached 42
62599047d6c5a102081e34a3
class EquipmentServiceServicer(object): <NEW_LINE> <INDENT> def Identificate(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def ReceiveUpdate(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def GetStatus(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Missing associated documentation comment in .proto file.
62599047004d5f362081f9aa
class Player(models.Model): <NEW_LINE> <INDENT> champion = models.ForeignKey(Champion) <NEW_LINE> summoner = models.ForeignKey(Summoner) <NEW_LINE> team_id = models.IntegerField() <NEW_LINE> game = models.ForeignKey('Game') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('team_id',) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s on %s (Team %d)' % (self.summoner, self.champion, self.team_id) <NEW_LINE> <DEDENT> def region(self): <NEW_LINE> <INDENT> return self.participant_of.region
Maps to Riot API fellowPlayer DTO. game-v1.3. fellowPlayer is related to match history query.
6259904750485f2cf55dc30f
class IpPrinter: <NEW_LINE> <INDENT> def __init__ (self, typename, val): <NEW_LINE> <INDENT> self.typename = typename <NEW_LINE> self.val = val <NEW_LINE> <DEDENT> def to_string (self): <NEW_LINE> <INDENT> ip_type = "" <NEW_LINE> addr = "" <NEW_LINE> if self.val['type_'] == 0: <NEW_LINE> <INDENT> x = int(self.val['ipv4_address_']['addr_']['s_addr']) <NEW_LINE> x1 = x & 0xFF <NEW_LINE> x2 = (x & 0xFF00) >> 8 <NEW_LINE> x3 = (x & 0xFF0000) >> 16 <NEW_LINE> x4 = (x & 0xFF000000) >> 24 <NEW_LINE> ip = '%d.%d.%d.%d' %(x1, x2, x3, x4) <NEW_LINE> ip_type = "IPv4" <NEW_LINE> addr = '%-15s' %(ip) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> addr = 'FIXME' <NEW_LINE> <DEDENT> return '<%s %-15s>' % (ip_type, addr)
Print TBB atomic varaiable of some kind
62599047462c4b4f79dbcd86
class ListTree: <NEW_LINE> <INDENT> def __attrnames(self, obj, indent): <NEW_LINE> <INDENT> spaces = ' ' * (indent + 1) <NEW_LINE> result = '' <NEW_LINE> for attr in sorted(obj.__dict__): <NEW_LINE> <INDENT> if attr.startswith('__') and attr.endswith('__'): <NEW_LINE> <INDENT> result += spaces + '{0}\n'.format(attr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result += spaces + '{0}={1}\n'.format(attr, getattr(obj, attr)) <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def __listclass(self, aClass, indent): <NEW_LINE> <INDENT> dots = '.' * indent <NEW_LINE> if aClass in self.__visited: <NEW_LINE> <INDENT> return '\n{0}<Class {1}:, address {2}: (see above)>\n'.format( dots, aClass.__name__, id(aClass)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__visited[aClass] = True <NEW_LINE> here = self.__attrnames(aClass, indent) <NEW_LINE> above = '' <NEW_LINE> for super in aClass.__bases__: <NEW_LINE> <INDENT> above += self.__listclass(super, indent+4) <NEW_LINE> <DEDENT> return '\n{0}<Class {1}, address {2}:\n{3}{4}{5}>\n'.format( dots, aClass.__name__, id(aClass), here, above, dots) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> self.__visited = {} <NEW_LINE> here = self.__attrnames(self, 0) <NEW_LINE> above = self.__listclass(self.__class__, 4) <NEW_LINE> return '<Instance of {0}, address {1}:\n{2}{3}>'.format( self.__class__.__name__, id(self), here, above)
Mix-in that returns an __str__ trace of the entire class tree and all its objects' attrs at and above self; run by print(), str() returns constructed string; uses __X attr names to avoid impacting clients; recurses to superclasses explicitly, uses str.format() for clarity;
625990474e696a045264e7e4
class NotLoadedType: <NEW_LINE> <INDENT> _locked = False <NEW_LINE> @staticmethod <NEW_LINE> def __init__(): <NEW_LINE> <INDENT> if NotLoadedType._locked: <NEW_LINE> <INDENT> raise ValueError('Do not make new instance of NotLoadedType') <NEW_LINE> <DEDENT> NotLoadedType._locked = True <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __bool__(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __repr__(): <NEW_LINE> <INDENT> return 'NotLoaded'
用于表示尚未载入的内容
62599048d53ae8145f9197e8
class CSSVariable(CSSFunction): <NEW_LINE> <INDENT> _functionName = 'CSSVariable' <NEW_LINE> _name = None <NEW_LINE> _fallback = None <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "<css_parser.css.%s object name=%r value=%r at 0x%x>" % ( self.__class__.__name__, self.name, self.value, id(self)) <NEW_LINE> <DEDENT> def _setCssText(self, cssText): <NEW_LINE> <INDENT> self._checkReadonly() <NEW_LINE> types = self._prods <NEW_LINE> prods = Sequence(Prod(name='var', match=lambda t, v: t == types.FUNCTION and normalize(v) == 'var(' ), PreDef.ident(toStore='ident'), Sequence(PreDef.comma(), Choice(_ColorProd(self, toStore='fallback'), _DimensionProd(self, toStore='fallback'), _URIProd(self, toStore='fallback'), _ValueProd(self, toStore='fallback'), _CalcValueProd(self, toStore='fallback'), _CSSVariableProd(self, toStore='fallback'), _CSSFunctionProd(self, toStore='fallback') ), minmax=lambda: (0, 1) ), PreDef.funcEnd(stop=True)) <NEW_LINE> store = {'ident': None, 'fallback': None} <NEW_LINE> ok, seq, store, unused = ProdParser().parse(cssText, 'CSSVariable', prods) <NEW_LINE> self.wellformed = ok <NEW_LINE> if ok: <NEW_LINE> <INDENT> self._name = store['ident'].value <NEW_LINE> try: <NEW_LINE> <INDENT> self._fallback = store['fallback'].value <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self._fallback = None <NEW_LINE> <DEDENT> self._setSeq(seq) <NEW_LINE> <DEDENT> <DEDENT> cssText = property(lambda self: css_parser.ser.do_css_CSSVariable(self), _setCssText, doc="String representation of variable.") <NEW_LINE> name = property(lambda self: self._name, doc="The name identifier of this variable referring to " "a value in a " ":class:`css_parser.css.CSSVariablesDeclaration`.") <NEW_LINE> fallback = property(lambda self: self._fallback, doc="The fallback Value of this variable") <NEW_LINE> type = property(lambda self: Value.VARIABLE, doc="Type is fixed to Value.VARIABLE.") <NEW_LINE> def _getValue(self): <NEW_LINE> <INDENT> rel = self <NEW_LINE> while True: <NEW_LINE> <INDENT> if hasattr(rel, 'parent'): <NEW_LINE> <INDENT> rel = rel.parent <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> variables = rel.parentRule.parentStyleSheet.variables <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return variables[self.name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> value = property(_getValue, doc='The resolved actual value or None.')
The CSSVariable represents a CSS variables like ``var(varname)``. A variable has a (nonnormalized!) `name` and a `value` which is tried to be resolved from any available CSSVariablesRule definition.
6259904850485f2cf55dc310
class StructuredDefaultDict(dict): <NEW_LINE> <INDENT> __slots__ = ('layer', 'type', 'args_munger', 'kwargs_munger', 'parent', 'key', '_stuff', 'gettest', 'settest') <NEW_LINE> def __init__(self, layers, type=None, args_munger=_default_args_munger, kwargs_munger=_default_kwargs_munger, gettest=lambda k: None, settest=lambda k, v: None): <NEW_LINE> <INDENT> if layers < 1: <NEW_LINE> <INDENT> raise ValueError("Not enough layers") <NEW_LINE> <DEDENT> self.layer = layers <NEW_LINE> self.type = type <NEW_LINE> self.args_munger = args_munger <NEW_LINE> self.kwargs_munger = kwargs_munger <NEW_LINE> self._stuff = (layers, type, args_munger, kwargs_munger) <NEW_LINE> self.gettest = gettest <NEW_LINE> self.settest = settest <NEW_LINE> <DEDENT> def __getitem__(self, k): <NEW_LINE> <INDENT> self.gettest(k) <NEW_LINE> if k in self: <NEW_LINE> <INDENT> return dict.__getitem__(self, k) <NEW_LINE> <DEDENT> layer, typ, args_munger, kwargs_munger = self._stuff <NEW_LINE> if layer == 1: <NEW_LINE> <INDENT> if typ is None: <NEW_LINE> <INDENT> ret = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = PickyDefaultDict(typ, args_munger, kwargs_munger) <NEW_LINE> ret.parent = self <NEW_LINE> ret.key = k <NEW_LINE> <DEDENT> <DEDENT> elif layer < 1: <NEW_LINE> <INDENT> raise ValueError("Invalid layer") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = StructuredDefaultDict(layer - 1, typ, args_munger, kwargs_munger) <NEW_LINE> ret.parent = self <NEW_LINE> ret.key = k <NEW_LINE> <DEDENT> dict.__setitem__(self, k, ret) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def __setitem__(self, k, v): <NEW_LINE> <INDENT> self.settest(k, v) <NEW_LINE> if type(v) is StructuredDefaultDict: <NEW_LINE> <INDENT> layer, typ, args_munger, kwargs_munger = self._stuff <NEW_LINE> if (v.layer == layer - 1 and (typ is None or v.type is typ) and v.args_munger is args_munger and v.kwargs_munger is kwargs_munger): <NEW_LINE> <INDENT> super().__setitem__(k, v) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> elif type(v) is PickyDefaultDict: <NEW_LINE> <INDENT> layer, typ, args_munger, kwargs_munger = self._stuff <NEW_LINE> if (layer == 1 and v.type is typ and v.args_munger is args_munger and v.kwargs_munger is kwargs_munger): <NEW_LINE> <INDENT> super().__setitem__(k, v) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> raise TypeError("Can't set layer {}".format(self.layer))
A ``defaultdict``-like class that expects values stored at a specific depth. Requires an integer to tell it how many layers deep to go. The innermost layer will be ``PickyDefaultDict``, which will take the ``type``, ``args_munger``, and ``kwargs_munger`` arguments supplied to my constructor.
62599048d99f1b3c44d06a27
class AuthorRecipeListView(ListView): <NEW_LINE> <INDENT> paginate_by = settings.PAGINATE_BY <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> author = get_object_or_404(User, username=self.kwargs['username']) <NEW_LINE> self.extra_context = {'author': author} <NEW_LINE> queryset = Recipe.objects.select_related( 'author').prefetch_related('tags').filter(author=author) <NEW_LINE> tags = self.request.GET.getlist('tags') <NEW_LINE> if tags: <NEW_LINE> <INDENT> return queryset.filter(tags__slug__in=tags) <NEW_LINE> <DEDENT> return queryset
Display recipe list of a particular author.
62599048a8ecb0332587259a
class _BCSnapshot(object): <NEW_LINE> <INDENT> def __init__(self, bcs): <NEW_LINE> <INDENT> self.bcs = map(weakref.ref, bcs) if bcs is not None else None <NEW_LINE> <DEDENT> def valid(self, bcs): <NEW_LINE> <INDENT> if len(bcs) != len(self.bcs): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for bc, wbc in zip(bcs, self.bcs): <NEW_LINE> <INDENT> if bc != wbc(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Record the boundary conditions which were applied to a form.
6259904845492302aabfd85a
class Command: <NEW_LINE> <INDENT> name = None <NEW_LINE> def __init__(self, runner): <NEW_LINE> <INDENT> self._runner = runner <NEW_LINE> <DEDENT> def __call__(self, args): <NEW_LINE> <INDENT> self.execute(args) <NEW_LINE> <DEDENT> def _error(self, message): <NEW_LINE> <INDENT> self._runner._error(message, prog=self.name) <NEW_LINE> <DEDENT> def execute(self, args): <NEW_LINE> <INDENT> raise NotImplementedError()
The base command to define command-line actions.
62599048498bea3a75a58ea8
class ElementSensor(TemperatureSensor): <NEW_LINE> <INDENT> def __init__(self, _id, _uuid, max_temp: Temperature, min_temp: Temperature): <NEW_LINE> <INDENT> super().__init__(_id, _uuid) <NEW_LINE> self.max_temp = max_temp <NEW_LINE> self.min_temp = min_temp <NEW_LINE> <DEDENT> def check_temperature_limits(self, current_temp) -> None: <NEW_LINE> <INDENT> if current_temp > self.max_temp: <NEW_LINE> <INDENT> system_logger.critical(f"Element turning off! {current_temp} is above it's limit of {self.max_temp} ") <NEW_LINE> raise OverTemperature <NEW_LINE> <DEDENT> if current_temp < self.min_temp: <NEW_LINE> <INDENT> system_logger.critical(f"Element turning off! {current_temp} is below it's limit of {self.min_temp} ") <NEW_LINE> raise UnderTemperature
This is a class representing an element sensor. Because of the materials used, the element should never exceed specified temperature limits set in the constructor.
6259904876d4e153a661dc3a
class PolymorphicMPTTChildModelAdmin(PolymorphicChildModelAdmin, MPTTModelAdmin): <NEW_LINE> <INDENT> base_model = None <NEW_LINE> base_form = PolymorpicMPTTAdminForm <NEW_LINE> base_fieldsets = None <NEW_LINE> @property <NEW_LINE> def change_form_template(self): <NEW_LINE> <INDENT> templates = super(PolymorphicMPTTChildModelAdmin, self).change_form_template <NEW_LINE> templates.insert(-2, "admin/polymorphic_tree/change_form.html") <NEW_LINE> return templates <NEW_LINE> <DEDENT> @property <NEW_LINE> def delete_confirmation_template(self): <NEW_LINE> <INDENT> templates = super(PolymorphicMPTTChildModelAdmin, self).delete_confirmation_template <NEW_LINE> templates.insert(-2, "admin/polymorphic_tree/delete_confirmation.html") <NEW_LINE> return templates <NEW_LINE> <DEDENT> @property <NEW_LINE> def object_history_template(self): <NEW_LINE> <INDENT> templates = super(PolymorphicMPTTChildModelAdmin, self).object_history_template <NEW_LINE> if isinstance(templates, list): <NEW_LINE> <INDENT> templates.insert(-2, "admin/polymorphic_tree/object_history.html") <NEW_LINE> <DEDENT> return templates
The internal machinery The admin screen for the ``PolymorphicMPTTModel`` objects.
62599048379a373c97d9a3b3
class Solution: <NEW_LINE> <INDENT> def sequenceReconstruction(self, org, seqs): <NEW_LINE> <INDENT> graph = self.build_graph(seqs) <NEW_LINE> topo_order = self.topological_sort(graph) <NEW_LINE> return topo_order == org <NEW_LINE> <DEDENT> def build_graph(self, seqs): <NEW_LINE> <INDENT> graph = {} <NEW_LINE> for seq in seqs: <NEW_LINE> <INDENT> for node in seq: <NEW_LINE> <INDENT> if node not in graph: <NEW_LINE> <INDENT> graph[node] = set() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for seq in seqs: <NEW_LINE> <INDENT> for i in range(1, len(seq)): <NEW_LINE> <INDENT> graph[seq[i - 1]].add(seq[i]) <NEW_LINE> <DEDENT> <DEDENT> return graph <NEW_LINE> <DEDENT> def get_indegrees(self, graph): <NEW_LINE> <INDENT> indegrees = { node: 0 for node in graph } <NEW_LINE> for node in graph: <NEW_LINE> <INDENT> for neighbor in graph[node]: <NEW_LINE> <INDENT> indegrees[neighbor] += 1 <NEW_LINE> <DEDENT> <DEDENT> return indegrees <NEW_LINE> <DEDENT> def topological_sort(self, graph): <NEW_LINE> <INDENT> indegrees = self.get_indegrees(graph) <NEW_LINE> queue = [] <NEW_LINE> for node in graph: <NEW_LINE> <INDENT> if indegrees[node] == 0: <NEW_LINE> <INDENT> queue.append(node) <NEW_LINE> <DEDENT> <DEDENT> topo_order = [] <NEW_LINE> while queue: <NEW_LINE> <INDENT> if len(queue) > 1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> node = queue.pop() <NEW_LINE> topo_order.append(node) <NEW_LINE> for neighbor in graph[node]: <NEW_LINE> <INDENT> indegrees[neighbor] -= 1 <NEW_LINE> if indegrees[neighbor] == 0: <NEW_LINE> <INDENT> queue.append(neighbor) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if len(topo_order) == len(graph): <NEW_LINE> <INDENT> return topo_order <NEW_LINE> <DEDENT> return None
@param org: a permutation of the integers from 1 to n @param seqs: a list of sequences @return: true if it can be reconstructed only one or false
62599048dc8b845886d54944
class ConstTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_type_attributes(self): <NEW_LINE> <INDENT> @rdpy.core.const.TypeAttributes(rdpy.core.type.UInt16Le) <NEW_LINE> class Test: <NEW_LINE> <INDENT> MEMBER_1 = 1 <NEW_LINE> MEMBER_2 = 2 <NEW_LINE> <DEDENT> self.assertIsInstance(Test.MEMBER_1, rdpy.core.type.UInt16Le, "MEMBER_1 is not in correct type") <NEW_LINE> self.assertIsInstance(Test.MEMBER_2, rdpy.core.type.UInt16Le, "MEMBER_2 is not in correct type") <NEW_LINE> <DEDENT> def test_const(self): <NEW_LINE> <INDENT> @rdpy.core.const.ConstAttributes <NEW_LINE> class Test: <NEW_LINE> <INDENT> MEMBER_1 = 1 <NEW_LINE> MEMBER_2 = 2 <NEW_LINE> <DEDENT> self.assertEquals(Test.MEMBER_1, Test.MEMBER_1, "handle same type of object")
represent test case for all classes and function present in rdpy.base.const
6259904823849d37ff852445
class Regle: <NEW_LINE> <INDENT> ID = 0 <NEW_LINE> def __init__(self, gauche:list, droite:list, fiab:float=1.) -> None: <NEW_LINE> <INDENT> self.__id = self.ID <NEW_LINE> Regle.ID += 1 <NEW_LINE> self.__left = frozenset(gauche) <NEW_LINE> self.__right = frozenset(droite) <NEW_LINE> self.__fiabilite = fiab <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> s = "R{0.idnum} :" <NEW_LINE> s += ','.join([str(x) for x in self.gauche]) <NEW_LINE> s += ' -> ' <NEW_LINE> s += ','.join([str(x) for x in self.droite]) <NEW_LINE> return s.format(self) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "R{0.idnum} {0.gauche} -> {0.droite}".format(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def idnum(self) -> int: <NEW_LINE> <INDENT> return self.__id <NEW_LINE> <DEDENT> @property <NEW_LINE> def gauche(self) -> set: <NEW_LINE> <INDENT> return self.__left <NEW_LINE> <DEDENT> @property <NEW_LINE> def droite(self) -> set: <NEW_LINE> <INDENT> return self.__right <NEW_LINE> <DEDENT> @property <NEW_LINE> def fiabilite(self) -> float: <NEW_LINE> <INDENT> return max(0., min(self.__fiabilite, 1.)) <NEW_LINE> <DEDENT> @fiabilite.setter <NEW_LINE> def fiabilite(self, val): <NEW_LINE> <INDENT> pass
<conditions> -> <conclusions>
6259904830c21e258be99b8f
class WeightLogEntryEditTestCase(WorkoutManagerTestCase): <NEW_LINE> <INDENT> def edit_log_entry(self, fail=True): <NEW_LINE> <INDENT> response = self.client.get(reverse('manager:log:edit', kwargs={'pk': 1})) <NEW_LINE> if fail: <NEW_LINE> <INDENT> self.assertTrue(response.status_code in (302, 403)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> date_before = WorkoutLog.objects.get(pk=1).date <NEW_LINE> response = self.client.post(reverse('manager:log:edit', kwargs={'pk': 1}), {'date': '2012-01-01', 'reps': 10, 'weight': 10, 'exercise': 1 }) <NEW_LINE> date_after = WorkoutLog.objects.get(pk=1).date <NEW_LINE> if fail: <NEW_LINE> <INDENT> self.assertTrue(response.status_code in (302, 403)) <NEW_LINE> self.assertEqual(date_before, date_after) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertEqual(response.status_code, 302) <NEW_LINE> self.assertEqual(date_after, datetime.date(2012, 1, 1)) <NEW_LINE> <DEDENT> <DEDENT> def test_edit_log_entry_anonymous(self): <NEW_LINE> <INDENT> self.edit_log_entry(fail=True) <NEW_LINE> <DEDENT> def test_edit_log_entry_owner(self): <NEW_LINE> <INDENT> self.user_login('admin') <NEW_LINE> self.edit_log_entry(fail=False) <NEW_LINE> <DEDENT> def test_edit_log_entry_other(self): <NEW_LINE> <INDENT> self.user_login('test') <NEW_LINE> self.edit_log_entry(fail=True)
Tests editing individual weight log entries
6259904830dc7b76659a0bbc
class Command(BaseCommand): <NEW_LINE> <INDENT> def add_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument("--run_time", help="Time to run for.") <NEW_LINE> parser.add_argument("--crash", action="store_true", help="Crash when running.") <NEW_LINE> parser.add_argument("--print", help="Value to print to stdout.") <NEW_LINE> <DEDENT> def handle(self, **options): <NEW_LINE> <INDENT> if options["crash"]: <NEW_LINE> <INDENT> raise Exception("**Sputter**") <NEW_LINE> <DEDENT> if options["print"]: <NEW_LINE> <INDENT> self.stdout.write("To print: %r" % options["print"]) <NEW_LINE> <DEDENT> self.stdout.write("This is a test.")
Test cron job command.
625990483617ad0b5ee074c6
class BoxAround(Enum): <NEW_LINE> <INDENT> TOP_LEFT = 0 <NEW_LINE> TOP_CENTER = 1 <NEW_LINE> TOP_RIGHT = 2 <NEW_LINE> LEFT = 3 <NEW_LINE> CENTER = 4 <NEW_LINE> RIGHT = 5 <NEW_LINE> BOTTOM_LEFT = 6 <NEW_LINE> BOTTOM_CENTER = 7 <NEW_LINE> BOTTOM_RIGHT = 8
Use for Box.around_ref dictionary 0 1 2 3 4 5 6 7 8 Box.around_ref[CENTER] should return self TODO Implement if needed
625990486fece00bbacccd3f
class NetworkManager(TortugaObjectManager): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(NetworkManager, self).__init__() <NEW_LINE> self._networkDbApi = NetworkDbApi() <NEW_LINE> <DEDENT> def getNetwork(self, session: Session, address: str, netmask: str) -> Network: <NEW_LINE> <INDENT> return self._networkDbApi.getNetwork(session, address, netmask) <NEW_LINE> <DEDENT> def getNetworkById(self, session: Session, id_) -> Network: <NEW_LINE> <INDENT> return self._networkDbApi.getNetworkById(session, id_) <NEW_LINE> <DEDENT> def getNetworkList(self, session: Session) -> TortugaObjectList: <NEW_LINE> <INDENT> return self._networkDbApi.getNetworkList(session) <NEW_LINE> <DEDENT> def addNetwork(self, session: Session, network: Network) -> int: <NEW_LINE> <INDENT> self.__validateNetwork(network) <NEW_LINE> return self._networkDbApi.addNetwork(session, network) <NEW_LINE> <DEDENT> def updateNetwork(self, session: Session, network: Network) -> Network: <NEW_LINE> <INDENT> self.__validateNetwork(network) <NEW_LINE> return self._networkDbApi.updateNetwork(session, network) <NEW_LINE> <DEDENT> def deleteNetwork(self, session: Session, network_id: int): <NEW_LINE> <INDENT> return self._networkDbApi.deleteNetwork(session, network_id) <NEW_LINE> <DEDENT> def __validateNetwork(self, network: Network) -> None: <NEW_LINE> <INDENT> optionDict = {} <NEW_LINE> if 'address' in network and not network['address']: <NEW_LINE> <INDENT> raise InvalidArgument('Network address not set') <NEW_LINE> <DEDENT> if 'netmask' in network and not network['netmask']: <NEW_LINE> <INDENT> raise InvalidArgument('Network mask not set') <NEW_LINE> <DEDENT> if network.getOptions(): <NEW_LINE> <INDENT> for option in network.getOptions().split(';'): <NEW_LINE> <INDENT> tokens = option.split('=') <NEW_LINE> if len(tokens) == 2: <NEW_LINE> <INDENT> key, value = tokens <NEW_LINE> optionDict[key] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if 'startIp' in network and network['startIp']: <NEW_LINE> <INDENT> startIp = ipaddress.IPv4Address(str(network['startIp'])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> increment = int(network['increment']) if 'increment' in network and network['increment'] else 1 <NEW_LINE> startIp = ipaddress.IPv4Address( str(network['address'])) + increment <NEW_LINE> <DEDENT> ipaddrNetwork = ipaddress.IPv4Network( '%s/%s' % (network['address'], network['netmask'])) <NEW_LINE> if startIp not in ipaddrNetwork: <NEW_LINE> <INDENT> raise InvalidArgument( 'Starting IP address [%s] is not on network [%s]' % ( startIp, ipaddrNetwork)) <NEW_LINE> <DEDENT> network['startIp'] = str(startIp) <NEW_LINE> if 'vlan' in optionDict: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if int(optionDict['vlan']) > 4095 or int(optionDict['vlan']) < 1: <NEW_LINE> <INDENT> raise InvalidArgument( 'The VLAN ID must be an integer in the range' ' 1-4095') <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise InvalidArgument( 'The VLAN ID must be an integer in the range 1-4095')
Class for network management. Usage: # Getting db instance. from tortuga.network.networkManager import NetworkManager networkManager = NetworkManager()
625990483c8af77a43b68902
@register_model('convtransformer') <NEW_LINE> class ConvTransformerModel(TransformerModel): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def add_args(parser): <NEW_LINE> <INDENT> super(ConvTransformerModel, ConvTransformerModel).add_args(parser) <NEW_LINE> parser.add_argument('--context_size', type=int, default=3, help='sets context size for convolutional layers') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def build_encoder(cls, args, src_dict, embed_tokens): <NEW_LINE> <INDENT> return ConvTransformerEncoder(args, src_dict, embed_tokens)
Args: encoder (ConvTransformerEncoder): the encoder decoder (TransformerDecoder): the decoder The Transformer model provides the following named architectures and command-line arguments: .. argparse:: :ref: fairseq.models.transformer_parser :prog:
62599048d10714528d69f052
class FormatNodeItemResultTest(TestCase): <NEW_LINE> <INDENT> def test_values(self): <NEW_LINE> <INDENT> result = MagicMock() <NEW_LINE> result.correct = 0 <NEW_LINE> result.fixed = 1 <NEW_LINE> result.skipped = 2 <NEW_LINE> result.failed = 3 <NEW_LINE> self.assertEqual( format_node_result(result), "0 OK, 1 fixed, 2 skipped, 3 failed", ) <NEW_LINE> <DEDENT> def test_zero(self): <NEW_LINE> <INDENT> result = MagicMock() <NEW_LINE> result.correct = 0 <NEW_LINE> result.fixed = 0 <NEW_LINE> result.skipped = 0 <NEW_LINE> result.failed = 0 <NEW_LINE> self.assertEqual( format_node_result(result), "0 OK, 0 fixed, 0 skipped, 0 failed", )
Tests blockwart.cmdline.apply.format_node_item_result.
6259904821a7993f00c672f3
class GenderEvaluator: <NEW_LINE> <INDENT> def __init__(self, gender=None): <NEW_LINE> <INDENT> self.eligible = False <NEW_LINE> self.reasons_eligible = None <NEW_LINE> if gender == 'MALE': <NEW_LINE> <INDENT> self.eligible = True <NEW_LINE> <DEDENT> elif gender == 'FEMALE': <NEW_LINE> <INDENT> self.eligible = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.eligible = False
Eligible if gender is valid
62599048be383301e0254ba3
class FeatureLine(Feature): <NEW_LINE> <INDENT> def __init__(self, points, thickness): <NEW_LINE> <INDENT> self.line = geom.LineString(points) <NEW_LINE> self.thickness = thickness <NEW_LINE> self._update_shape() <NEW_LINE> self.models = [] <NEW_LINE> <DEDENT> def _update_shape(self): <NEW_LINE> <INDENT> self.shape = self.line.buffer(self.thickness, cap_style=geom.CAP_STYLE.flat, join_style=geom.JOIN_STYLE.round) <NEW_LINE> <DEDENT> def interaction(self): <NEW_LINE> <INDENT> return "replace"
Feature corresponding to a linear zone: new functions to manipulate the curve of the feature.
6259904845492302aabfd85c
class AverageMeter(object): <NEW_LINE> <INDENT> def __init__(self, name, fmt=':4g', disp_avg=True): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.fmt = fmt <NEW_LINE> self.disp_avg = disp_avg <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.val = 0 <NEW_LINE> self.avg = 0 <NEW_LINE> self.sum = 0 <NEW_LINE> self.count = 0 <NEW_LINE> <DEDENT> def update(self, val, n=1): <NEW_LINE> <INDENT> self.val = val <NEW_LINE> self.sum += val * n <NEW_LINE> self.count += n <NEW_LINE> self.avg = self.sum / self.count <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> fmtstr = '{name}{val' + self.fmt + '}' <NEW_LINE> fmtstr = fmtstr.format(name=self.name, val=self.val) <NEW_LINE> if self.disp_avg: <NEW_LINE> <INDENT> fmtstr += '({avg' + self.fmt + '})' <NEW_LINE> fmtstr = fmtstr.format(avg=self.avg) <NEW_LINE> <DEDENT> return fmtstr.format(**self.__dict__)
Computes and stores the average and current value
625990488e05c05ec3f6f820
class Origin(BaseListeningAgent): <NEW_LINE> <INDENT> async def send_schema(self, schema_data_json: str) -> str: <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> logger.debug('Origin.send_schema: >>> schema_data_json: {}'.format(schema_data_json)) <NEW_LINE> req_json = await ledger.build_schema_request(self.did, schema_data_json) <NEW_LINE> resp_json = await ledger.sign_and_submit_request(self.pool.handle, self.wallet.handle, self.did, req_json) <NEW_LINE> resp = (json.loads(resp_json))['result'] <NEW_LINE> rv = await self.get_schema(resp['identifier'], resp['data']['name'], resp['data']['version']) <NEW_LINE> logger.debug('Origin.send_schema: <<< {}'.format(rv)) <NEW_LINE> return rv <NEW_LINE> <DEDENT> async def process_post(self, form: dict) -> str: <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> logger.debug('Origin.process_post: >>> form: {}'.format(form)) <NEW_LINE> self.__class__._vet_keys({'type', 'data'}, set(form.keys())) <NEW_LINE> mro = Origin._mro_dispatch() <NEW_LINE> for ResponderClass in mro: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rv = await ResponderClass.process_post(self, form) <NEW_LINE> logger.debug('Origin.process_post: <<< {}'.format(rv)) <NEW_LINE> return rv <NEW_LINE> <DEDENT> except NotImplementedError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> if form['type'] == 'schema-send': <NEW_LINE> <INDENT> self.__class__._vet_keys( {'schema', 'attr-names'}, set(form['data'].keys()), hint='data') <NEW_LINE> self.__class__._vet_keys( {'issuer-did', 'name', 'version'}, set(form['data']['schema'].keys()), hint='schema') <NEW_LINE> schema_json = await self.send_schema(json.dumps({ 'name': form['data']['schema']['name'], 'version': form['data']['schema']['version'], 'attr_names': form['data']['attr-names'] })) <NEW_LINE> schema = json.loads(schema_json) <NEW_LINE> self._schema_cache = { 'issuer-did': form['data']['schema']['issuer-did'], 'name': form['data']['schema']['name'], 'version': form['data']['schema']['version'], 'seq_no': schema['seqNo'], 'json': schema_json} <NEW_LINE> rv = await self.get_schema( self.schema_cache['issuer-did'], self.schema_cache['name'], self.schema_cache['version']) <NEW_LINE> logger.debug('Origin.process_post: <<< {}'.format(rv)) <NEW_LINE> return rv <NEW_LINE> <DEDENT> logger.debug('Origin.process_post: <!< not this form type: {}'.format(form['type'])) <NEW_LINE> raise NotImplementedError('{} does not support token type {}'.format(self.__class__.__name__, form['type']))
Mixin for agent to send schemata and claim definitions to the distributed ledger
62599048baa26c4b54d50635
class ProductionTimeReportResource(Resource): <NEW_LINE> <INDENT> item_methods = ['GET'] <NEW_LINE> resource_methods = ['GET'] <NEW_LINE> privileges = {'GET': 'production_time_report'} <NEW_LINE> schema = { 'desk_stats': { 'type': 'dict', 'required': False, 'schema': {}, 'allow_unknown': True }, 'highcharts': { 'type': 'list', 'required': False, 'schema': { 'type': 'dict', 'schema': {}, 'allow_unknown': True } } }
Desk Activity Report schema
62599048004d5f362081f9ac
class HeapNode: <NEW_LINE> <INDENT> def __init__(self, key: int) -> None: <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.left = None <NEW_LINE> self.right = None <NEW_LINE> self.parent = None <NEW_LINE> <DEDENT> def cut(self) -> None: <NEW_LINE> <INDENT> if self.parent.left == self: <NEW_LINE> <INDENT> self.parent.left = self.right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.parent.right = self.right <NEW_LINE> <DEDENT> if self.right: <NEW_LINE> <INDENT> self.right.parent = self.parent <NEW_LINE> <DEDENT> self.parent = None <NEW_LINE> self.right = None
A node in a pairing heap. Attributes: key (int): The key value stored by this node. Guaranteed to be less than or equal to all keys in this subheap. left (HeapNode or None): The child of the node. right (HeapNode or None): The sibling of the node. parent (HeapNode or None): The parent of the node.
6259904830c21e258be99b91
class dualwb_intercon(intercon): <NEW_LINE> <INDENT> intercon_type = "dualwb" <NEW_LINE> complement = None <NEW_LINE> sideinfo = "" <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> intercon.__init__(self, **kwargs) <NEW_LINE> if not hasattr(self, "data_width"): <NEW_LINE> <INDENT> setattr(self, "data_width", 32) <NEW_LINE> <DEDENT> if not hasattr(self, "addr_width"): <NEW_LINE> <INDENT> setattr(self, "addr_width", 0) <NEW_LINE> <DEDENT> self.intercon_type = "dualwb" <NEW_LINE> self.signals["m_dat_o"] = {"width": self.data_width, "direction": "out", "signal_obj": None, "description": "Master data output"} <NEW_LINE> if self.addr_width > 0: <NEW_LINE> <INDENT> self.signals["m_adr_o"] = {"width": self.addr_width, "direction": "out", "signal_obj": None, "description": "Master address output"} <NEW_LINE> <DEDENT> self.signals["m_stb_o"] = {"width": 1, "direction": "out", "signal_obj": None, "description": "Master strobe"} <NEW_LINE> self.signals["m_cyc_o"] = {"width": 1, "direction": "out", "signal_obj": None, "description": "Master cycle"} <NEW_LINE> self.signals["m_lflit_o"] = {"width": 1, "direction": "out", "signal_obj": None, "description": "Master last flit flag"} <NEW_LINE> self.signals["m_ack_i"] = {"width": 1, "direction": "in", "signal_obj": None, "description": "Master acknowledge"} <NEW_LINE> self.signals["m_stall_i"] = {"width": 1, "direction": "in", "signal_obj": None, "description": "Master stall"} <NEW_LINE> self.signals["m_err_i"] = {"width": 1, "direction": "in", "signal_obj": None, "description": "Master error"} <NEW_LINE> self.signals["s_dat_i"] = {"width": self.data_width, "direction": "in", "signal_obj": None, "description": "Slave data input"} <NEW_LINE> if self.addr_width > 0: <NEW_LINE> <INDENT> self.signals["s_adr_i"] = {"width": self.addr_width, "direction": "in", "signal_obj": None, "description": "Slave address input"} <NEW_LINE> <DEDENT> self.signals["s_stb_i"] = {"width": 1, "direction": "in", "signal_obj": None, "description": "Slave strobe"} <NEW_LINE> self.signals["s_cyc_i"] = {"width": 1, "direction": "in", "signal_obj": None, "description": "Slave cycle"} <NEW_LINE> self.signals["s_lflit_i"] = {"width": 1, "direction": "in", "signal_obj": None, "description": "Slave last flit flag"} <NEW_LINE> self.signals["s_ack_o"] = {"width": 1, "direction": "out", "signal_obj": None, "description": "Slave acknowledge"} <NEW_LINE> self.signals["s_stall_o"] = {"width": 1, "direction": "out", "signal_obj": None, "description": "Slave stall"} <NEW_LINE> self.signals["s_err_o"] = {"width": 1, "direction": "out", "signal_obj": None, "description": "Slave error"} <NEW_LINE> <DEDENT> def get_complement_signal(self, signalname): <NEW_LINE> <INDENT> if signalname not in self.signals: <NEW_LINE> <INDENT> raise KeyError("Signal '%s' not found" % signalname) <NEW_LINE> <DEDENT> mchange = {"m": "s", "s": "m"} <NEW_LINE> dchange = {"i": "o", "o": "i"} <NEW_LINE> return mchange[signalname[0]] + signalname[1:-1] + dchange[signalname[-1]]
Wishbone dual P2P intercon model This intercon defines two bidirectional Wishbone P2P ports.
6259904829b78933be26aa88
class DataMissingError(DataError): <NEW_LINE> <INDENT> pass
An error raised when data is missing from the expected location.
6259904873bcbd0ca4bcb618
class BottleNeck(nn.Module): <NEW_LINE> <INDENT> expansion = 4 <NEW_LINE> def __init__(self, inplanes, planes, stride=1): <NEW_LINE> <INDENT> super(BottleNeck, self).__init__() <NEW_LINE> self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) <NEW_LINE> self.bn1 = nn.BatchNorm2d(planes) <NEW_LINE> self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) <NEW_LINE> self.bn2 = nn.BatchNorm2d(planes) <NEW_LINE> self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False) <NEW_LINE> self.bn3 = nn.BatchNorm2d(self.expansion*planes) <NEW_LINE> self.shortcut = nn.Sequential() <NEW_LINE> if stride != 1 or inplanes != self.expansion*planes: <NEW_LINE> <INDENT> self.shortcut = nn.Sequential( nn.Conv2d(inplanes, self.expansion*planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(self.expansion*planes) ) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> out = F.relu(self.bn1(self.conv1(x))) <NEW_LINE> out = F.relu(self.bn2(self.conv2(out))) <NEW_LINE> out = self.bn3(self.conv3(out)) <NEW_LINE> sh = self.shortcut(x) <NEW_LINE> out += sh <NEW_LINE> out = F.relu(out) <NEW_LINE> return out
ResNet BottleNeck
6259904810dbd63aa1c71f66
class TestPub(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> test_lock.acquire() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> test_lock.release() <NEW_LINE> <DEDENT> def test_pub_unicode(self): <NEW_LINE> <INDENT> from posttroll.message import Message <NEW_LINE> from posttroll.publisher import Publish <NEW_LINE> message = Message("/pџтяöll", "info", 'hej') <NEW_LINE> with Publish("a_service", 9000) as pub: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pub.send(message.encode()) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> self.fail("Sending raised UnicodeDecodeError unexpectedly!") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_pub_minmax_port(self): <NEW_LINE> <INDENT> import os <NEW_LINE> for port in range(40000, 50000): <NEW_LINE> <INDENT> os.environ['POSTTROLL_PUB_MIN_PORT'] = str(port) <NEW_LINE> os.environ['POSTTROLL_PUB_MAX_PORT'] = str(port + 1) <NEW_LINE> res = _get_port(min_port=None, max_port=None) <NEW_LINE> if res is False: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.assertEqual(res, port) <NEW_LINE> break <NEW_LINE> <DEDENT> for port in range(50000, 60000): <NEW_LINE> <INDENT> res = _get_port(min_port=port, max_port=port+1) <NEW_LINE> if res is False: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.assertEqual(res, port) <NEW_LINE> break
Testing the publishing capabilities.
6259904823e79379d538d889
class NoneTransform(object): <NEW_LINE> <INDENT> def __call__(self, image): <NEW_LINE> <INDENT> return image
Does nothing to the image, to be used instead of None Args: image in, image out, nothing is done
625990483c8af77a43b68903
class MyTestCase(unittest.TestCase): <NEW_LINE> <INDENT> screenshot_path = os.path.join(gl.screenshot_path, os.path.splitext(os.path.basename(__file__))[0]) <NEW_LINE> start_date = '2018-01-01' <NEW_LINE> end_date = '2018-01-31' <NEW_LINE> count = '294' <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.webdriver = tools.get_chrome_driver() <NEW_LINE> web_login.login(cls.webdriver) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> cls.webdriver.quit() <NEW_LINE> <DEDENT> def test_brand_in_city(self): <NEW_LINE> <INDENT> casename = sys._getframe().f_code.co_name <NEW_LINE> try: <NEW_LINE> <INDENT> brandincitypage = brand_in_city_page.BrandInCityPage(self.webdriver) <NEW_LINE> url = brandincitypage.get_url() <NEW_LINE> self.webdriver.get(url) <NEW_LINE> brandincitypage.input_loan_date_start(self.start_date) <NEW_LINE> brandincitypage.input_loan_date_end(self.end_date) <NEW_LINE> brandincitypage.click_search_button() <NEW_LINE> time.sleep(5) <NEW_LINE> brandincitypage.page_down() <NEW_LINE> time.sleep(1) <NEW_LINE> assert self.count == brandincitypage.get_count() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> tools.screenshot(self.webdriver, self.screenshot_path, casename) <NEW_LINE> raise e
按省区各品牌投放城市
6259904807d97122c421802d
class Config: <NEW_LINE> <INDENT> DEBUG = True <NEW_LINE> SQLALCHEMY_DATABASE_URI = "mysql://root:[email protected]:3306/ihome" <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = True <NEW_LINE> SQLALCHEMY_COMMIT_ON_TEARDOWN = True <NEW_LINE> HOST = "127.0.0.1" <NEW_LINE> POST = 6379 <NEW_LINE> NUM = 0 <NEW_LINE> SECRET_KEY = "fasdhnfjasf" <NEW_LINE> SESSION_TYPE = "redis" <NEW_LINE> SESSION_USE_SIGNER = True <NEW_LINE> SESSION_REDIS = redis.StrictRedis(host=HOST, port=POST) <NEW_LINE> SESSION_PERMANENT = False <NEW_LINE> PERMANENT_SESSION_LIFETIME = 86400 * 2
基本配置参数
62599048009cb60464d028c0
class ScalingFunction(AliasedFactory): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def scale_to_hertz(self, scale: float) -> float: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def hertz_to_scale(self, hertz: float) -> float: <NEW_LINE> <INDENT> pass
Converts a frequency to some scale and back again
6259904807d97122c421802e
class KinesisStreamHealthCheck: <NEW_LINE> <INDENT> def __init__(self, stream_conn, stream_name): <NEW_LINE> <INDENT> self._stream_connection = stream_conn <NEW_LINE> self.stream_name = stream_name <NEW_LINE> <DEDENT> def check_active(self): <NEW_LINE> <INDENT> return self._check_status() == 'ACTIVE' <NEW_LINE> <DEDENT> def check_deleting(self): <NEW_LINE> <INDENT> return self._check_status() == 'DELETING' <NEW_LINE> <DEDENT> def _check_status(self): <NEW_LINE> <INDENT> description_map = self._stream_connection.describe_stream(self.stream_name) <NEW_LINE> description = description_map.get('StreamDescription') <NEW_LINE> return description.get('StreamStatus')
a Kinesis stream health checker to get information on a given stream's operability
625990480fa83653e46f6268
class ListProductsPager: <NEW_LINE> <INDENT> def __init__( self, method: Callable[..., service.ListProductsResponse], request: service.ListProductsRequest, response: service.ListProductsResponse, *, metadata: Sequence[Tuple[str, str]] = () ): <NEW_LINE> <INDENT> self._method = method <NEW_LINE> self._request = service.ListProductsRequest(request) <NEW_LINE> self._response = response <NEW_LINE> self._metadata = metadata <NEW_LINE> <DEDENT> def __getattr__(self, name: str) -> Any: <NEW_LINE> <INDENT> return getattr(self._response, name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def pages(self) -> Iterator[service.ListProductsResponse]: <NEW_LINE> <INDENT> yield self._response <NEW_LINE> while self._response.next_page_token: <NEW_LINE> <INDENT> self._request.page_token = self._response.next_page_token <NEW_LINE> self._response = self._method(self._request, metadata=self._metadata) <NEW_LINE> yield self._response <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self) -> Iterator[products.Product]: <NEW_LINE> <INDENT> for page in self.pages: <NEW_LINE> <INDENT> yield from page.products <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
A pager for iterating through ``list_products`` requests. This class thinly wraps an initial :class:`google.cloud.channel_v1.types.ListProductsResponse` object, and provides an ``__iter__`` method to iterate through its ``products`` field. If there are more pages, the ``__iter__`` method will make additional ``ListProducts`` requests and continue to iterate through the ``products`` field on the corresponding responses. All the usual :class:`google.cloud.channel_v1.types.ListProductsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup.
6259904815baa7234946331c
class eClassSession(Base.WebSession): <NEW_LINE> <INDENT> METHODS = ['sign_all'] <NEW_LINE> def __init__(self, login, passwd): <NEW_LINE> <INDENT> link = '%s/index.php?page_size_change=1&noticeType=%d&signStatus=%d&numPerPage=%d' % (ENOTICE, EXPIRED, NOT_SIGNED, NUM_PAGE) <NEW_LINE> cred = {USERNAME_ID:login, PASSWORD_ID:passwd} <NEW_LINE> super().__init__(url_login=ECLASS, url_auth=ELOGIN, params=cred, agent=USER_AGENT) <NEW_LINE> self.notice = self.access(link) <NEW_LINE> if LOGIN_FAILURE_TITLE in self.notice: <NEW_LINE> <INDENT> raise Base.AuthenticationError <NEW_LINE> <DEDENT> <DEDENT> def sign_all(self): <NEW_LINE> <INDENT> for element in BS(self.notice, Base.PARSER).find_all(class_=NOTICE_LINK): <NEW_LINE> <INDENT> if UNSIGNED not in element.text: <NEW_LINE> <INDENT> self.session.post(re.sub(r'^javascript:sign\((\d+)\,(\d+)\)$', r'%s/sign_update.php?NoticeID=\1&StudentID=\2' % ENOTICE, element['href']))
Session for eClass IP 2.5
62599048e64d504609df9d96
class ServiceModel(object): <NEW_LINE> <INDENT> SHAPE_CLASSES = { 'structure': StructureShape, 'list': ListShape, 'map': MapShape, } <NEW_LINE> def __init__(self, service_description, service_name=None): <NEW_LINE> <INDENT> self._service_description = service_description <NEW_LINE> self.metadata = service_description.get('metadata', {}) <NEW_LINE> self._shape_resolver = ShapeResolver( service_description.get('shapes', {})) <NEW_LINE> self._signature_version = NOT_SET <NEW_LINE> self._service_name = service_name <NEW_LINE> <DEDENT> def shape_for(self, shape_name, member_traits=None): <NEW_LINE> <INDENT> return self._shape_resolver.get_shape_by_name( shape_name, member_traits) <NEW_LINE> <DEDENT> def resolve_shape_ref(self, shape_ref): <NEW_LINE> <INDENT> return self._shape_resolver.resolve_shape_ref(shape_ref) <NEW_LINE> <DEDENT> def operation_model(self, operation_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> model = self._service_description['operations'][operation_name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise OperationNotFoundError(operation_name) <NEW_LINE> <DEDENT> return OperationModel(model, self, operation_name) <NEW_LINE> <DEDENT> @CachedProperty <NEW_LINE> def documentation(self): <NEW_LINE> <INDENT> return self._service_description.get('documentation', '') <NEW_LINE> <DEDENT> @CachedProperty <NEW_LINE> def operation_names(self): <NEW_LINE> <INDENT> return list(self._service_description.get('operations', [])) <NEW_LINE> <DEDENT> @CachedProperty <NEW_LINE> def service_name(self): <NEW_LINE> <INDENT> if self._service_name is not None: <NEW_LINE> <INDENT> return self._service_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.endpoint_prefix <NEW_LINE> <DEDENT> <DEDENT> @CachedProperty <NEW_LINE> def signing_name(self): <NEW_LINE> <INDENT> signing_name = self.metadata.get('signingName') <NEW_LINE> if signing_name is None: <NEW_LINE> <INDENT> signing_name = self.endpoint_prefix <NEW_LINE> <DEDENT> return signing_name <NEW_LINE> <DEDENT> @CachedProperty <NEW_LINE> def api_version(self): <NEW_LINE> <INDENT> return self._get_metadata_property('apiVersion') <NEW_LINE> <DEDENT> @CachedProperty <NEW_LINE> def protocol(self): <NEW_LINE> <INDENT> return self._get_metadata_property('protocol') <NEW_LINE> <DEDENT> @CachedProperty <NEW_LINE> def endpoint_prefix(self): <NEW_LINE> <INDENT> return self._get_metadata_property('endpointPrefix') <NEW_LINE> <DEDENT> def _get_metadata_property(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.metadata[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise UndefinedModelAttributeError( '"%s" not defined in the metadata of the the model: %s' % (name, self)) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def signature_version(self): <NEW_LINE> <INDENT> if self._signature_version is NOT_SET: <NEW_LINE> <INDENT> signature_version = self.metadata.get('signatureVersion') <NEW_LINE> self._signature_version = signature_version <NEW_LINE> <DEDENT> return self._signature_version <NEW_LINE> <DEDENT> @signature_version.setter <NEW_LINE> def signature_version(self, value): <NEW_LINE> <INDENT> self._signature_version = value
:ivar service_description: The parsed service description dictionary.
62599048507cdc57c63a6129
class EdxInstanceExternalEnrollment(BaseExternalEnrollment): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "openedX" <NEW_LINE> <DEDENT> def _get_enrollment_headers(self): <NEW_LINE> <INDENT> headers = { "Accept": "application/json", "Content-Type": "application/json", "X-Edx-Api-Key": settings.EDX_API_KEY, } <NEW_LINE> return headers <NEW_LINE> <DEDENT> def _get_enrollment_data(self, data, course_settings): <NEW_LINE> <INDENT> user, _ = get_user(email=data.get("user_email")) <NEW_LINE> return { "user": user.username, "is_active": data.get("is_active", True), "mode": course_settings.get( "external_enrollment_mode_override", data.get("course_mode") ), "course_details": { "course_id": course_settings.get("external_course_run_id") } } <NEW_LINE> <DEDENT> def _get_enrollment_url(self, course_settings): <NEW_LINE> <INDENT> return course_settings.get("external_enrollment_api_url")
EdxInstanceExternalEnrollment class.
6259904821a7993f00c672f5
@attr(rank=101, author='wong', scenario='GraphTriggers', doc='', ) <NEW_LINE> class GraphTriggers(object): <NEW_LINE> <INDENT> @attr(duration=0) <NEW_LINE> def test_100_provider_node(self): <NEW_LINE> <INDENT> sshifc = self.get_ssh() <NEW_LINE> cfgifc = self.get_config() <NEW_LINE> emifc = self.get_em() <NEW_LINE> LOG.info("Deleting Provider Terminal Node...") <NEW_LINE> self.set_data('redeploy', False, overwrite=True) <NEW_LINE> <DEDENT> def test_101_consumer_node(self): <NEW_LINE> <INDENT> sshifc = self.get_ssh() <NEW_LINE> cfgifc = self.get_config() <NEW_LINE> emifc = self.get_em() <NEW_LINE> LOG.info("Deleting Consumer Terminal Node...") <NEW_LINE> self.set_data('redeploy', False, overwrite=True) <NEW_LINE> <DEDENT> def test_102_rs_node_to_mfunc(self): <NEW_LINE> <INDENT> sshifc = self.get_ssh() <NEW_LINE> cfgifc = self.get_config() <NEW_LINE> emifc = self.get_em() <NEW_LINE> LOG.info("Deleting vnsRsNodeToMFunc...") <NEW_LINE> self.set_data('redeploy', False, overwrite=True)
This is like a healper class for trigger tests. All trigger tests can be run on any graph. To use this class: class Tests(InterfaceTestCase, GraphTriggers): ...
62599048be383301e0254ba5
class Field(GDALBase): <NEW_LINE> <INDENT> def __init__(self, feat, index): <NEW_LINE> <INDENT> self._feat = feat <NEW_LINE> self._index = index <NEW_LINE> fld_ptr = capi.get_feat_field_defn(feat.ptr, index) <NEW_LINE> if not fld_ptr: <NEW_LINE> <INDENT> raise GDALException('Cannot create OGR Field, invalid pointer given.') <NEW_LINE> <DEDENT> self.ptr = fld_ptr <NEW_LINE> self.__class__ = OGRFieldTypes[self.type] <NEW_LINE> if isinstance(self, OFTReal) and self.precision == 0: <NEW_LINE> <INDENT> self.__class__ = OFTInteger <NEW_LINE> self._double = True <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.value).strip() <NEW_LINE> <DEDENT> def as_double(self): <NEW_LINE> <INDENT> return capi.get_field_as_double(self._feat.ptr, self._index) <NEW_LINE> <DEDENT> def as_int(self): <NEW_LINE> <INDENT> return capi.get_field_as_integer(self._feat.ptr, self._index) <NEW_LINE> <DEDENT> def as_string(self): <NEW_LINE> <INDENT> string = capi.get_field_as_string(self._feat.ptr, self._index) <NEW_LINE> return force_text(string, encoding=self._feat.encoding, strings_only=True) <NEW_LINE> <DEDENT> def as_datetime(self): <NEW_LINE> <INDENT> yy, mm, dd, hh, mn, ss, tz = [c_int() for i in range(7)] <NEW_LINE> status = capi.get_field_as_datetime( self._feat.ptr, self._index, byref(yy), byref(mm), byref(dd), byref(hh), byref(mn), byref(ss), byref(tz)) <NEW_LINE> if status: <NEW_LINE> <INDENT> return (yy, mm, dd, hh, mn, ss, tz) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise GDALException('Unable to retrieve date & time information from the field.') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> name = capi.get_field_name(self.ptr) <NEW_LINE> return force_text(name, encoding=self._feat.encoding, strings_only=True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def precision(self): <NEW_LINE> <INDENT> return capi.get_field_precision(self.ptr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return capi.get_field_type(self.ptr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def type_name(self): <NEW_LINE> <INDENT> return capi.get_field_type_name(self.type) <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self.as_string() <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return capi.get_field_width(self.ptr)
This class wraps an OGR Field, and needs to be instantiated from a Feature object.
62599048379a373c97d9a3b7
class BackupUDBInstanceBinlogResponseSchema(schema.ResponseSchema): <NEW_LINE> <INDENT> fields = {}
BackupUDBInstanceBinlog - 备份UDB指定时间段的binlog列表
62599048b830903b9686ee41
class ProductList(b.Base): <NEW_LINE> <INDENT> admin = False <NEW_LINE> method = "GET" <NEW_LINE> url = "products" <NEW_LINE> documentation_type = "product_list"
List available products for the current users.
62599048d6c5a102081e34a9
class TimedRoute(Route): <NEW_LINE> <INDENT> def __init__(self, route, distances, speed, frequency): <NEW_LINE> <INDENT> self.speed = speed <NEW_LINE> self.frequency = frequency <NEW_LINE> Route.__init__(self, route, distances) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_start_and_end(cls, start_location, end_location, speed, frequency): <NEW_LINE> <INDENT> route, distances = cls._generate_route_from_start_and_end(start_location, end_location) <NEW_LINE> timed_route = cls(route, distances, speed, frequency) <NEW_LINE> timed_route.upsample_route() <NEW_LINE> return timed_route <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_gpx(cls, gpx_source_path, speed, frequency): <NEW_LINE> <INDENT> route, distances = cls._generate_route_from_gpx(gpx_source_path) <NEW_LINE> timed_route = cls(route, distances, speed, frequency) <NEW_LINE> timed_route.upsample_route() <NEW_LINE> return timed_route <NEW_LINE> <DEDENT> def upsample_route(self): <NEW_LINE> <INDENT> points_per_meter = self.frequency/self.speed <NEW_LINE> new_route = [] <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> new_route.append(self.route[0]) <NEW_LINE> <DEDENT> for i in range(len(self.distances)): <NEW_LINE> <INDENT> distance = self.distances[i] <NEW_LINE> start_point = self.route[i] <NEW_LINE> end_point = self.route[i+1] <NEW_LINE> new_route.append(start_point) <NEW_LINE> points_needed = int(distance*points_per_meter)-1 <NEW_LINE> if points_needed > 0: <NEW_LINE> <INDENT> latitude_delta = (end_point.latitude-start_point.latitude) / points_needed <NEW_LINE> longitude_delta = (end_point.longitude-start_point.longitude) / points_needed <NEW_LINE> altitude_delta = (end_point.altitude-start_point.altitude) / points_needed <NEW_LINE> for j in range(1, points_needed): <NEW_LINE> <INDENT> new_point = Location(start_point.latitude + latitude_delta*j, start_point.longitude + longitude_delta*j, start_point.altitude + altitude_delta*j) <NEW_LINE> new_route.append(new_point) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> new_route.append(self.route[-1]) <NEW_LINE> self.route = new_route <NEW_LINE> self.distances = [1/points_per_meter for x in range(len(new_route)-1)] <NEW_LINE> <DEDENT> def write_route(self, file_name): <NEW_LINE> <INDENT> write_array = [] <NEW_LINE> time = 0.0 <NEW_LINE> for location in self.route: <NEW_LINE> <INDENT> write_array.append(("%.1f" % (time,),)+location.get_xyz_tuple()) <NEW_LINE> time = time + (1/self.frequency) <NEW_LINE> <DEDENT> _write_to_csv(FILE_FOLDER_PATH+file_name, write_array)
An object for a route that has a desired speed and point frequency. Attributes: speed: how fast the person moves through the route in meters/second frequency: how many points per second the timed route should have (Hz) route: a list of Location objects for each point on the route distances: a list of distances for each pair of consecutive locations in meters
625990484e696a045264e7e7
class _LocIndexer: <NEW_LINE> <INDENT> def __init__(self, data_array): <NEW_LINE> <INDENT> self.data_array = data_array <NEW_LINE> <DEDENT> def expand(self, key): <NEW_LINE> <INDENT> if not is_dict_like(key): <NEW_LINE> <INDENT> labels = expanded_indexer(key, self.data_array.ndim) <NEW_LINE> key = dict(zip(self.data_array.dims, labels)) <NEW_LINE> <DEDENT> return key <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> key = _reassign_quantity_indexer(self.data_array, self.expand(key)) <NEW_LINE> return self.data_array.loc[key] <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> key = _reassign_quantity_indexer(self.data_array, self.expand(key)) <NEW_LINE> self.data_array.loc[key] = value
Provide the unit-wrapped .loc indexer for data arrays.
6259904807d97122c421802f
class calldef_matcher_t( declaration_matcher_t ): <NEW_LINE> <INDENT> def __init__( self, name=None, return_type=None, arg_types=None, decl_type=None, header_dir=None, header_file=None): <NEW_LINE> <INDENT> if None is decl_type: <NEW_LINE> <INDENT> decl_type = calldef.calldef_t <NEW_LINE> <DEDENT> declaration_matcher_t.__init__( self , name=name , decl_type=decl_type , header_dir=header_dir , header_file=header_file ) <NEW_LINE> self.return_type = return_type <NEW_LINE> self.arg_types = arg_types <NEW_LINE> <DEDENT> def __call__( self, decl ): <NEW_LINE> <INDENT> if not super( calldef_matcher_t, self ).__call__( decl ): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not None is self.return_type and not self.__compare_types( self.return_type, decl.return_type ): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.arg_types: <NEW_LINE> <INDENT> if isinstance( self.arg_types, (types.ListType, types.TupleType)): <NEW_LINE> <INDENT> if len(self.arg_types) != len( decl.arguments ): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for type_or_str, arg in zip( self.arg_types, decl.arguments ): <NEW_LINE> <INDENT> if None == type_or_str: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not self.__compare_types( type_or_str, arg.type ): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def __compare_types( self, type_or_str, type ): <NEW_LINE> <INDENT> assert type_or_str <NEW_LINE> if type is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if isinstance( type_or_str, cpptypes.type_t ): <NEW_LINE> <INDENT> if type_or_str != type: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if type_or_str != type.decl_string: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def __str__( self ): <NEW_LINE> <INDENT> msg = [ super( calldef_matcher_t, self ).__str__() ] <NEW_LINE> if msg == [ 'any' ]: <NEW_LINE> <INDENT> msg = [] <NEW_LINE> <DEDENT> if not None is self.return_type: <NEW_LINE> <INDENT> msg.append( '(return type==%s)' % str(self.return_type) ) <NEW_LINE> <DEDENT> if self.arg_types: <NEW_LINE> <INDENT> for i in range( len( self.arg_types ) ): <NEW_LINE> <INDENT> if self.arg_types[i] is None: <NEW_LINE> <INDENT> msg.append( '(arg %d type==any)' % i ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg.append( '(arg %d type==%s)' % ( i, str( self.arg_types[i] ) ) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not msg: <NEW_LINE> <INDENT> msg.append( 'any' ) <NEW_LINE> <DEDENT> return ' and '.join( msg )
Instance of this class will match callable by the following criteria: * :class:`declaration_matcher_t` criteria * return type. For example: :class:`int_t` or 'int' * argument types
6259904823e79379d538d88c
class v4l2src_bin(gst.Bin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> gst.Bin.__init__(self) <NEW_LINE> self.set_name('jamedia_camara_bin') <NEW_LINE> camara = gst.element_factory_make("v4l2src", "v4l2src") <NEW_LINE> caps = gst.Caps('video/x-raw-yuv,framerate=30/1') <NEW_LINE> camerafilter = gst.element_factory_make("capsfilter", "camera_filter") <NEW_LINE> camerafilter.set_property("caps", caps) <NEW_LINE> self.add(camara) <NEW_LINE> self.add(camerafilter) <NEW_LINE> camara.link(camerafilter) <NEW_LINE> self.add_pad(gst.GhostPad("src", camerafilter.get_static_pad("src"))) <NEW_LINE> <DEDENT> def set_device(self, device): <NEW_LINE> <INDENT> camara = self.get_by_name("v4l2src") <NEW_LINE> camara.set_property("device", device)
Bin de entrada de camara v4l2src.
6259904815baa7234946331f
class cond_rv_frozen(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(cond_rv_frozen, self).__init__()
Class which encapsulates common functionality between all conditional distributions.
625990487cff6e4e811b6dc7
class Refused(DNSException): <NEW_LINE> <INDENT> code = 5
The server refused to answer for the reply
62599048d4950a0f3b111809
@register_plugin <NEW_LINE> class FFTPlugin(Device, version_type='ADCore'): <NEW_LINE> <INDENT> ... <NEW_LINE> _default_suffix = 'FFT1:' <NEW_LINE> _suffix_re = r'FFT\d:' <NEW_LINE> _plugin_type = 'NDPluginFFT'
Serves as a base class for other versions
62599048b5575c28eb713690
class CustomIndexDashboard(Dashboard): <NEW_LINE> <INDENT> def init_with_context(self, context): <NEW_LINE> <INDENT> site_name = get_admin_site_name(context) <NEW_LINE> self.children.append(modules.AppList( _('Site Components'), collapsible=True, column=1, css_classes=('collapse closed',), exclude=('django.contrib.*',), )) <NEW_LINE> self.children.append(modules.ModelList( _('System Administration'), column=1, collapsible=True, css_classes=('collapse closed',), models=('django.contrib.*',), )) <NEW_LINE> self.children.append(modules.LinkList( _('Media Management'), column=2, children=[ { 'title': _('FileBrowser'), 'url': './filebrowser/browse/', 'external': False, }, ] ))
Custom index dashboard for www.
6259904824f1403a92686294
class FreeplaneCannotCompareNodeWithDifferentID(FreeplaneError): <NEW_LINE> <INDENT> pass
Will be raised when a request or node compare is done agains two nodes with different ID. The whole code works on the assumption that ID are unique
62599048a79ad1619776b40f
class SolowModel(problems.IVP): <NEW_LINE> <INDENT> def __init__(self, f, k_star, params): <NEW_LINE> <INDENT> rhs = self._rhs_factory(f) <NEW_LINE> self._equilbrium_capital = k_star <NEW_LINE> self._intensive_output = f <NEW_LINE> super(SolowModel, self).__init__(self._initial_condition, 1, 1, params, rhs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def equilibrium_capital(self): <NEW_LINE> <INDENT> return self._equilbrium_capital <NEW_LINE> <DEDENT> @property <NEW_LINE> def intensive_output(self): <NEW_LINE> <INDENT> return self._intensive_output <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _initial_condition(t, k, k0, **params): <NEW_LINE> <INDENT> return [k - k0] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _solow_model(cls, t, k, f, delta, g, n, s, **params): <NEW_LINE> <INDENT> return [s * f(k, **params) - (g + n + delta) * k] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _rhs_factory(cls, f): <NEW_LINE> <INDENT> return functools.partial(cls._solow_model, f=f)
Class representing a generic Solow growth model. Attributes ---------- equilibrium_capital : function Equilibrium value for capital (per unit effective labor). intensive_output : function Output (per unit effective labor supply). params : dict(str: float) Dictionary of model parameters.
625990488e71fb1e983bce54
class Actions(ActionsBase): <NEW_LINE> <INDENT> def configure(self, serviceObj): <NEW_LINE> <INDENT> from CloudscalerLibcloud.imageutil import registerImage <NEW_LINE> name = 'Routeros 6.31' <NEW_LINE> registerImage(serviceObj, name, 'Linux', 10)
process for install ------------------- step1: prepare actions step2: check_requirements action step3: download files & copy on right location (hrd info is used) step4: configure action step5: check_uptime_local to see if process stops (uses timeout $process.stop.timeout) step5b: if check uptime was true will do stop action and retry the check_uptime_local check step5c: if check uptime was true even after stop will do halt action and retry the check_uptime_local check step6: use the info in the hrd to start the application step7: do check_uptime_local to see if process starts step7b: do monitor_local to see if package healthy installed & running step7c: do monitor_remote to see if package healthy installed & running, but this time test is done from central location
6259904894891a1f408ba0bd
class AddGraphLearnedPositionalEmbeddings(PositionalEncoder): <NEW_LINE> <INDENT> def __init__(self, num_embed: int, max_seq_len: int, prefix: str, embed_weight: Optional[mx.sym.Symbol] = None) -> None: <NEW_LINE> <INDENT> self.num_embed = num_embed <NEW_LINE> self.max_seq_len = max_seq_len <NEW_LINE> self.prefix = prefix <NEW_LINE> if embed_weight is not None: <NEW_LINE> <INDENT> self.embed_weight = embed_weight <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.embed_weight = mx.sym.Variable(prefix + "weight") <NEW_LINE> <DEDENT> <DEDENT> def encode(self, data: mx.sym.Symbol, data_length: Optional[mx.sym.Symbol], seq_len: int, metadata=None) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]: <NEW_LINE> <INDENT> positions = metadata[1] <NEW_LINE> pos_embedding = mx.sym.Embedding(data=positions, input_dim=self.max_seq_len, weight=self.embed_weight, output_dim=self.num_embed, name=self.prefix + "pos_embed") <NEW_LINE> return mx.sym.broadcast_add(data, pos_embedding, name="%s_add" % self.prefix), data_length, seq_len <NEW_LINE> <DEDENT> def encode_positions(self, positions: mx.sym.Symbol, data: mx.sym.Symbol) -> mx.sym.Symbol: <NEW_LINE> <INDENT> pos_embedding = mx.sym.Embedding(data=positions, input_dim=self.max_seq_len, weight=self.embed_weight, output_dim=self.num_embed, name=self.prefix + "pos_embed") <NEW_LINE> return mx.sym.broadcast_add(data, pos_embedding, name="%s_add" % self.prefix) <NEW_LINE> <DEDENT> def get_num_hidden(self) -> int: <NEW_LINE> <INDENT> return self.num_embed <NEW_LINE> <DEDENT> def get_max_seq_len(self) -> Optional[int]: <NEW_LINE> <INDENT> return self.max_seq_len
Takes an encoded sequence and adds positional embeddings to it, which are learned jointly. Note that this will limited the maximum sentence length during decoding. :param num_embed: Embedding size. :param max_seq_len: Maximum sequence length. :param prefix: Name prefix for symbols of this encoder. :param embed_weight: Optionally use an existing embedding matrix instead of creating a new one.
6259904830c21e258be99b95
class TestMemmapCoalesce(testlib.SimpleTestCase): <NEW_LINE> <INDENT> PARAMETERS = dict(commandline="memmap %(pids)s --coalesce", pid=2624)
Make sure that memmaps are coalesced properly.
62599048b57a9660fecd2e0c
class IntConst(Token): <NEW_LINE> <INDENT> name = "integerConstant" <NEW_LINE> def __init__(self, int_value: int) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.value = int(int_value)
a literal int
625990483c8af77a43b68905
class Node(NamedTuple): <NEW_LINE> <INDENT> ip: bytes <NEW_LINE> port: bytes
ip-port pair, used to identify one side of the connection
62599048596a897236128f77
class LastAction(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey('User') <NEW_LINE> action = models.CharField(blank=False, max_length=128) <NEW_LINE> created = models.DateTimeField(auto_now_add=True)
Tracks user's LastAction
6259904873bcbd0ca4bcb61d
class Tea: <NEW_LINE> <INDENT> def __init__(self, name, origin): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._origin = origin <NEW_LINE> <DEDENT> def getRecipe(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def getOrigin(self): <NEW_LINE> <INDENT> return self._origin
Represents a cup of tea object
6259904815baa72349463321
class ManagerProxy: <NEW_LINE> <INDENT> def __init__(self, db: Order, instance: _man.StatusManager): <NEW_LINE> <INDENT> self._db, self._instance = db, instance <NEW_LINE> <DEDENT> def json(self): <NEW_LINE> <INDENT> return self._instance.json() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self._instance.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def current(self) -> fsm.State: <NEW_LINE> <INDENT> return self._instance.current <NEW_LINE> <DEDENT> @property <NEW_LINE> def events(self) -> List[fsm.Event]: <NEW_LINE> <INDENT> return self._instance.events <NEW_LINE> <DEDENT> def stop(self) -> NoReturn: <NEW_LINE> <INDENT> self._instance.stop() <NEW_LINE> self._db.instance = pickle.dumps(self._instance) <NEW_LINE> self._db.save() <NEW_LINE> <DEDENT> def start(self) -> NoReturn: <NEW_LINE> <INDENT> self._instance.start() <NEW_LINE> self._db.instance = pickle.dumps(self._instance) <NEW_LINE> self._db.save() <NEW_LINE> <DEDENT> def handle(self, event: fsm.Event) -> NoReturn: <NEW_LINE> <INDENT> self._instance.handle(event) <NEW_LINE> self._db.instance = pickle.dumps(self._instance) <NEW_LINE> self._db.save()
代理Manager的访问 add 函数不代理 - 实例化后的状态机不应该改变状态图
625990487cff6e4e811b6dc9
class CertificateEmail(Resource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'location': {'required': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'kind': {'key': 'kind', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'email_id': {'key': 'properties.emailId', 'type': 'str'}, 'time_stamp': {'key': 'properties.timeStamp', 'type': 'iso-8601'}, } <NEW_LINE> def __init__(self, location, name=None, kind=None, type=None, tags=None, email_id=None, time_stamp=None): <NEW_LINE> <INDENT> super(CertificateEmail, self).__init__(name=name, kind=kind, location=location, type=type, tags=tags) <NEW_LINE> self.email_id = email_id <NEW_LINE> self.time_stamp = time_stamp
SSL certificate email. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :param name: Resource Name. :type name: str :param kind: Kind of resource. :type kind: str :param location: Resource Location. :type location: str :param type: Resource type. :type type: str :param tags: Resource tags. :type tags: dict :param email_id: Email id. :type email_id: str :param time_stamp: Time stamp. :type time_stamp: datetime
62599048d4950a0f3b11180a
class CollisionSeriesKindle(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.modeling_cloth_collision_series_kindle" <NEW_LINE> bl_label = "Modeling Cloth Collision Series Kindle" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> collision_series(False) <NEW_LINE> return {'FINISHED'}
Support my addons by checking out my awesome sci fi books
6259904891af0d3eaad3b1b5
class TestV1ConfigMapEnvSource(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testV1ConfigMapEnvSource(self): <NEW_LINE> <INDENT> pass
V1ConfigMapEnvSource unit test stubs
6259904863b5f9789fe864fd
class APIComponent(ContainerComponent): <NEW_LINE> <INDENT> def __init__( self, components, use_redis=True, do_profiling=False, disable_ratelimits=False, cache_time: int = None, ): <NEW_LINE> <INDENT> super().__init__(components) <NEW_LINE> app.config["owapi_use_redis"] = use_redis <NEW_LINE> app.config["owapi_do_profiling"] = do_profiling <NEW_LINE> app.config["owapi_disable_ratelimits"] = disable_ratelimits <NEW_LINE> app.config["owapi_cache_time"] = cache_time <NEW_LINE> <DEDENT> async def start(self, ctx): <NEW_LINE> <INDENT> self.add_component( "kyoukai", KyoukaiComponent, ip="127.0.0.1", port=4444, app="app:app", template_renderer=None, ) <NEW_LINE> ctx.session = ClientSession(headers={"User-Agent": "owapi scraper/1.0.1"}) <NEW_LINE> if app.config["owapi_use_redis"]: <NEW_LINE> <INDENT> from asphalt.redis.component import RedisComponent <NEW_LINE> self.add_component("redis", RedisComponent) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.warning("redis is disabled by config, rate limiting and caching not available") <NEW_LINE> <DEDENT> await super().start(ctx) <NEW_LINE> logger.info("Started OWAPI server.")
Container for other components. I think.
625990488e71fb1e983bce56
class RunYearly(Algo): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(RunYearly, self).__init__() <NEW_LINE> self.last_date = None <NEW_LINE> <DEDENT> def __call__(self, target): <NEW_LINE> <INDENT> now = target.now <NEW_LINE> if now is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.last_date is None: <NEW_LINE> <INDENT> self.last_date = now <NEW_LINE> return False <NEW_LINE> <DEDENT> result = False <NEW_LINE> if now.year != self.last_date.year: <NEW_LINE> <INDENT> result = True <NEW_LINE> <DEDENT> self.last_date = now <NEW_LINE> return result
Returns True on year change. Returns True if the target.now's year has changed since the last run, if not returns False. Useful for yearly rebalancing strategies. Note: This algo will typically run on the first day of the year (assuming we have daily data)
6259904850485f2cf55dc319
class TokenSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = token_model <NEW_LINE> fields = ["key"]
登入帐号的令牌
6259904826068e7796d4dcd7
class ItemStatus(ModelNormal): <NEW_LINE> <INDENT> allowed_values = { } <NEW_LINE> validations = { } <NEW_LINE> @cached_property <NEW_LINE> def additional_properties_type(): <NEW_LINE> <INDENT> lazy_import() <NEW_LINE> return (bool, date, datetime, dict, float, int, list, str, none_type,) <NEW_LINE> <DEDENT> _nullable = True <NEW_LINE> @cached_property <NEW_LINE> def openapi_types(): <NEW_LINE> <INDENT> lazy_import() <NEW_LINE> return { 'investments': (ItemStatusInvestments,), 'transactions': (ItemStatusTransactions,), 'last_webhook': (ItemStatusLastWebhook,), } <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def discriminator(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attribute_map = { 'investments': 'investments', 'transactions': 'transactions', 'last_webhook': 'last_webhook', } <NEW_LINE> _composed_schemas = {} <NEW_LINE> required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) <NEW_LINE> @convert_js_args_to_python_args <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _check_type = kwargs.pop('_check_type', True) <NEW_LINE> _spec_property_naming = kwargs.pop('_spec_property_naming', False) <NEW_LINE> _path_to_item = kwargs.pop('_path_to_item', ()) <NEW_LINE> _configuration = kwargs.pop('_configuration', None) <NEW_LINE> _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) <NEW_LINE> if args: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) <NEW_LINE> <DEDENT> self._data_store = {} <NEW_LINE> self._check_type = _check_type <NEW_LINE> self._spec_property_naming = _spec_property_naming <NEW_LINE> self._path_to_item = _path_to_item <NEW_LINE> self._configuration = _configuration <NEW_LINE> self._visited_composed_classes = _visited_composed_classes + (self.__class__,) <NEW_LINE> for var_name, var_value in kwargs.items(): <NEW_LINE> <INDENT> if var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> setattr(self, var_name, var_value)
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values.
625990484e696a045264e7e9
class SubVisitor: <NEW_LINE> <INDENT> def subst(self, node): <NEW_LINE> <INDENT> method_name = 'subst_' + type(node).__name__ <NEW_LINE> substitution = getattr(self, method_name, self.generic_subst) <NEW_LINE> return substitution(node) <NEW_LINE> <DEDENT> def generic_subst(self, node): <NEW_LINE> <INDENT> raise Exception('No substitute_{} method'.format(type(node).__name__))
generic visitor class for substitution
6259904815baa72349463322
class BalancedCard(BalancedThing): <NEW_LINE> <INDENT> thing_type = 'card' <NEW_LINE> def __getitem__(self, name): <NEW_LINE> <INDENT> if name == 'id': <NEW_LINE> <INDENT> out = self._customer.href if self._customer is not None else None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = { 'address_1': 'address.line1', 'address_2': 'meta.address_2', 'country': 'meta.country', 'city_town': 'meta.city_town', 'zip': 'address.postal_code', 'state': 'meta.region', 'last4': 'number', 'last_four': 'number', }.get(name, name) <NEW_LINE> out = self._get(name) <NEW_LINE> <DEDENT> return out
This is a dict-like wrapper around a Balanced Account.
62599048287bf620b6272f7a