code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def mashi_distance_by_scipy(x, y): <NEW_LINE> <INDENT> X = np.vstack([x, y]) <NEW_LINE> XT = X.T <NEW_LINE> d2 = pdist(XT, 'mahalanobis') <NEW_LINE> print("d2: ", d2)
采用scipy实现
625941de30c21e258bdfa7eb
def import_to_ak(self, csv_file): <NEW_LINE> <INDENT> url = self.settings.AK_API_BASE_URL + 'upload/' <NEW_LINE> result = requests.post(url, files={'upload': StringIO(csv_file.getvalue())}, data={'page': self.settings.AK_IMPORT_PAGE, 'autocreate_user_fields': 0}, auth=(self.settings.AK_USER, self.settings.AK_PASSWORD)...
Import given CSV file into ActionKit
625941dedc8b845886cb5882
def get_mb_id(self, tags, name): <NEW_LINE> <INDENT> if tags is None or not name: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> (exists, mbid) = tags.get_string_index("musicbrainz-" + name, 0) <NEW_LINE> return mbid or ""
Get MusicBrainz ID @param tags as Gst.TagList @param name as str @return str
625941de5166f23b2e1a54a5
def apply_shift(self, shift): <NEW_LINE> <INDENT> dict = Message.build_shift_dict(self,shift) <NEW_LINE> keys = dict.keys() <NEW_LINE> encripted_message = '' <NEW_LINE> for index in range(len(self.message_text)): <NEW_LINE> <INDENT> if self.message_text[index] in keys: <NEW_LINE> <INDENT> encripted_message += dict[self...
Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (stri...
625941ded58c6744b4257faa
def test_ticket47871_init(topology_m1c1): <NEW_LINE> <INDENT> topology_m1c1.ms["master1"].plugins.enable(name=PLUGIN_RETRO_CHANGELOG) <NEW_LINE> mod = [(ldap.MOD_REPLACE, 'nsslapd-changelogmaxage', "10s"), (ldap.MOD_REPLACE, 'nsslapd-changelog-trim-interval', "5s")] <NEW_LINE> topology_m1c1.ms["master1"].modify_s("cn=%...
Initialize the test environment
625941de4428ac0f6e5bab40
def start(self, args=None): <NEW_LINE> <INDENT> self.loop.run_until_complete( self.events.dispatch(str(PreceptEvent.BEFORE_CLI_START)) ) <NEW_LINE> try: <NEW_LINE> <INDENT> self.loop.run_until_complete(self.cli.run(args=args)) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> self.loop.run_until_complet...
Start the application loop. :return:
625941de32920d7e50b2851f
def get_config_item(item): <NEW_LINE> <INDENT> if os.path.isfile(CONFIG_FILE): <NEW_LINE> <INDENT> tmp_json = json.load(open(CONFIG_FILE)) <NEW_LINE> return tmp_json[item] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Configuration : unable to open or read file '{0}')".format(CONFIG_FILE)) <NEW_LINE> <...
Generic function
625941de55399d3f05588a01
def precess_img(img): <NEW_LINE> <INDENT> test_img = img.resize((HEIGHT, WIDHT)) <NEW_LINE> test_img_array = np.array(test_img) <NEW_LINE> test_img_array = test_img_array / 255 <NEW_LINE> test_img_array = test_img_array.reshape(-1, HEIGHT, WIDHT, 3) <NEW_LINE> return test_img_array
对图像进行预处理,使其满足输入数据的要求 1, 改变大小,2. 数据归一化 3. 改变shape :param img: 要预处理的图像 :return: 返回预处理后的数组
625941de66673b3332b923dd
def spectral_norm(input_): <NEW_LINE> <INDENT> if len(input_.shape) < 2: <NEW_LINE> <INDENT> raise ValueError("Spectral norm can only be applied to multi-dimensional tensors") <NEW_LINE> <DEDENT> w = tf.reshape(input_, [-1, input_.get_shape().as_list()[-1]]) <NEW_LINE> u_var = tf.get_variable( input_.name.replace(":", ...
Performs Spectral Normalization on a weight tensor.
625941de8e7ae83300e4b319
def validTree_uf(n, edges): <NEW_LINE> <INDENT> if len(edges) != n - 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> parent = list(range(n)) <NEW_LINE> rank = [1] * n <NEW_LINE> def find(x): <NEW_LINE> <INDENT> if x != parent[x]: <NEW_LINE> <INDENT> parent[x] = find(parent[x]) <NEW_LINE> <DEDENT> return parent[...
Union find / Disjoint set Time: O(v) Space: O(v)
625941de167d2b6e31218ee1
def sendConnections(self): <NEW_LINE> <INDENT> for obj in self.dv_destionations: <NEW_LINE> <INDENT> try:obj.setDV(self.dv) <NEW_LINE> except:print("Warning: object <%s> failed to accept DataVault connection. May be missing method <setDV>"%obj)
Sends the successful data vault connection to each specified object
625941de76d4e153a657ee7e
def _inverse_binarize_thresholding(y, output_type, classes, threshold): <NEW_LINE> <INDENT> if output_type == "binary" and y.ndim == 2 and y.shape[1] > 2: <NEW_LINE> <INDENT> raise ValueError("output_type='binary', but y.shape = {0}". format(y.shape)) <NEW_LINE> <DEDENT> if output_type != "binary" and y.shape[1] != len...
Inverse label binarization transformation using thresholding.
625941de293b9510aa2c35de
def read_audio(fname): <NEW_LINE> <INDENT> wav, sr = sf.read(fname) <NEW_LINE> assert sr == 16e3 <NEW_LINE> return wav, 16e3
Load an audio file and return PCM along with the sample rate
625941de91f36d47f21ac841
def testTrainableWeightsBehaveCorrectlyDuringPCQAT(self): <NEW_LINE> <INDENT> preserve_sparsity = True <NEW_LINE> clustered_model = self._get_clustered_model(preserve_sparsity) <NEW_LINE> clustered_model = cluster.strip_clustering(clustered_model) <NEW_LINE> quant_aware_annotate_model = ( quantize.quantize_annotate_mod...
PCQAT zero centroid masks stay the same and trainable variables are updating between epochs.
625941def7d966606f6aa354
def sanity_check_step(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.cfg['exts_list'] or self.cfg['sanity_check_paths'] or self.cfg['sanity_check_commands']: <NEW_LINE> <INDENT> super(Bundle, self).sanity_check_step(*args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.log.info("Testing loading of mo...
Nothing is being installed, so just being able to load the (fake) module is sufficient
625941decdde0d52a9e53381
def sumEvenAfterQueries(self, A, queries): <NEW_LINE> <INDENT> result = 0 <NEW_LINE> for val in A: <NEW_LINE> <INDENT> if val%2 == 0: <NEW_LINE> <INDENT> result += val <NEW_LINE> <DEDENT> <DEDENT> f_result = [] <NEW_LINE> for val_index in queries: <NEW_LINE> <INDENT> val, index = val_index[0], val_index[1] <NEW_LINE> p...
:type A: List[int] :type queries: List[List[int]] :rtype: List[int]
625941de460517430c3944c9
def test_missingTemplateLoaderRepr(self): <NEW_LINE> <INDENT> class PrettyReprElement(Element): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Pretty Repr Element' <NEW_LINE> <DEDENT> <DEDENT> self.assertIn('Pretty Repr Element', repr(MissingTemplateLoader(PrettyReprElement())))
A L{MissingTemplateLoader} instance can be repr()'d without error.
625941de5f7d997b87174de7
def print_parameters(self): <NEW_LINE> <INDENT> print('\n[info] printing parameters of segment ...') <NEW_LINE> print('\tlimits: [{}, {}]'.format(self.start, self.end)) <NEW_LINE> print('\treal limits: [{}, {}]'.format(self.vertices[0], self.vertices[-1])) <NEW_LINE> print('\tstretching ratio: {}'.format(self.stretch_r...
Prints the parameters of the segment.
625941de3d592f4c4ed1d3b2
def pandl_for_trading_rule(self, rule_variation_name, delayfill=True): <NEW_LINE> <INDENT> def _pandl_for_trading_rule( system, instrument_code_unused, rule_variation_name, this_stage, delayfill): <NEW_LINE> <INDENT> this_stage.log.terse( "Calculating pandl for trading rule %s" % rule_variation_name) <NEW_LINE> this_st...
Get the p&l for one trading rule over multiple instruments; as % of it's risk contribution Within the trading rule the instrument returns are weighted by instrument weight :param rule_variation_name: rule to get values for :type rule_variation_name: str :param delayfill: Lag fills by one day :type delayfill: bool :...
625941de711fe17d825426b0
def repair_actions(self, period, areaselector=None): <NEW_LINE> <INDENT> if areaselector is None: <NEW_LINE> <INDENT> areaselector = self.areaselector <NEW_LINE> <DEDENT> aa = copy.copy(self.applied_actions[period]) <NEW_LINE> self.reset_actions(period) <NEW_LINE> for acode in aa: <NEW_LINE> <INDENT> if not aa[acode]: ...
Attempts to repair the action schedule for given period, using an AreaSelector object (defaults to class-default areaselector, which is a simple greedy oldest-first selector).
625941de7b180e01f3dc4b43
@main.command('live-profile') <NEW_LINE> @live_profiler_params <NEW_LINE> @viewer_params <NEW_LINE> def live_profile(script, argv, timer, interval, spawn, signum, pickle_protocol, mono): <NEW_LINE> <INDENT> filename, code, globals_ = script <NEW_LINE> sys.argv[:] = [filename] + list(argv) <NEW_LINE> parent_sock, child_...
Profile a Python script continuously.
625941de8c3a87329515870a
def add_version_milestone_raw(self, project_id_or_key, form_parameters): <NEW_LINE> <INDENT> return self._request( '/projects/{}/versions'.format(project_id_or_key), method='POST', form_parameters=form_parameters)
Adds new Version/Milestone to the project. :param str project_id_or_key: Project ID or Project Key :param dict form_parameters: form_parameters :return: requests Response object :rtype: requests.Response
625941de6fb2d068a760f3ee
def traverse_friend_list(self): <NEW_LINE> <INDENT> response = TextResponse(url=self.driver.current_url , body=self.driver.page_source, encoding='utf-8') <NEW_LINE> friends_list_link = response.xpath('//div[@class="fsm fwn fcg"]/a[contains(@href, "friends")]/@href').extract_first() <NEW_LINE> print(friends_list_link) <...
Grabs the URL of link pointing to friends' list, goes to the grabbed URL and Traverses over the list of friends and grabs the profile URL of friends visible on the list. Returns: friends_list(List): A List containing URLs of all friends of a given user
625941dee64d504609d74b8c
def push(self, x): <NEW_LINE> <INDENT> self.first.append(x)
:type x: int :rtype: nothing
625941dee76e3b2f99f3ab53
def invoke(self, function_name, event, stdout=None, stderr=None): <NEW_LINE> <INDENT> function = self.provider.get(function_name) <NEW_LINE> if not function: <NEW_LINE> <INDENT> raise FunctionNotFound("Unable to find a Function with name '%s'", function_name) <NEW_LINE> <DEDENT> LOG.debug("Found one Lambda function wit...
Find the Lambda function with given name and invoke it. Pass the given event to the function and return response through the given streams. This function will block until either the function completes or times out. :param string function_name: Name of the Lambda function to invoke :param string event: Event data pass...
625941de1f5feb6acb0c4e97
def get_discussions_by_cashout(self, discussion_query: dict): <NEW_LINE> <INDENT> return self.exec('get_discussions_by_cashout', discussion_query, api='social_network')
get_discussions_by_cashout
625941de4f6381625f114d88
def hide_not_reveal_example(): <NEW_LINE> <INDENT> pass
>>> code_unit.inline_examples( ... ethan_joris_start_example.__doc__, ... locals(), globals(), ... verify_examples = False) >>> wait = 4.0 / joris._speed Joris does not have preview enabled. >>> joris.root.preview_gift_mc.enabled_mc.currentLabel 'none' >>> mouse_down_and_sleep(joris, joris.root._2_2_mc, ...
625941de099cdd3c635f0fa6
def enable(self, enable=True): <NEW_LINE> <INDENT> llogger = local_logger.LocalLogger() <NEW_LINE> llogger.log_method_call(self.__class__.__name__, sys._getframe().f_code.co_name) <NEW_LINE> if enable is False: <NEW_LINE> <INDENT> self.enabled = False <NEW_LINE> llogger.debug("The evaluation logger is disabled") <NEW_L...
Enables or disables the evaluation logger. If the log_ident or the log_folder is None the evaluation logger can't be enabled. :param enable: defines whether the evaluation logger should be enabled or disabled :return: new status of the evaluation logger
625941de7d847024c06be60b
def varsfile(path): <NEW_LINE> <INDENT> lines = None <NEW_LINE> with open(path) as fp: <NEW_LINE> <INDENT> lines = fp.readlines() <NEW_LINE> return dict({'SCRIPTPATH': values.src}, **{ key: val for (key, val) in [ l.split('=') for l in lines if l.strip() and not l.startswith('#') ] })
Does varsfile
625941dedc8b845886cb5883
def setlanguage(language: Optional[str], print_change: bool = True, store_to_config: bool = True) -> None: <NEW_LINE> <INDENT> cfg = _ba.app.config <NEW_LINE> cur_language = cfg.get('Lang', None) <NEW_LINE> if language != cur_language and store_to_config: <NEW_LINE> <INDENT> if language is None: <NEW_LINE> <INDENT> if ...
Set the active language used for the game. category: General Utility Functions Pass None to use OS default language.
625941dee5267d203edcdfe5
def retinanet( inputs, backbone_layers, num_classes, l_num_classes, num_anchors = 9, l_num_anchors = 9, create_pyramid_features = __create_pyramid_features, create_l_pyramid_features = __create_l_pyramid_features, submodels = None, name = 'retinanet' ): <NEW_LINE> ...
Construct a RetinaNet model on top of a backbone. This model is the minimum model necessary for training (with the unfortunate exception of anchors as output). Args inputs : keras.layers.Input (or list of) for the input to the model. num_classes : Number of classes to classify. ...
625941de26238365f5f0f1bf
def getLastEventDate(self, format=None): <NEW_LINE> <INDENT> cursor = self.cnx.cursor() <NEW_LINE> query = ("""SELECT MAX(date) FROM `tournaments`;""") <NEW_LINE> if format!= None: <NEW_LINE> <INDENT> query = ("SELECT MAX(date) FROM `tournaments` WHERE `format` = '"+format+"';") <NEW_LINE> <DEDENT> try: <NEW_LINE> <IND...
Retrieves the date of the event collected This method is useful for when there is weekly/daily collection so a script can pickup where it left off. Returns: A datetime date object.
625941de507cdc57c630702e
def test_get_image_details_by_status(self): <NEW_LINE> <INDENT> extra_fixture = {'id': 3, 'status': 'saving', 'is_public': True, 'disk_format': 'vhd', 'container_format': 'ovf', 'name': 'new name! #123', 'size': 19, 'checksum': None} <NEW_LINE> glance.registry.db.api.image_create(None, extra_fixture) <NEW_LINE> images ...
Tests that a detailed call can be filtered by status
625941de85dfad0860c3b1a9
def isMatch(self, s, p): <NEW_LINE> <INDENT> sP, pP, matchS, starP = 0, 0, 0, -1 <NEW_LINE> while sP < len(s): <NEW_LINE> <INDENT> if pP < len(p) and (p[pP] == '?' or s[sP] == p[pP]): <NEW_LINE> <INDENT> pP += 1 <NEW_LINE> sP += 1 <NEW_LINE> <DEDENT> elif pP < len(p) and p[pP] == '*': <NEW_LINE> <INDENT> starP = pP <NE...
:type s: str :type p: str :rtype: bool
625941de379a373c97cfae93
def display_files(self, cwd, index=-1): <NEW_LINE> <INDENT> self.cls.status = True <NEW_LINE> status_cwd() <NEW_LINE> self.cls.files = self.get_files(cwd) <NEW_LINE> self.cls.view = None <NEW_LINE> sublime.set_timeout( lambda: self.window.show_quick_panel( self.cls.files, self.check_selection, 0, index, on_highlight=se...
Display files in folder.
625941de4e4d5625662d4720
def _grindxpath(self, key_xpath, key_value): <NEW_LINE> <INDENT> simple = lambda: "[{}='{}']".format(key_xpath.replace("_", "-"), key_value) <NEW_LINE> composite = lambda: "[{}]".format( " and ".join( [ "{}='{}'".format(xp.replace("_", "-"), xv) for xp, xv in zip(key_xpath, key_value) ] ) ) <NEW_LINE> return simple() i...
returns xpath elements for key values
625941de1d351010ab855e68
@lru_cache(maxsize=1024) <NEW_LINE> def guess_company(path): <NEW_LINE> <INDENT> non_core_pythons = [impl for impl in PYTHON_IMPLEMENTATIONS if impl != "python"] <NEW_LINE> return next( iter(impl for impl in non_core_pythons if impl in path.lower()), "PythonCore" )
Given a path to python, guess the company who created it :param str path: The path to guess about :return: The guessed company :rtype: Optional[str]
625941de24f1403a92600eb0
def perform_final_action(args): <NEW_LINE> <INDENT> mapping = { "HISTORICAL": cruncher.make_plot, "RANDOM": cruncher.make_plot, "RECENT": lambda *args: logger.info("Finished") } <NEW_LINE> mapping[args.data_type](pre_rets, post_rets)
Depending on whether we are looking for historical or recent views, perform the last action
625941defb3f5b602dac39e3
def _on_conf_editor_notify_use_custom_font(self, *args): <NEW_LINE> <INDENT> font = gaupol.util.get_font() <NEW_LINE> for column in self.get_columns(): <NEW_LINE> <INDENT> renderer = column.get_cell_renderers()[0] <NEW_LINE> if hasattr(renderer.props, "font"): <NEW_LINE> <INDENT> renderer.props.font = font <NEW_LINE> <...
Apply the new font to all columns.
625941de7c178a314d6ef7b1
def test_asymmetric_key_encryption(self): <NEW_LINE> <INDENT> key = gen_symmetric_key() <NEW_LINE> ciphertext = asymmetric_encrypt_sign( key, self._client_pub_key2, self._server_priv_key1) <NEW_LINE> self.assertNotEqual(key, ciphertext) <NEW_LINE> deciphered = asymmetric_decrypt_verify( ciphertext, self._client_priv_ke...
Tests asymmetric key encryption
625941ded486a94d0b98e494
def config_ip4(self): <NEW_LINE> <INDENT> addr = self.local_ip4n <NEW_LINE> addr_len = 24 <NEW_LINE> self.test.vapi.sw_interface_add_del_address( self.sw_if_index, addr, addr_len)
Configure IPv4 address on the VPP interface
625941dea17c0f6771cbe39c
def map_language_code(self, code): <NEW_LINE> <INDENT> return code.replace("_", "-").lower()
Convert language to service specific code.
625941de60cbc95b062c6890
def find_raw(self, pattern, regex=False): <NEW_LINE> <INDENT> settings = [] <NEW_LINE> self.search_unzipped_files(settings, pattern, regex) <NEW_LINE> self.zipped_idx = len(settings) <NEW_LINE> self.search_zipped_files(settings, pattern, regex) <NEW_LINE> self.window.show_quick_panel( settings, lambda x: self.process_f...
Search all packages regardless of whether it is being overridden.
625941de3539df3088e2e697
@app.route('/api/categories') <NEW_LINE> def get_categories(): <NEW_LINE> <INDENT> categories = data_service.get_all_categories() <NEW_LINE> json = {'categories': categories} <NEW_LINE> return jsonify(json), 200
Returns a list of all categories
625941ded18da76e23532826
def create_user(self, email, password=None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError('Users must have an email address') <NEW_LINE> <DEDENT> user = self.model( email=self.normalize_email(email) ) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using=self._db) <NEW_LINE> FiveUs...
Creates and saves a User with the given email, date of birth and password.
625941de1b99ca400220adff
def test_api_file_get_admin(): <NEW_LINE> <INDENT> app = create_ctfd() <NEW_LINE> with app.app_context(): <NEW_LINE> <INDENT> chal = gen_challenge(app.db) <NEW_LINE> f = gen_file( app.db, location="0bf1a55a5cd327c07af15df260979668/bird.swf", challenge_id=chal.id, ) <NEW_LINE> assert Files.query.count() == 1 <NEW_LINE> ...
Can a user get /api/v1/files/<file_id> if admin
625941de7b25080760e397a5
def togrid(src, trg, radius, center, data, interpol, *args, **kwargs): <NEW_LINE> <INDENT> ix = extract_circle(center, radius, trg) <NEW_LINE> ip = interpol(src, trg[ix], *args, **kwargs) <NEW_LINE> data_on_subgrid = ip(data).reshape((len(ix))) <NEW_LINE> composegridshape = [len(trg)] <NEW_LINE> composegridshape.extend...
Interpolate data from a radar location to the composite grid or set of locations Parameters ---------- src : :class:`numpy:numpy.ndarray` array of float of shape (numpoints, ndim), cartesian x / y coordinates of the radar bins trg : :class:`numpy:numpy.ndarray` array of float of shape (numpoints, ndim)...
625941de5fc7496912cc3ccb
def categorical_to_rast_array(self, shapefile, col_name): <NEW_LINE> <INDENT> rast_array = rasterio.features.rasterize( [(shapefile.geometry[i], shapefile[col_name][i]) for i in range(len(shapefile))], out_shape=(self.ny, self.nx), transform=self.transform, default_value=0, fill=0, all_touched=True, dtype=rasterio.uint...
given a shapefile, convert to np array that is 0/1 of whether shapefile covers that grid
625941de30bbd722463cc114
def __init__(self, api, name, firstnext): <NEW_LINE> <INDENT> self.api = api <NEW_LINE> self.firstnext = firstnext <NEW_LINE> self._name = name <NEW_LINE> self._state = None <NEW_LINE> self.attributes = {}
Initialize.
625941de656771135c3ebbbf
def __init__(self, mainEngine): <NEW_LINE> <INDENT> self.historyData = mainEngine.historyData <NEW_LINE> self.eventEngine = mainEngine.eventEngine
Constructor
625941de498bea3a759b9dfb
def get_label_string(self, index_list): <NEW_LINE> <INDENT> blabel = [bool(x) for x in index_list] <NEW_LINE> blabel_string = list(compress(self.label_strings, blabel)) <NEW_LINE> return blabel_string
Returns the string for a boolean list for the label. See self.labels[0] for reference
625941debe8e80087fb20f8b
def test_19_pg_constraint_create_table_partition(self): <NEW_LINE> <INDENT> self.doTest('pg_constraint_create_table_partition.sql') <NEW_LINE> self.doTest('pg_constraint_create_table_partition_2.sql') <NEW_LINE> self.doTest('pg_constraint_create_table_partition_3.sql') <NEW_LINE> self.doTest('pg_constraint_create_table...
Oid_inconsistency : pg_constaint create partition table -oid
625941deadb09d7d5db6cada
def edge_added(self, source_id, time_id, edge_id, from_node, to_node, directed): <NEW_LINE> <INDENT> if not source_id is self.source_id: <NEW_LINE> <INDENT> self.set_source_id(source_id) <NEW_LINE> <DEDENT> buff = bytearray() <NEW_LINE> buff.extend(self.encode_byte(EVENT_ADD_EDGE)) <NEW_LINE> buff.extend(self.encode_st...
An edge was added.
625941de56b00c62f0f149a8
def importIitYarp(**kwargs): <NEW_LINE> <INDENT> importedDicts = importIitYarpRecursive(**kwargs) <NEW_LINE> if kwargs.get('zeroTime', kwargs.get('zeroTimestamps', True)): <NEW_LINE> <INDENT> rezeroTimestampsForImportedDicts(importedDicts) <NEW_LINE> <DEDENT> if len(importedDicts) == 1: <NEW_LINE> <INDENT> importedDict...
Import data in IIT Yarp format.
625941de66656f66f7cbc4f9
def add_notes_single(self, fields, tags='', model=None, deck=None): <NEW_LINE> <INDENT> if model is not None: <NEW_LINE> <INDENT> self.set_model(model) <NEW_LINE> <DEDENT> self._add_note(fields, tags, False, deck)
Add new note to collection from args
625941deab23a570cc2504d2
def _is_core_field(self, api_name): <NEW_LINE> <INDENT> return api_name in self.core_fields
True if this field is one that we should always include regardless of other settings or field configuration, such as Contact.FirstName. DB-level required fields don't need to be so handled.
625941deaad79263cf390d93
def get_data(self): <NEW_LINE> <INDENT> return self._data
(list<dict<str, *>>) Returns a list of all the records in the file
625941ded10714528d600034
def _find_pkgname_in_dist_dir(dist_dir: str) -> str: <NEW_LINE> <INDENT> pkgname = None <NEW_LINE> for f in os.listdir(dist_dir): <NEW_LINE> <INDENT> if f.endswith(".whl"): <NEW_LINE> <INDENT> new_pkgname = f.split("-")[0].replace("_", "-") <NEW_LINE> if pkgname and new_pkgname != pkgname: <NEW_LINE> <INDENT> raise Run...
Find the package name by looking at .whl files
625941de94891a1f4081bdf8
def set_boot_arch(arch="default"): <NEW_LINE> <INDENT> if arch not in ["i386", "x86_64", "default"]: <NEW_LINE> <INDENT> msg = ( "Invalid value passed for arch.\n" "Must be i386, x86_64, or default.\n" "Passed: {}".format(arch) ) <NEW_LINE> raise SaltInvocationError(msg) <NEW_LINE> <DEDENT> cmd = "systemsetup -setkerne...
Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down...
625941de8a349b6b435e84c0
def plot_mask(self, color="#dd2222", alpha=.66): <NEW_LINE> <INDENT> mask_data = self.stat_img.get_data()[self.x_slice, self.y_slice, self.z_slice] <NEW_LINE> bool_mask = mask_data.astype(bool) <NEW_LINE> mask_data = bool_mask.astype(np.float) <NEW_LINE> mask_data[~bool_mask] = np.nan <NEW_LINE> cmap = mpl.colors.Liste...
Plot the statistical volume as a binary mask.
625941de0c0af96317bb8535
def interface_port_channel_ip_ip_config_arp_aging_agtimeout(**kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> interface = ET.SubElement(config, "interface", xmlns="urn:brocade.com:mgmt:brocade-interface") <NEW_LINE> if kwargs.pop('delete_interface', False) is True: <NEW_LINE> <INDENT> delete_inter...
Auto Generated Code
625941de851cf427c661a859
def filter_word(text): <NEW_LINE> <INDENT> if text.lower() in STOPWORDS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Take out stopwords, punctuation, and compound endings.
625941de0a366e3fb873eb6a
def __init__(self, date, addConfirm, addSuspect, addDead, addHeal): <NEW_LINE> <INDENT> self.date = date <NEW_LINE> self.addConfirm = addConfirm <NEW_LINE> self.addSuspect = addSuspect <NEW_LINE> self.addDead = addDead <NEW_LINE> self.addHeal = addHeal
Info的初始化方法
625941de10dbd63aa1bd2ef0
def get_fake_values(cls, annotate=True, seed=None, n=None): <NEW_LINE> <INDENT> if hasattr(cls, 'lower'): <NEW_LINE> <INDENT> cls = class_by_name[cls] <NEW_LINE> <DEDENT> iseed = None <NEW_LINE> kwargs = {} <NEW_LINE> for i, attr in enumerate(cls._necessary_attrs + cls._recommended_attrs): <NEW_LINE> <INDENT> if seed i...
Returns a dict containing the default values for all attribute for a class from neo.core. If seed is not None, use the seed to set the random number generator. The seed is incremented by 1 for each successive object. If annotate is True (default), also add annotations to the values.
625941de63d6d428bbe4483d
def height(self, p=None): <NEW_LINE> <INDENT> if p is None: <NEW_LINE> <INDENT> p = self.root() <NEW_LINE> <DEDENT> return self._height2(p)
Return the height of the subtree rooted at Position p. if p is None, return the height of the entire tree.
625941de4527f215b584c7a1
def getKeyFeatures(string, ignore_string): <NEW_LINE> <INDENT> str_list = [i.replace(ignore_string, '').replace("'",'').replace('"','') for i in string.split('\n')] <NEW_LINE> str_list2 = [i for i in str_list if i != ''] <NEW_LINE> return str_list2
Return list of key features
625941ded8ef3951e324388b
def getOnly(self, **kwargs): <NEW_LINE> <INDENT> return self.get(get_only=True, **kwargs)
Fetches default Resource @param kwargs: keyword args @return: default Resource
625941de5510c4643540f72a
def close(self): <NEW_LINE> <INDENT> os.close(self.fd) <NEW_LINE> self.fd = None <NEW_LINE> self._paths = None <NEW_LINE> self._wds = None
Shut down this watcher. All subsequent method calls are likely to raise exceptions.
625941de38b623060ff0b13b
def cloud_choices(): <NEW_LINE> <INDENT> choices = [] <NEW_LINE> for (name, cloud) in Kamaki.get_clouds().items(): <NEW_LINE> <INDENT> descr = cloud['description'] if 'description' in cloud else '' <NEW_LINE> choices.append((name, descr)) <NEW_LINE> <DEDENT> return choices
Returns the available clouds
625941de2eb69b55b151cc01
def repeatedSubstringPattern(self, s): <NEW_LINE> <INDENT> for length in range(1, len(s) / 2 + 1): <NEW_LINE> <INDENT> if len(s) % length != 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> start = 0 <NEW_LINE> temp = None <NEW_LINE> is_equal = True <NEW_LINE> while start < len(s): <NEW_LINE> <INDENT> p = s[start:st...
:type s: str :rtype: bool
625941de8c0ade5d55d3ed0b
def __slot_currentItemChanged(self, item, col): <NEW_LINE> <INDENT> if item is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.current_img_preview = None <NEW_LINE> self.img_preview_progress_bar.hide() <NEW_LINE> self.abort_preview.emit() <NEW_LINE> data = item.data(0, QtCore.Qt.UserRole) <NEW_LINE> user_has_...
Handles the QTreeWidget currentItemChanged event.
625941de6aa9bd52df0370f3
def _check_maintainers(self, pkg, loc, doc): <NEW_LINE> <INDENT> if self.options.gentoo_repo: <NEW_LINE> <INDENT> maintainer_needed = any( c.text.strip() == 'maintainer-needed' for c in doc.xpath('//comment()')) <NEW_LINE> if pkg.maintainers: <NEW_LINE> <INDENT> if maintainer_needed: <NEW_LINE> <INDENT> yield Maintaine...
Validate maintainers in package metadata for the gentoo repo.
625941de5166f23b2e1a54a7
def p_comma_pow_vfpdef(self, p): <NEW_LINE> <INDENT> p[0] = p[3]
comma_pow_vfpdef : COMMA POW vfpdef
625941dec4546d3d9de72d84
def id_to_object(self, line): <NEW_LINE> <INDENT> user = User.get(line, ignore=404) <NEW_LINE> if not user: <NEW_LINE> <INDENT> user = User(username=line) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> return user
Resolves the given id to a user object, if it doesn't exists it will be created.
625941de97e22403b379d2e9
def verify_output(self, bson_metrics_file_name, expected_results, check_last_row_only=False): <NEW_LINE> <INDENT> with open(bson_metrics_file_name, 'rb') as f: <NEW_LINE> <INDENT> options = CodecOptions(document_class=OrderedDict) <NEW_LINE> index = 0 <NEW_LINE> if check_last_row_only: <NEW_LINE> <INDENT> decoded_bson ...
:param bson_metrics_file_name: :param expected_results: :param check_last_row_only: Check that the last row is correct. Since the results are cumulative, this likely means previous rows are all correct as well. :return:
625941ded164cc617578309d
def processTicket(): <NEW_LINE> <INDENT> global origin_data <NEW_LINE> origin_data['TicketPrefix'] = origin_data['Ticket'].map(lambda x: getRepr(x.upper(),"([a-zA-Z\.\/]+)",'U')) <NEW_LINE> origin_data['TicketPrefix'] = origin_data['TicketPrefix'].map(lambda x:re.sub('[\.?\/?]','',x)) <NEW_LINE> origin_data['TicketPref...
处理票单号 :param origin_data: :return:
625941de8e71fb1e9831daf6
def get_user_option(self, option_name, expand=True): <NEW_LINE> <INDENT> value = self._get_user_option(option_name) <NEW_LINE> if expand: <NEW_LINE> <INDENT> if isinstance(value, list): <NEW_LINE> <INDENT> value = self._expand_options_in_list(value) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> ...
Get a generic option - no special process, no default. :param option_name: The queried option. :param expand: Whether options references should be expanded. :returns: The value of the option.
625941de26068e7796caf031
def _reflected_emitted_curve(phase, F0, Aplanet, phase_shift): <NEW_LINE> <INDENT> return F0 - Aplanet*np.cos(2.*np.pi*(phase - phase_shift))
Returns sinusoidal reflection curve Args: phase (numpy array): orbital phase F0 (float): zero-point for phase curve Aplanet (float): phase curve amplitude phase_shift (float): phase curve shift
625941deb5575c28eb68e351
def sanitize(s): <NEW_LINE> <INDENT> return "".join([c for c in s if (31 < ord(c) < 127) or (c == '\n')])
Removes all ASCII control characters but newlines.
625941decdde0d52a9e53383
def count_assigned_targets_guide(self): <NEW_LINE> <INDENT> no_assigned_targets = len(self.get_assigned_targets_guide()) <NEW_LINE> return no_assigned_targets
Count the number of guide targets assigned to this tile. Returns ------- no_assigned_targets : int The number of guide targets assigned to this tile.
625941de8a349b6b435e84c1
def testPaymentInvoiceApplicationItemCreateRequestType(self): <NEW_LINE> <INDENT> pass
Test PaymentInvoiceApplicationItemCreateRequestType
625941de8e7ae83300e4b31c
def binary_search(lis, item): <NEW_LINE> <INDENT> fst = 0 <NEW_LINE> lst = len(lis)-1 <NEW_LINE> while fst <= lst: <NEW_LINE> <INDENT> mid = (fst + lst)//2 <NEW_LINE> if lis[mid] == item: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if item < lis[mid]: <NEW_LINE> <INDENT> lst = mid-1 <N...
Binary search alfgorithm that should run faster over large data sets than a linear search. :param lis: list of items to search :param item: item that you search for :return: a boolean
625941dea05bb46b383ecb6e
def test_jt_superuser(self): <NEW_LINE> <INDENT> self.client.login(username='test_admin', password='admin') <NEW_LINE> self.client.get('/leave_team/1/test_user2/') <NEW_LINE> self.assertNotIn(Player.objects.get(username='test_user2'), Team.objects.get(teamID=1).players.all()) <NEW_LINE> self.client.get('/join_team/1/te...
superuser should be able to add anyone to a team
625941dee76e3b2f99f3ab55
def calc_snr(region, evt, bkg=None, elow=700, ehigh=7000, elow_pb=9500, ehigh_pb=12000): <NEW_LINE> <INDENT> if bkg is None: <NEW_LINE> <INDENT> return math.inf <NEW_LINE> <DEDENT> tf1 = tempfile.NamedTemporaryFile() <NEW_LINE> tf2 = tempfile.NamedTemporaryFile() <NEW_LINE> extract_spec(tf1.name, evtfile=evt, region=re...
Calculate the signal-to-noise ratio (SNR) for the source spectrum with respect to the background spectrum, with particle background renormalization considered. The source and background spectra are extracted from the corresponding event files within the given region. NOTE ---- * If the given background is already a s...
625941def9cc0f698b140947
def secondPageHasNext(self, url): <NEW_LINE> <INDENT> c = self.get(url) <NEW_LINE> sel = etree.HTML(c) <NEW_LINE> l = sel.xpath('//tr/td[@align="center"]/a/@href') <NEW_LINE> if len(l) == 2: <NEW_LINE> <INDENT> return 'http://www.dali.gov.cn/' + l[0] <NEW_LINE> <DEDENT> return ''
http://www.dali.gov.cn//dlzwz/5117219530480812032/index.html 提取包含'下一页'的链接 :param url: :return:
625941de283ffb24f3c55c4c
def GetStatus(self): <NEW_LINE> <INDENT> STATUS_FORMAT = ">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH" <NEW_LINE> STATUS_FIELDS = [ "packetType", "firmwareVersion", "protocolVersion", "mainFineCurrent", "usbFineCurrent", "auxFineCurrent", "voltage1", "mainCoarseCurrent", "usbCoarseCurrent", "auxCoarseCurrent", "voltage...
Requests and waits for status. Returns status dictionary.
625941de4a966d76dd551360
def _default_location_destination(self, cr, uid, context=None): <NEW_LINE> <INDENT> location_id = False <NEW_LINE> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> if context.get('move_line', []): <NEW_LINE> <INDENT> if context['move_line'][0]: <NEW_LINE> <INDENT> if isinstance(context['move_lin...
Gets default address of partner for destination location @return: Address id or False
625941de73bcbd0ca4b2c3c4
def flip_history(player: Player) -> None: <NEW_LINE> <INDENT> new_history = [action.flip() for action in player.history] <NEW_LINE> player.history = new_history
Flips all the actions in `player.history`.
625941de23e79379d52ee8ae
def test_2040_chunked_size_overflow(self): <NEW_LINE> <INDENT> self.real_test = "{0}_{1}".format(inspect.stack()[0][3], self.nb) <NEW_LINE> method = self._get_valid_chunk_method() <NEW_LINE> self.req.set_method(method) <NEW_LINE> self.setGravity(self.GRAVITY_CRITICAL) <NEW_LINE> self.req.add_header('Transfer-Encoding',...
Try an int overflow on the chunk size
625941de4428ac0f6e5bab43
def __generarReferencias(self, atributos): <NEW_LINE> <INDENT> un_atributo_clase = '' <NEW_LINE> for index in range(len(atributos)): <NEW_LINE> <INDENT> atributo = atributos[index] <NEW_LINE> if atributo['referencia'] != '': <NEW_LINE> <INDENT> un_atributo_clase = ' %s_id = Int()\n %s = Reference(%s_id, %s.ide)\n...
A partir de los datos de los atributos verifica si es necesario generar la cadena de atributos de clase que contienen referencias.
625941de462c4b4f79d1da1f
@click.group(name="device") <NEW_LINE> def cli_device(): <NEW_LINE> <INDENT> pass
Commands to see details of device: list
625941dea219f33f34628cb4
def __init__( self, method: Callable[..., reservation.SearchAssignmentsResponse], request: reservation.SearchAssignmentsRequest, response: reservation.SearchAssignmentsResponse, *, metadata: Sequence[Tuple[str, str]] = () ): <NEW_LINE> <INDENT> self._method = method <NEW_LINE> self._request = reservation.SearchAssignme...
Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.bigquery_reservation_v1.types.SearchAssignmentsRequest): The initial request object. response (google.cloud.bigquery_reservation_v1.types.SearchAss...
625941de26238365f5f0f1c1
def write_all_registers(self): <NEW_LINE> <INDENT> lst = list(self.reg.addresses) <NEW_LINE> lst.sort() <NEW_LINE> lst.reverse() <NEW_LINE> for addr in lst: <NEW_LINE> <INDENT> self.write_reg(addr, self.reg[addr].value) <NEW_LINE> <DEDENT> self.write_reg(0x00, self.reg[0x00].value)
write every register starting with the highest address, writing addr 0x00 last
625941de7d847024c06be60e
def rpcf_user5_enable_turbo_mode(self, params): <NEW_LINE> <INDENT> if not self.urfa_call(-0x1200a): <NEW_LINE> <INDENT> raise Exception("Fail of urfa_call(-0x1200a) [rpcf_user5_enable_turbo_mode]") <NEW_LINE> <DEDENT> self.pck.init(code = U_PKT_DATA) <NEW_LINE> self.pck.add_data(params['slink_id'], U_TP_I) <NEW_LINE> ...
description @params: :(s) slink_id : (i) - @returns: :(s) result : (i) -
625941debf627c535bc1351e
def split_filename(filename: str) -> (str, str): <NEW_LINE> <INDENT> _esep_ = Pref._esep_ <NEW_LINE> filename_split = filename.split(_esep_) <NEW_LINE> name = _esep_.join(filename_split[:-1]) <NEW_LINE> extension = filename_split[-1] <NEW_LINE> return name, extension
This function splits a file's full name into its name and its extension. :param filename: The file's full name :return: The file's name and the file's extension
625941de6aa9bd52df0370f4
def l2_proj(eps, input, axes=None): <NEW_LINE> <INDENT> axes = util._normalize_axes(axes, input.ndim) <NEW_LINE> xp = backend.get_array_module(input) <NEW_LINE> norm = xp.sum(xp.abs(input)**2, axis=axes, keepdims=True)**0.5 <NEW_LINE> mask = norm < eps <NEW_LINE> output = mask * input + (1 - mask) * (eps * input / (nor...
Projection onto L2 ball. Args: eps (float, or array): L2 ball scaling. input (array) Returns: array: Result.
625941de507cdc57c6307030
def marshall_lines(self, collector): <NEW_LINE> <INDENT> if isinstance(collector, collectors.Counter): <NEW_LINE> <INDENT> exec_method = self._format_counter <NEW_LINE> <DEDENT> elif isinstance(collector, collectors.Gauge): <NEW_LINE> <INDENT> exec_method = self._format_gauge <NEW_LINE> <DEDENT> elif isinstance(collect...
Marshalls a collector and returns the storage/transfer format in a tuple, this tuple has reprensentation format per element.
625941de76e4537e8c3519c3
def make_enumeration_declarations_and_definitions(enumeration_type): <NEW_LINE> <INDENT> declarations = declarations_template.format( type=enumeration_type, width_expression=math_parser.str_expression(enumeration_type.width), ) <NEW_LINE> template_fn = os.path.join(os.path.dirname(__file__), 'templates', 'slvcodec_enum...
Create declarations and definitions of functions to convert to and from enumeration types.
625941de3cc13d1c6d3c76c8
def _compute_numstats( self, col, grouping, where, values, constraint=None, threshold=None, suffix="", silent=False, ): <NEW_LINE> <INDENT> if not silent: <NEW_LINE> <INDENT> self._print_statmsg([col], constraint, threshold, grouping=grouping) <NEW_LINE> <DEDENT> if threshold is None: <NEW_LINE> <INDENT> having = SQL("...
Computes statistics on a single numerical column, grouped by the values of another set of columns. This function is used by add_numstats to compute the statistics to add. INPUT: - ``col`` -- as for ``add_numstats`` - ``grouping`` -- as for ``add_numstats`` - ``where`` -- as output by ``_process_constraint`` - ``valu...
625941ded4950a0f3b08c699
def raise_errors(self): <NEW_LINE> <INDENT> if self._error is not None: <NEW_LINE> <INDENT> raise OSError(self._error)
Raise an exceptions if any errors have been found while parsing the Sphinx output. EXAMPLES:: sage: from sys import stdout sage: from sage_docbuild.sphinxbuild import SageSphinxLogger sage: logger = SageSphinxLogger(stdout, "doctesting") sage: logger._log_line("This is a SEVERE error\n") [doctesti...
625941de379a373c97cfae95