code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@click.command(cls=MagicDocCLI, context_settings=CONTEXT_SETTINGS) <NEW_LINE> @click.version_option() <NEW_LINE> @click.pass_context <NEW_LINE> def cli(ctx): <NEW_LINE> <INDENT> pass
CloudMage: MagicDoc Project Documentation Utility
625941f4925a0f43d254a490
def parse_request(self): <NEW_LINE> <INDENT> if not super(DialogueSentenceView, self).parse_request(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.template_file = getattr(self.form_class.Meta, "form_template", "dialogue_sentence_form.html") <NEW_LINE> return True
Parse request data. Returns: boolean: Parse success.
625941f426238365f5f0f489
def _GenerateCreateValueFromType(self, type_, var, is_ptr): <NEW_LINE> <INDENT> underlying_type = self._type_helper.FollowRef(type_) <NEW_LINE> if (underlying_type.property_type == PropertyType.CHOICES or underlying_type.property_type == PropertyType.OBJECT): <NEW_LINE> <INDENT> if is_ptr: <NEW_LINE> <INDENT> return '(...
Generates the statement to create a base::Value given a type. type_: The type of the values being converted. var: The name of the variable. is_ptr: Whether |type_| is optional.
625941f49b70327d1c4e13eb
def compute_tree(self, state): <NEW_LINE> <INDENT> fringe = Stack() <NEW_LINE> visited = set() <NEW_LINE> meta = dict() <NEW_LINE> meta[state] = (None, None) <NEW_LINE> fringe.push(state) <NEW_LINE> while not fringe.isEmpty(): <NEW_LINE> <INDENT> current_node = fringe.pop() <NEW_LINE> if current_node.isWin(): <NEW_LINE...
Given a pacman state, computes a path from that state to a state where pacman has eaten all the food dots. Arguments: ---------- - `state`: the current game state. Return: ------- - A list of legal moves as defined in `game.Directions`
625941f48e71fb1e9831ddb9
def main(retry_iterator=1): <NEW_LINE> <INDENT> crawlers = GLUE.get_crawlers() <NEW_LINE> try: <NEW_LINE> <INDENT> crawl_exist = False <NEW_LINE> for i in crawlers['Crawlers']: <NEW_LINE> <INDENT> if i['Name'] == ARGS['crawler_name']: <NEW_LINE> <INDENT> crawl_exist = True <NEW_LINE> result = "Crawler with this name ex...
Create AWS Glue Crawler
625941f43eb6a72ae02ecb02
def test_nonIntPartsToChangeVersionsScript(self): <NEW_LINE> <INDENT> versionChanger = ChangeVersionsScript() <NEW_LINE> self.assertRaises(SystemExit, versionChanger.main, ["my united.states.of prewhatever"])
L{changeVersionsScript} raises SystemExit when the version number isn't made out of numbers.
625941f485dfad0860c3b470
def is_set_max_noutput_items(self): <NEW_LINE> <INDENT> return _spacegrant_swig.DeNRZI_sptr_is_set_max_noutput_items(self)
is_set_max_noutput_items(DeNRZI_sptr self) -> bool
625941f4d58c6744b4258270
def get_interp(self, days=None, date=None): <NEW_LINE> <INDENT> return self.parent.get_interp(self.key, days, date)
Will lookup value interpolated to @days or @date. The function requires one, and only one, time indicator in terms of @days or @date. If the @date variable is given that should be Python datetime instance. vec = sum["WWCT:A-3"] vec.get_interp(days = 100) vec.get_interp(date = datetime.date(year, month, day))...
625941f43d592f4c4ed1d66f
def find_vpn_service(self, name_or_id, ignore_missing=True): <NEW_LINE> <INDENT> return self._find(_vpn_service.VPNService, name_or_id, ignore_missing=ignore_missing)
Find a single vpn service :param name_or_id: The name or ID of a vpn service. :param bool ignore_missing: When set to ``False`` :class:`~openstack.exceptions.ResourceNotFound` will be raised when the resource does not exist. When set to ``True``, None will be returned when ...
625941f4f8510a7c17cf9d14
def block(self, interval=0.1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.wait(states.EXITING, interval=interval, channel='main') <NEW_LINE> <DEDENT> except (KeyboardInterrupt, IOError): <NEW_LINE> <INDENT> self.log('Keyboard Interrupt: shutting down bus') <NEW_LINE> self.exit() <NEW_LINE> <DEDENT> except System...
Wait for the EXITING state, KeyboardInterrupt or SystemExit. This function is intended to be called only by the main thread. After waiting for the EXITING state, it also waits for all threads to terminate, and then calls os.execv if self.execv is True. This design allows another thread to call bus.restart, yet have th...
625941f4cb5e8a47e48b80b2
def transform_and_store_expr(expr): <NEW_LINE> <INDENT> expr_pre_stmts, transformed_expr = transform_expr(expr) <NEW_LINE> tmp = new_expression_replacing_var("tmp", expr) <NEW_LINE> return expr_pre_stmts + [irt.AssignStmt(tmp, transformed_expr)], tmp
Transforms the given expression and returns a variable that contains its value. :param lal.Expr expr: An arbitrary expression. :rtype: irt.Identifier
625941f4be383301e01b5a8c
def testModificationTime(self): <NEW_LINE> <INDENT> path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_HFS, identifier=self._IDENTIFIER_ANOTHER_FILE, location='/a_directory/another_file', parent=self._raw_path_spec) <NEW_LINE> file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) <...
Test the modification_time property.
625941f491af0d3eaac9c030
def skipWithoutRbacUser(func): <NEW_LINE> <INDENT> def _decorated(*args, **kwargs): <NEW_LINE> <INDENT> self = args[0] <NEW_LINE> if not hasattr(self, 'user') or self.user is None: <NEW_LINE> <INDENT> return self.skipTest('No RBAC user could be loaded') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return func(*args, *...
TestCase decorator which skips the test if an RBAC user is required but could not be loaded.
625941f40fa83653e46575ca
def test_erp_home_realm_oom(dev, apdev): <NEW_LINE> <INDENT> check_erp_capa(dev[0]) <NEW_LINE> params = int_eap_server_params() <NEW_LINE> params['erp_send_reauth_start'] = '1' <NEW_LINE> params['erp_domain'] = 'example.com' <NEW_LINE> params['eap_server_erp'] = '1' <NEW_LINE> params['disable_pmksa_caching'] = '1' <NEW...
ERP and home realm OOM
625941f473bcbd0ca4b2c689
def select_route_submenu(self): <NEW_LINE> <INDENT> is_selected = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.logger.info('Start: select route submenu') <NEW_LINE> self._home_page.select_route_submenu() <NEW_LINE> is_selected = True <NEW_LINE> <DEDENT> except WebDriverException as exp: <NEW_LINE> <INDENT> self.logger...
Returning select route submenu Implementing logging for select route submenu functionality :return: True/False
625941f43317a56b8693a25c
def generateToken(expiry, deposit=False, withdraw=False, positions=False, user=False): <NEW_LINE> <INDENT> headers = { 'content-type': "application/json", 'accept': "application/json", } <NEW_LINE> scopes = [] <NEW_LINE> if deposit: <NEW_LINE> <INDENT> scopes += "deposit" <NEW_LINE> <DEDENT> if withdraw: <NEW_LINE> <IN...
Using the given scopes, generate token to give access to different parts of the public API. Parameters- expiry: token expiry in seconds. deposit: Allow deposit (optional) withdraw: Allow withdraw (optional) positions: Allow opening or closing trade positions (optional) user: Allow access to user information (optional)
625941f4fbf16365ca6f67e5
@task <NEW_LINE> def install_python_dependencies(): <NEW_LINE> <INDENT> from virtualenv import VIRTUALENVDIR <NEW_LINE> from virtualenv import VIRTUALENVNAME <NEW_LINE> from virtualenv import VIRTUALENVWRAPPER_ACTIVATE <NEW_LINE> from virtualenv import virtualenv <NEW_LINE> sudo('apt-get -y install python-dev') <NEW_LI...
Install required Python packages
625941f4e8904600ed9f254b
def pack_to(self, writer): <NEW_LINE> <INDENT> writer.write_object_varray(self._notes, 'B')
Writes the current ReplaceNotesInSong to the given BinaryWriter.
625941f497e22403b379d5af
def _ClientPathToString(client_path, prefix=""): <NEW_LINE> <INDENT> return os.path.join(prefix, client_path.client_id, client_path.vfs_path)
Returns a path-like String of client_path with optional prefix.
625941f40a366e3fb873ee34
def _transposes(list_of_splited_words): <NEW_LINE> <INDENT> transposes = [] <NEW_LINE> for beg, ending in list_of_splited_words: <NEW_LINE> <INDENT> if len(ending) > 1: <NEW_LINE> <INDENT> transposes.append(beg + ending[1] + ending[0] + ending[2:]) <NEW_LINE> <DEDENT> <DEDENT> return transposes
Swaps 2 letters of the splited words in the list. The ones that swaps are the last character of the first element of the tuple with the first character of the second element in the tuple.
625941f4046cf37aa974d354
def search_field(self, html, field, pattern): <NEW_LINE> <INDENT> patterns = [ global_regular(), pattern, ] <NEW_LINE> fields = [field] <NEW_LINE> return self.parse_html(html, fields, patterns)
提取字段方法
625941f4283ffb24f3c55f0e
def read_usa_graph(): <NEW_LINE> <INDENT> graph = Graph() <NEW_LINE> file = open('contiguous-usa.dat', 'r') <NEW_LINE> count = 0 <NEW_LINE> for line in file: <NEW_LINE> <INDENT> pair = line.split() <NEW_LINE> state1 = pair[0] <NEW_LINE> state2 = pair[1] <NEW_LINE> v1 = graph.add_vertex_if_new(state1) <NEW_LINE> v2 = gr...
Read and return the graph of contiguous USA states.
625941f4a17c0f6771cbe662
def test_pkBaer(self): <NEW_LINE> <INDENT> file = os.path.join(self.path, 'manz_waldk.a01.gz') <NEW_LINE> data = np.loadtxt(gzip.open(file), dtype=np.float32) <NEW_LINE> df, ntdownmax, ntupevent, thr1, thr2, npreset_len, np_dur = (200.0, 20, 60, 7.0, 12.0, 100, 100) <NEW_LINE> nptime, pfm = pkBaer(data, df, ...
Test pkBaer against implementation for UNESCO short course
625941f494891a1f4081c0c0
def print_file(file_name, asgt_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cmd = r'lpr %s -T %s -P %s -o cpi=14 -o lpi=8 -o sides=two-sided-long-edge -o page-left=72 -o page-right=72 -o prettyprint' %(file_name, asgt_name, PRINTER_NAME) <NEW_LINE> proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)...
Prints a file file_name: name of file to print asgt_name: Title of file Return Value: none
625941f47d847024c06be8d5
def _launch_legacy(self, image, env_override, volumes): <NEW_LINE> <INDENT> raw_cmd = self.docker_cmd(image, env_override=env_override, volumes=volumes) <NEW_LINE> log.info("Starting docker container for IE {0} with command [{1}]".format( self.attr.viz_id, raw_cmd )) <NEW_LINE> p = Popen( raw_cmd, stdout=PIPE, stderr=P...
Legacy launch method for use when the container interface is not enabled
625941f485dfad0860c3b471
def write_freq(self, freq): <NEW_LINE> <INDENT> self.freq = freq <NEW_LINE> return_value = self.gpg.set_grove_pwm_frequency( self.get_port_ID(), self.freq) <NEW_LINE> debug ("Analog Write on {} at {}".format(self.get_port_ID(), self.freq)) <NEW_LINE> return return_value
Sets the frequency of the PWM signal. The frequency range goes from 3Hz up to 48000Hz. Default value is set to 24000Hz (24kHz). :param int freq: Frequency of the PWM signal. .. seealso:: Read more about this in :py:meth:`gopigo3.GoPiGo3.set_grove_pwm_frequency`'s description.
625941f46aa9bd52df0373bc
def test_write_int(self): <NEW_LINE> <INDENT> tests = [ (-1, b'\xFF\xFF'), (-128, b'\x80\xFF'), (128, b'\x80\x00'), (255, b'\xFF\x00'), (256, b'\x00\x01'), (-32768, b'\x00\x80'), (-32769, b'\x00\x80'), (32767, b'\xFF\x7F'), (32768, b'\xFF\x7F'), ] <NEW_LINE> p = pexpect.spawn(daxc_path) <NEW_LINE> p.expect('dax>') <NEW...
check the corner cases for writing to an INT
625941f4cb5e8a47e48b80b3
def update(self, tableName, setDict, whereDict): <NEW_LINE> <INDENT> logging.info("Generating UPDATE query(%s) ..." % (tableName)) <NEW_LINE> finalQuery = ("UPDATE `%s` SET " % (tableName)) <NEW_LINE> key = list(setDict.keys()) <NEW_LINE> value = list(setDict.values()) <NEW_LINE> length = len(key) <NEW_LINE> try: <NEW_...
Generates a DELETE query. `setDict` is a dict datatype with key as column name and value as the new value to be set as. `whereDict` is a dict datatype with key as column name and value as the value of the rows to update.
625941f463d6d428bbe44b05
def test_txn_get_bad_request(self): <NEW_LINE> <INDENT> response = self.make_bad_request(transaction_id='t-1') <NEW_LINE> self.assertEqual(self.status.INTERNAL_ERROR, response.status) <NEW_LINE> self.assertFalse(response.transaction.SerializeToString())
Verifies requests for a specific txn break with a bad protobuf. Expects to find: - a status of INTERNAL_ERROR - that the Transaction returned, when serialized, is actually empty
625941f4ad47b63b2c50a594
def run_migrations_offline(): <NEW_LINE> <INDENT> url = config.get_main_option("sqlalchemy.url") <NEW_LINE> context.configure( url=url, target_metadata=target_metadata, literal_binds=True, version_table=version_table) <NEW_LINE> with context.begin_transaction(): <NEW_LINE> <INDENT> context.run_migrations()
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
625941f430dc7b7665901f73
def calc_jacobian(self, field, epsdiff=1.0e-6): <NEW_LINE> <INDENT> if (field.model.islinear == 1) and (hasattr(self, "jacobian_use")): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.neq = field.neq <NEW_LINE> self.dim = self.neq * field.nelem <NEW_LINE> self.jacobian = np.zeros([self.dim, self.dim]) <NEW_LINE> ep...
jacobian matrix dR/dQ of dQ/dt=R(Q) is computed as successive columns by finite difference of R(Q+dQ) ordering is ncell x neq (neq is the fast index) Args: field: epsdiff: (Default value = 1.e-6) Returns:
625941f49b70327d1c4e13ec
def handlemessage(self, msg: Any) -> Any: <NEW_LINE> <INDENT> if isinstance(msg, ChangeMessage): <NEW_LINE> <INDENT> self._handle_repeat_message_attack() <NEW_LINE> if self._dead: <NEW_LINE> <INDENT> print_error('chooser got ChangeMessage after dying') <NEW_LINE> return <NEW_LINE> <DEDENT> if not self._text_node: <NEW_...
Standard generic message handler.
625941f429b78933be1e5cb8
def update_storage(kwargs=None, conn=None, call=None): <NEW_LINE> <INDENT> if call != 'function': <NEW_LINE> <INDENT> raise SaltCloudSystemExit( 'The show_storage function must be called with -f or --function.' ) <NEW_LINE> <DEDENT> if not conn: <NEW_LINE> <INDENT> conn = get_conn() <NEW_LINE> <DEDENT> if kwargs is Non...
.. versionadded:: 2015.8.0 Update a storage account's properties CLI Example: .. code-block:: bash salt-cloud -f update_storage my-azure name=my_storage label=my_storage
625941f48e05c05ec3eea98e
def parse(file): <NEW_LINE> <INDENT> conf = _parse(file) <NEW_LINE> conf_dir_path = os.path.join(os.path.dirname(file), CONFIG_DIR) <NEW_LINE> if os.path.exists(conf_dir_path): <NEW_LINE> <INDENT> files = sorted(os.listdir(conf_dir_path)) <NEW_LINE> for f in files: <NEW_LINE> <INDENT> if f.endswith('.xml'): <NEW_LINE> ...
parse a config file The root element (glidein) is registered as type Config :param file: file path :return: the document root :rtype: Config
625941f4046cf37aa974d355
def test_for_return_type(self): <NEW_LINE> <INDENT> return self.assertEqual(type(self.weather.getMinTemp('Nakuru')),type(10.0),msg='Invalid return type')
Tests for correct return type
625941f40fa83653e46575cb
def test_unique_pairs(models, add_hlom, add_doc): <NEW_LINE> <INDENT> d = add_doc() <NEW_LINE> r = add_hlom() <NEW_LINE> HLOM_Citation.create(document=d, record=r) <NEW_LINE> with pytest.raises(IntegrityError): <NEW_LINE> <INDENT> HLOM_Citation.create(document=d, record=r)
Don't allow duplicate links between the same text -> syllabus pair.
625941f45fc7496912cc3f91
def t_test(col, a, b, alpha): <NEW_LINE> <INDENT> stat, p = ttest_ind(a[col].dropna(), b[col].dropna()) <NEW_LINE> if p < alpha: <NEW_LINE> <INDENT> return 'H0 rejected' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'X'
Calculates the T-test for the means of two independent samples of scores This is a two-sided test for the null hypothesis that 2 independent samples have identical average (expected) values This test assumes that the populations have identical variances by default :param col: Column concerned :param alpha: Statistic...
625941f43c8af77a43ae3dbc
def __init__(self, embedding_size, vocab_size, num_actions): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.num_actions = num_actions <NEW_LINE> self.embedding_size = embedding_size <NEW_LINE> self.d2e = nn.Embedding(vocab_size, embedding_size) <NEW_LINE> self.rnn = nn.GRUCell(embedding_size, embedding_size) <N...
- input: utterance - output: action
625941f4566aa707497f4b74
def rc_dir(): <NEW_LINE> <INDENT> return os.path.join(QDir.home().absolutePath(), ".biblereader")
Return the directory that contains the rc files
625941f44527f215b584ca65
def notify(self, n=1): <NEW_LINE> <INDENT> if not is_locked(self._lock): <NEW_LINE> <INDENT> raise RuntimeError('lock is not locked') <NEW_LINE> <DEDENT> notified = [0] <NEW_LINE> def walker(switcher, predicate): <NEW_LINE> <INDENT> if not switcher.active: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if predica...
Raise the condition and wake up fibers waiting on it. The optional *n* parameter specifies how many fibers will be notified. By default, one fiber is notified.
625941f471ff763f4b549cab
def get_auth_registration_requests_image(self): <NEW_LINE> <INDENT> return self.auth.get("registration_requests_image", False)
Have the registration form request an Image
625941f44f6381625f11504f
def default_output_fn(prediction, accept): <NEW_LINE> <INDENT> return _worker.Response(response=_encoders.encode(prediction, accept), mimetype=accept)
Function responsible to serialize the prediction for the response. Args: prediction (obj): prediction returned by predict_fn . accept (str): accept content-type expected by the client. Returns: (worker.Response): a Flask response object with the following args: * Args: response: the s...
625941f463b5f9789fde76fa
def flush(self): <NEW_LINE> <INDENT> self._requested_voltage = self.encoder.getVoltage() <NEW_LINE> self._requested_speed = 0
Flushes the modules requested speed and voltage
625941f4be8e80087fb2124b
def _load_new_instance(self, obj_data): <NEW_LINE> <INDENT> raise NotImplementedError
Deserialize the provided data into a new instance. :param obj_data: Likely a dict, but could be any user provided data. :return: Any errors that came up, and the instance.
625941f4f9cc0f698b140c0a
def keyPressEvent(self, evt): <NEW_LINE> <INDENT> if evt.key() == Qt.Key_C and evt.modifiers() & Qt.ControlModifier: <NEW_LINE> <INDENT> self.__copyFilter() <NEW_LINE> <DEDENT> elif evt.key() == Qt.Key_Delete: <NEW_LINE> <INDENT> self.removeRule() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(AdBlockTre...
Protected method handling key presses. @param evt key press event (QKeyEvent)
625941f476e4537e8c351c8c
def entity_children2(entity): <NEW_LINE> <INDENT> return [(e.slug, e) for e in entity.get_natural_children( skip_slugs=['health_area', 'vfq'])]
(entity.slug, entity) of all children of an entity
625941f4ab23a570cc25079c
def __init__(self, **kwargs): <NEW_LINE> <INDENT> base.Solver.__init__(self, **kwargs) <NEW_LINE> self._lbfgs_args = self.spec.get('lbfgs_args', {}) <NEW_LINE> self._param = None <NEW_LINE> self._sparse_net = None <NEW_LINE> self._previous_net = None
The LBFGS solver. Necessary args is: lbfgs_args: a dictionary containg the parameters to be passed to lbfgs.
625941f4baa26c4b54cb172d
def _get_vis_data(self): <NEW_LINE> <INDENT> bool_error_getting_data = False <NEW_LINE> try: <NEW_LINE> <INDENT> self.df_vis_data = pandas.read_sql(self.string_sql_query, self.sql_conn._list_conn[1]) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> string_e_args = str(e.args) <NEW_LINE> bool_error_getting...
this method queries the data from the database Requirements: package pandas package SqlMethods Inputs: None Type: n/a Desc: n/a Important Info: None Return: object Type: pandas.DataFrame Desc: data from the sql database which holds the transaction data columns -> ** see base class documentation
625941f48c3a8732951589d7
def GetOutput(self, grd, env_lang, env_defs, out_type, out_lang): <NEW_LINE> <INDENT> grd.SetOutputLanguage(env_lang) <NEW_LINE> grd.SetDefines(env_defs) <NEW_LINE> buf = StringIO.StringIO() <NEW_LINE> build.RcBuilder.ProcessNode(grd, DummyOutput(out_type, out_lang), buf) <NEW_LINE> return buf.getvalue()
Generates an output of a writer. Args: grd: The root of the grit tree. env_lang: The environment language. env_defs: Environment definitions. out_type: Type of the output node for which output will be generated. This selects the writer. out_lang: Language of the output node for which output will be gener...
625941f4bd1bec0571d90c43
def test_encryption_alt_encoding(self): <NEW_LINE> <INDENT> key = self.generate_key("Craig Gentry", "xorr.ox", passphrase="craiggentry") <NEW_LINE> gentry = str(key.fingerprint) <NEW_LINE> key = self.generate_key("Marten van Dijk", "xorr.ox") <NEW_LINE> dijk = str(key.fingerprint) <NEW_LINE> self.gpg._encoding = 'latin...
Test encryption with latin-1 encoding
625941f48e7ae83300e4b5e3
def fired(self): <NEW_LINE> <INDENT> return self._fired
The number of times this event has fired
625941f4fff4ab517eb2fa55
def get_parent_img(testcasepath, dir, get, isparent=False, verbose=True): <NEW_LINE> <INDENT> if verbose: <NEW_LINE> <INDENT> printv(f'testcasepath: {testcasepath}') <NEW_LINE> printv(f'dir: {dir}') <NEW_LINE> printv(f'get: {get}') <NEW_LINE> printv(f'isparent: {isparent}') <NEW_LINE> printv(f'verbose: {verbose}') <NEW...
Returns the name of the testcase parent image, CS or complete present in a directory. Helpful for finding the parent of the image, without checking every time if it would be a CS or a complete image. @param testcasepath Full path or name of the testcase @param dir Path to the directory to check for the image in @para...
625941f4cc40096d61595f62
def task_coverage(): <NEW_LINE> <INDENT> cov = Coverage([PythonPackage('pyreg', 'tests')]) <NEW_LINE> yield cov.all() <NEW_LINE> yield cov.src() <NEW_LINE> yield cov.by_module()
show coverage for all modules including tests
625941f421bff66bcd684f61
def defaults(self, **kwargs): <NEW_LINE> <INDENT> return self._parser.set_defaults(**kwargs)
Set global defaults. All arguments are passed on to :py:meth:`ArgumentParser.set_defaults`.
625941f450812a4eaa59c92f
def bound(self): <NEW_LINE> <INDENT> return _newE(self.__data.bound())
回転結果を維持しつつ、各軸の角度を±πの範囲におさめた値を得る。 :rtype: `EulerRotation`
625941f476d4e153a657f147
@app.template_filter('markup_summary') <NEW_LINE> def filter_markup_summary(text, default_summary = "(no summary text)"): <NEW_LINE> <INDENT> return (Markup('<p>') + (text or default_summary) + Markup('</p>')).replace("\n", Markup("<br>"))
概要テキストを HTML 化するフィルター :param str text: テキスト :return: 全文を含む HTML テキスト ``<p>`` タグに包んだ HTML テキストを返す。 ``text`` 中の改行は ``<br>`` タグに変換される。
625941f4851cf427c661ab1d
def position(self, maxage: Optional[float] = None) -> Optional[pynmea2.GGA]: <NEW_LINE> <INDENT> if maxage: <NEW_LINE> <INDENT> if time.time() - self.lastpostime > maxage: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> return self.lastpos
Get the current position. Returns None if we don't have a valid position, or position is older than maxage :return:
625941f4fb3f5b602dac3caf
def __init__(self, email, name=None, login=None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise utils.ReportError( "Email required for user initialization.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parts = utils.EMAIL_REGEXP.search(email) <NEW_LINE> self.email = parts.groups()[1] <NEW_LINE> self.log...
Set user email, name and login values.
625941f4004d5f362079a943
def test_class_created(): <NEW_LINE> <INDENT> check_class_exists(task_22_2b, "CiscoTelnet")
Проверка, что класс создан
625941f4e8904600ed9f254c
def memoize(f): <NEW_LINE> <INDENT> class memodict(dict): <NEW_LINE> <INDENT> def __getitem__(self, *key): <NEW_LINE> <INDENT> return dict.__getitem__(self, key) <NEW_LINE> <DEDENT> def __missing__(self, key): <NEW_LINE> <INDENT> ret = self[key] = f(*key) <NEW_LINE> return ret <NEW_LINE> <DEDENT> <DEDENT> return memodi...
Memoization decorator for a function taking one or more arguments.
625941f4b57a9660fec33ea1
def __call__(self, output): <NEW_LINE> <INDENT> p_pos = self._compute_probability(self.positive, output) <NEW_LINE> if self.negative: <NEW_LINE> <INDENT> p_neg = self._compute_probability(self.negative, output) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p_neg = 1 - p_pos <NEW_LINE> <DEDENT> x = 1 / (1 + (p_neg/p_pos...
Parameters ---------- output : np.array Model output, usually (# observations,) or (# obervations, # classes) array for regression or classification problems, respectively. Returns ------- probability : float Probability that every predicted target value was generated by a positive density or di...
625941f4c432627299f0525f
def runAllTests(self): <NEW_LINE> <INDENT> for program in self.programNames: <NEW_LINE> <INDENT> self.testProgram(program)
Function that automatically runs all the programs in the file
625941f4d53ae8145f87a877
def setMaxHorizPixels(self, hpx): <NEW_LINE> <INDENT> self.hpx = hpx
Sets the maximum horizontal pixels.
625941f4460517430c394788
def visualize_days(parsed_data): <NEW_LINE> <INDENT> counter = Counter(item["DayOfWeek"] for item in parsed_data) <NEW_LINE> data_list = [ counter["Monday"], counter["Tuesday"], counter["Wednesday"], counter["Thursday"], counter["Friday"], counter["Saturday"], counter["Sunday"] ] <NEW_LINE> day_tuple = tuple(["Mon", "T...
Visualize data by day of week
625941f46fece00bbac2dd5b
def test_update_saved_app_map_search(self): <NEW_LINE> <INDENT> pass
Test case for update_saved_app_map_search Update a search # noqa: E501
625941f41f037a2d8b946810
@sensitive_variables('body', 'quote') <NEW_LINE> def format_body(sender, body, indent=_("> "), width=WRAP_WIDTH): <NEW_LINE> <INDENT> indent = force_text(indent) <NEW_LINE> wrapper = TextWrapper(width=width, initial_indent=indent, subsequent_indent=indent) <NEW_LINE> quote = '\n'.join([line.startswith(indent) and inden...
Wrap the text and prepend lines with a prefix. The aim is to get lines with at most `width` chars. But does not wrap if the line is already prefixed. Prepends each line with a localized prefix, even empty lines. Existing line breaks are preserved. Used for quoting messages in replies.
625941f4442bda511e8bea23
def __init__(self, out_channels, kernel_size): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.conv1d = nn.Conv1d( 1, out_channels, kernel_size, padding=int((kernel_size - 1) / 2), padding_mode="reflect", )
out_channels: Number of channels produced by the convolution kernel_size: size of the convolving kernel
625941f4cad5886f8bd275ec
def pretty_speed(speed): <NEW_LINE> <INDENT> unit = 'bps' <NEW_LINE> kmg = ['', 'K', 'M', 'G'] <NEW_LINE> i = 0 <NEW_LINE> while speed >= 1000: <NEW_LINE> <INDENT> speed /= 1000 <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> return "{:.2f}".format(speed) + ' ' + kmg[i] + unit
return speed value prettily accordingly in either bps, Kbps, Mbps, Gbps
625941f415baa723493c458f
def _get_new_tag(self, new_version): <NEW_LINE> <INDENT> suffix = "" <NEW_LINE> if self.config.has_option("globalconfig", "tag_suffix"): <NEW_LINE> <INDENT> suffix = self.config.get("globalconfig", "tag_suffix") <NEW_LINE> <DEDENT> return "%s-%s%s" % (self.project_name, new_version, suffix)
Returns the actual tag we'll be creating.
625941f47cff6e4e81117f9a
def read_dist_wordvec(D_embedding_fname, fname_wordlist): <NEW_LINE> <INDENT> wordlist = set() <NEW_LINE> with open(fname_wordlist) as f_wordlist: <NEW_LINE> <INDENT> for line in f_wordlist: <NEW_LINE> <INDENT> wordlist.add(line.strip().split(" ")[0]) <NEW_LINE> <DEDENT> <DEDENT> D_embedding_vec = dict() <NEW_LINE> for...
To read embedding vectors and only keep those in wordlist. :param D_embedding_fname: {"embedding_name": "filepath/filename"}, where the value is the absolute filename of the pretrained embedding. Currently only support those could be passed to gensim.models.keyedvect...
625941f4d8ef3951e3243b52
def typecheck_first_pass(self, typeManager, env): <NEW_LINE> <INDENT> self.return_type = typeManager.new_type() <NEW_LINE> full_type = self.return_type <NEW_LINE> for param in self.params: <NEW_LINE> <INDENT> new_type = typeManager.new_type() <NEW_LINE> self.param_types.append(new_type) <NEW_LINE> <DEDENT> length = len...
First typechecking pass. Binds a generic function type of the form a1->a2->a3->return_type, where a1,a2,..,an are a new type for each variable and 'return_type' a new type for the return type of the function.
625941f466673b3332b926a6
def to_dict(self): <NEW_LINE> <INDENT> data = {"field": self._uid, "datatype": self._datatype.value, "cardinality": self._cardinality.value} <NEW_LINE> if self._description: <NEW_LINE> <INDENT> data["text"] = self._description <NEW_LINE> <DEDENT> return data
The attribute dictionary representation.
625941f43346ee7daa2b3386
def nycRestaurantGradesSum(self,): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> total = 0 <NEW_LINE> for restaurantID in self.data['CAMIS'].unique(): <NEW_LINE> <INDENT> total += self.testRestaurantGrades(restaurantID) <NEW_LINE> <DEDENT> return total <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise...
Sums testRestaurantGrades() values across all restaurants in NYC. Throws loadedDataException() if loadRestaurantData() was not used before.
625941f430c21e258bdfaab9
def repository_relative_uris(self, plural_record_type: str, repository_uris: list = None, endpoint_extension: str = None,): <NEW_LINE> <INDENT> plural_record_type = plural_record_type.strip('/') <NEW_LINE> return ( '%s/%s/%d%s' % ( repo_uri, plural_record_type, rec_id, '' if endpoint_extension is None else '/%s' % endp...
Streams all URIs of a specific type from the ArchivesSpace instance, assuming that a `/repositories/:repo_id/:plural_record_type` endpoint exists, and supports the `all_ids=true` parameter. :plural_record_type: The desired record type, formatted as it appears in the documentation for the related API endpoint. :reposi...
625941f4d6c5a10208144664
def _analyse_sentence(self, sentence): <NEW_LINE> <INDENT> n_char = len(sentence) + 0.0 <NEW_LINE> n_words = len(sentence.split()) + 0.0 <NEW_LINE> n_punct = sum([sentence.count(s) for s in ",.:;-"]) + 0.0 <NEW_LINE> return [n_char, n_words, n_punct, n_char/n_words, n_punct/n_words]
Extract features for a single source sentence. Args: sentence (string): Source sentence string Returns: 5-tuple of features as described in the class docstring
625941f4a8370b7717052eb2
def test_AddPoints(): <NEW_LINE> <INDENT> if src.AddPoints((3, 4)): <NEW_LINE> <INDENT> assert len(src.points) != 0 <NEW_LINE> <DEDENT> if src.AddPoints((-4, 7)): <NEW_LINE> <INDENT> assert len(src.points) == 0
this is the general method, a convention of pytest since we are not using oop, we are using pytest here to see whether all of my functions return the expected results
625941f4293b9510aa2c38a4
def test_login_unregistered(self): <NEW_LINE> <INDENT> with self.client: <NEW_LINE> <INDENT> response = self.client.post( '/v1/auth/login', data=json.dumps(dict( username='unknown', password='unknown' )), content_type='application/json' ) <NEW_LINE> data = json.loads(response.data.decode()) <NEW_LINE> self.assertEqual(...
Tests an unregistered user cannot login
625941f4d4950a0f3b08c95b
def _train_single_epoch(self, batchgen: MultiThreadedAugmenter, epoch, verbose=False): <NEW_LINE> <INDENT> chainer.global_config.train = True <NEW_LINE> return super()._train_single_epoch(batchgen, epoch, verbose=verbose)
Trains the network a single epoch Parameters ---------- batchgen : MultiThreadedAugmenter Generator yielding the training batches epoch : int current epoch
625941f421a7993f00bc8311
def turn_opposite(self, bias=None): <NEW_LINE> <INDENT> self.current_loop = self.get_opposite_loop(self.current_loop)
Turn the turtle around, to look at the opposite edge: +----+ +----+ | @> | --> | <@ | +----+ +----+ If the current face has odd count of edges, then the term "around" is ambigous: +----+ | > | @ * | / > +----+ / +...
625941f42c8b7c6e89b35dd0
def next_line(self, n=None): <NEW_LINE> <INDENT> if self.__position__ == len(self.string): <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> result = self.next_match(cre_line, n=n) <NEW_LINE> if self.__position__ < len(self.string): <NEW_LINE> <INDENT> self.__position__ += 1 <NEW_LINE> <DEDENT> return result
Reads lines from string. Args: n (array, int, str, re.RegexObject): specifies either the shape of the numpy array returned or the regular expression to stop matching before; Returns: If `n` is specified returns a numpy array of the given shape filled with lines from the string. Otherwise r...
625941f4b830903b967e9f19
def read_data(filename = 'alkuarvot.txt'): <NEW_LINE> <INDENT> infile=open(filename,'r') <NEW_LINE> mylambda = float(infile.readline().strip().split()[0]) <NEW_LINE> n_iter = int(float(infile.readline().strip().split()[0])) <NEW_LINE> tol = float(infile.readline().strip().split()[0]) <NEW_LINE> temperature = float(infi...
Yritetään lukea alkuarvot filestä alkuarvot.txt. Luetaan laskentaparametreja ja gridin tietoja. muutetaan siten että x->y ja y->x eli input tiedossa y tulee ensin koska se on matriisin 1. dimensio gridin koon määrittelyssä ja ytimien paikkojen määrittelyssä
625941f456b00c62f0f14c72
def generate_moves(self, board: DominosaBoard) -> typing.Iterator[MoveDescription]: <NEW_LINE> <INDENT> for rule in (generator(board) for generator in self.move_generators): <NEW_LINE> <INDENT> has_yielded = False <NEW_LINE> for move, state in rule: <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print() <NEW_LI...
Generate all moves from the board's current state. :param Board board: the current state
625941f4009cb60464c639c1
def add_to_flow_edge_capacity(self, node1, node2, cpcty): <NEW_LINE> <INDENT> if self.has_edge(node1, node2): <NEW_LINE> <INDENT> self[node1][node2]['capacity'] += cpcty <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.add_edge(node1, node2, capacity=cpcty, flow=0) <NEW_LINE> self.add_edge(node2, node1, capacity=0, f...
Increases the capacity of the edge between node1 and node2 Parameter ---------- node1 : the source node node2 : the dest node cpcty : the amount by which the capacity needs to be increased Example --------- >>> import MarkovModel as mm >>> g = mm.DirectedGraph() >>> g.add_nodes_from(['a','b']) >>> g.add_all_flow_edge...
625941f41f037a2d8b946811
def add_byte_array_field(self, field_name: str) -> "ClassDefinitionBuilder": <NEW_LINE> <INDENT> self._add_field_by_type(field_name, FieldType.BYTE_ARRAY, self.version) <NEW_LINE> return self
Adds the field with the byte array type to the class definition. Args: field_name (str): Name of the field to add. Returns: ClassDefinitionBuilder: Itself for chaining. Raises: HazelcastSerializationError: If this method is called after :func:`build` or a field with the same name is alrea...
625941f40c0af96317bb87fc
def __num_lines(self, test): <NEW_LINE> <INDENT> for i, l in enumerate(test.split('\n')): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return i + 1
Count the number of lines in a string.
625941f47d847024c06be8d6
def download_jobs_status(logger, jobs_collection, remote_jobs_collection): <NEW_LINE> <INDENT> logger.info("Beginning Jobs status download") <NEW_LINE> jobs_results = remote_jobs_collection.find({}, {"_id": 0}) <NEW_LINE> for result in jobs_results: <NEW_LINE> <INDENT> jobs_collection.replace_one( {"job_name": result["...
Download the latest whois information.
625941f4e1aae11d1e74a2d2
@patch('stream_alert_cli.version.LOGGER_CLI') <NEW_LINE> def test_version_helper_error(mock_logging): <NEW_LINE> <INDENT> package = AthenaPackage( version='1.0', config=basic_streamalert_config() ) <NEW_LINE> publish = LambdaVersion( config=basic_streamalert_config(), clustered_deploy=False, package=package ) <NEW_LINE...
CLI - Publish Helper Raises Error
625941f43539df3088e2e960
def __init__(self): <NEW_LINE> <INDENT> self.db = IncidentModel()
initiliase the redflag class
625941f426238365f5f0f48b
def deploy(self): <NEW_LINE> <INDENT> if rb_is_win(): <NEW_LINE> <INDENT> rb_deploy_lib(rb_install_get_lib_file("libvorbis_static.lib")) <NEW_LINE> rb_deploy_headers(dir = rb_install_get_include_dir() +"vorbis", subdir = "vorbis") <NEW_LINE> <DEDENT> elif rb_is_mac(): <NEW_LINE> <INDENT> rb_deploy_lib(rb_install_get_li...
if rb_is_msvc(): sd = "VS2010" if rb_is_vs2010() else "VS2012" dd = rb_get_download_dir(self) +"win32/" +sd +"/Win32/" +rb_msvc_get_build_type_string() +"/" rb_deploy_dll(dd +"libvorbis.dll") rb_deploy_lib(dd +"libvorbis.lib") rb_deploy_headers(dir = rb_get_download_dir(self) +"/include/vorbis", sub...
625941f4be7bc26dc91cdc09
def test_incompatible_fetch_archive_and_no_archive(self): <NEW_LINE> <INDENT> args = ['--fetch-archive', '--no-archive'] <NEW_LINE> parser = BackendCommandArgumentParser(MockedBackendCommand.BACKEND, archive=True) <NEW_LINE> with self.assertRaises(AttributeError): <NEW_LINE> <INDENT> _ = parser.parse(*args)
Test if fetch-archive and no-archive arguments are incompatible
625941f4eab8aa0e5d26e16f
def get(self, request, collection, experiment): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> collection_obj = Collection.objects.get(name=collection) <NEW_LINE> experiment_obj = Experiment.objects.get(name=experiment, collection=collection_obj) <NEW_LINE> if experiment_obj is None: <NEW_LINE> <INDENT> return BossResour...
GET requests for a single instance of a experiment Args: request: DRF Request object collection: Collection name specifying the collection you want experiment: Experiment name specifying the experiment instance Returns : Experiment
625941f401c39578d7e75450
@query_blueprint.route('/classmates') <NEW_LINE> def get_classmates(): <NEW_LINE> <INDENT> from flask import request, render_template, session, redirect, url_for <NEW_LINE> from everyclass.server.tools import get_time_chinese, get_day_chinese <NEW_LINE> from everyclass.server.db.dao import get_students_in_class <NEW_LI...
同学名单查询视图函数
625941f44e4d5625662d49e4
def get_XS(self,name,rx_type): <NEW_LINE> <INDENT> ind = self.get_ind(name,'N_name') <NEW_LINE> return getattr(self,rx_type+'_XS')[ind]
Get cross sections (stored in barns)
625941f4dc8b845886cb5b4c
def setUp(self): <NEW_LINE> <INDENT> self.client = app.test_client() <NEW_LINE> app.config['TESTING'] = True <NEW_LINE> app.config['SECRET KEY'] = 'key' <NEW_LINE> with self.client as c: <NEW_LINE> <INDENT> with c.session_transaction() as sess: <NEW_LINE> <INDENT> sess['RSVP'] = 1 <NEW_LINE> <DEDENT> <DEDENT> connect_t...
Stuff to do before every test.
625941f4aad79263cf39105f
def generate_map(timeout=10): <NEW_LINE> <INDENT> r = requests.get(CLDR_WINZONE_URL, timeout=timeout) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> raise ValueError('Unexpected response: %s' % r) <NEW_LINE> <DEDENT> tz_map = {} <NEW_LINE> for e in to_xml(r.content).find('windowsZones').find('mapTimezones').fi...
Helper method to update the map if the CLDR database is updated
625941f4796e427e537b0be0
def stats(self): <NEW_LINE> <INDENT> print(self.name) <NEW_LINE> for hero in self.heroes: <NEW_LINE> <INDENT> print("{} had a kill/death ratio of {}/{}".format(hero.name, hero.kills, hero.deaths))
This method should print the ratio of kills/deaths for each member of the team to the screen. This data must be output to the terminal.
625941f463b5f9789fde76fb
def read_board(board_file): <NEW_LINE> <INDENT> wordrows = read_words(board_file) <NEW_LINE> sublist_containing_letters = [] <NEW_LINE> final_board = [] <NEW_LINE> for i in wordrows: <NEW_LINE> <INDENT> for j in i: <NEW_LINE> <INDENT> sublist_containing_letters.append(j) <NEW_LINE> <DEDENT> <DEDENT> return sublist_cont...
(file open for reading) -> list of list of str Return a board read from open file board_file. The board file will contain one row of the board per line. Newlines are not included in the board.
625941f40a366e3fb873ee35
def testTypicalUseCase1(self): <NEW_LINE> <INDENT> self.mgr.do_updates() <NEW_LINE> self.assertTrue(self.mgr.malware.version > 0, "Malware list did not update version") <NEW_LINE> self.assertTrue(self.mgr.phishing.version > 0, "Phishing list did not update version") <NEW_LINE> self.assertTrue(len(self.mgr) > 0, "Update...
A more thorough test corresponding to a typical use of the blacklist manager
625941f4009cb60464c639c2
def getDevice(self, deviceName): <NEW_LINE> <INDENT> return self.getHardwareObject(deviceName)
Return a Device given its name (see getHardwareObject())
625941f4f7d966606f6aa621
def avg_bio_f1_score(y_true, y_pred): <NEW_LINE> <INDENT> from seqlearn.evaluation import bio_f_score <NEW_LINE> return sum(map(bio_f_score, y_true, y_pred)) / len(y_true)
Macro-averaged F1 score of lists of BIO-encoded sequences ``y_true`` and ``y_pred``. A named entity in a sequence from ``y_pred`` is considered correct only if it is an exact match of the corresponding entity in the ``y_true``. It requires https://github.com/larsmans/seqlearn to work.
625941f4167d2b6e312191a9